@malloydata/render 0.0.248-dev250325235002 → 0.0.248

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.
@@ -1419,7 +1419,7 @@ ${(0,iet.indent)(r)}
1419
1419
  $$ LANGUAGE SQL;
1420
1420
  `}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
1421
1421
  `}sqlSelectAliasAsStruct(e,r){return"MYSQL: Implement this"}sqlMaybeQuoteIdentifier(e){return"`"+e.replace(/`/g,"``")+"`"}sqlCreateTableAsSelect(e,r){throw new Error("Not implemented Yet")}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTruncExpr(e,r){let i=r.e.sql||"why could this be undefined";if(r.units==="week"&&(i=`DATE_SUB(${i}, INTERVAL DAYOFWEEK(${i}) - 1 DAY)`),Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,eE.qtz)(e);if(o){const u=`(CONVERT_TZ(${i}, 'UTC','${o}'))`;return`(${`CONVERT_TZ(${`${this.truncToUnit(u,r.units)}`}, '${o}', 'UTC')`})`}}return`${this.truncToUnit(i,r.units)}`}truncToUnit(e,r){let i="'%Y-%m-%d %H:%i:%s'";switch(r){case"minute":i="'%Y-%m-%d %H:%i:00'";break;case"hour":i="'%Y-%m-%d %H:00:00'";break;case"day":case"week":i="'%Y-%m-%d 00:00:00'";break;case"month":i="'%Y-%m-01 00:00:00'";break;case"quarter":i=`CASE WHEN MONTH(${e}) > 9 THEN '%Y-10-01 00:00:00' WHEN MONTH(${e}) > 6 THEN '%Y-07-01 00:00:00' WHEN MONTH(${e}) > 3 THEN '%Y-04-01 00:00:00' ELSE '%Y-01-01 00:00:00' end`;break;case"year":i="'%Y-01-01 00:00:00'";break}return`TIMESTAMP(DATE_FORMAT(${e}, ${i}))`}sqlTimeExtractExpr(e,r){const i=uet[r.units]||r.units;let s=r.e.sql;if(Wc.TD.isTimestamp(r.e.typeDef)){const o=(0,eE.qtz)(e);o&&(s=`CONVERT_TZ(${s}, 'UTC', '${o}')`)}return`${i}(${s})`}sqlAlterTimeExpr(e){let r=e.units,i=e.kids.delta.sql;r==="quarter"?(r="month",i=`${i}*3`):r==="week"&&(r="day",i=`${i}*7`);const s=`INTERVAL ${i} ${r} `;return`(${e.kids.base.sql})${e.op}${s}`}sqlCast(e,r){const i=r.e.sql||"internal-error-in-sql-generation",{op:s,srcTypeDef:o,dstTypeDef:u,dstSQLType:a}=this.sqlCastPrep(r),l=(0,eE.qtz)(e);if(s==="timestamp::date"&&l)return`CAST(CONVERT_TZ(${i}, 'UTC', '${l}') AS DATE) `;if(s==="date::timestamp"&&l)return` CONVERT_TZ(${i}, '${l}', 'UTC')`;if(!Wc.TD.eq(o,u)){if(r.safe)throw new Error("Mysql dialect doesn't support Safe Cast");return Wc.TD.isString(u)?`CONCAT(${i}, '')`:`CAST(${i} AS ${a})`}return i}sqlRegexpMatch(e){return`REGEXP_LIKE(${e.kids.expr.sql}, ${e.kids.regex.sql})`}sqlLiteralTime(e,r){if(Wc.TD.isDate(r.typeDef))return`DATE '${r.literal}'`;const i=r.timezone||(0,eE.qtz)(e);return i?` CONVERT_TZ('${r.literal}', '${i}', 'UTC')`:`TIMESTAMP '${r.literal}'`}sqlMeasureTimeExpr(e){let r=e.kids.left.sql,i=e.kids.right.sql;if(ale[e.units]){r=`UNIX_TIMESTAMP(${r})`,i=`UNIX_TIMESTAMP(${i})`;const s=`${i}-${r}`;return e.units==="second"?`FLOOR(${s})`:`FLOOR((${s})/${ale[e.units].toString()}.0)`}throw new Error(`Unknown or unhandled MySQL time unit: ${e.units}`)}sqlAggDistinct(e,r,i){throw new Error("MySQL dialect does not support nesting.")}sqlSampleTable(e,r){if(r!==void 0){if((0,Wc.isSamplingEnable)(r)&&r.enable&&(r=this.defaultSampling),(0,Wc.isSamplingRows)(r))return`(SELECT * FROM ${e} ORDER BY rand() LIMIT ${r.rows} )`;if((0,Wc.isSamplingPercent)(r))return`(SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY rand()) as __row_number, __source_tbl.* from ${e} as __source_tbl) as __rand_tbl where __row_number % FLOOR(100.0 / ${r.percent}) = 1)`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getDialectFunctionOverrides(){return(0,ule.expandOverrideMap)(oet.MYSQL_MALLOY_STANDARD_OVERLOADS)}getDialectFunctions(){return(0,ule.expandBlueprintMap)(set.MYSQL_DIALECT_FUNCTIONS)}mapFieldsForJsonObject(e,r){return e.map(i=>`${i.sqlOutputName.replace(/`/g,"'")}, ${r?"NULL":i.sqlExpression}
1422
- `).join(", ")}castToString(e){return`CONCAT(${e}, '')`}concat(...e){return`CONCAT(${e.join(",")})`}validateTypeName(e){return e.match(/^[A-Za-z\s(),0-9]*$/)!==null}sqlLiteralArray(e){return`JSON_ARRAY(${e.kids.values.map(i=>i.sql).join(",")})`}sqlLiteralRecord(e){return`JSON_OBJECT(${Object.entries(e.kids).map(([i,s])=>`${this.sqlLiteralString(i)},${s.sql}`).join(", ")})`}}F4.MySQLDialect=cet,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(F4,t)}(hB);var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.getDialects=Ma.registerDialect=Ma.getDialect=void 0;const fet=sB,xet=nB,det=aB,het=V$,lle=cB,pet=hB,mB=new Map;function met(t){const e=mB.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}Ma.getDialect=met;function Gc(t){mB.set(t.name,t)}Ma.registerDialect=Gc;function get(){return[...mB.values()]}Ma.getDialects=get,Gc(new xet.PostgresDialect),Gc(new het.StandardSQLDialect),Gc(new fet.DuckDBDialect),Gc(new det.SnowflakeDialect),Gc(new lle.TrinoDialect),Gc(new lle.PrestoDialect),Gc(new pet.MySQLDialect),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TinyParser=t.getMalloyStandardFunctions=t.registerDialect=t.getDialect=t.MySQLDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.variadicParam=t.param=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=lt;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return e.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var r=qc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=V$;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=nB;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=sB;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var u=aB;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return u.SnowflakeDialect}});var a=cB;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return a.TrinoDialect}});var l=hB;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Ma;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=Qc;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var x=Cd;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return x.TinyParser}})}(p2);var Yi={},Hs={},A2={},gi={};Object.defineProperty(gi,"__esModule",{value:!0}),gi.annotationToTag=gi.annotationToTaglines=gi.addModelScope=void 0;const cle=$o;function yet(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}gi.addModelScope=yet;function fle(t,e){t||(t={});const r=t.inherits?fle(t.inherits,e):[];function i(s){const o=[];for(const u of s||[])(e===void 0||u.text.match(e))&&o.push(u.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}gi.annotationToTaglines=fle;function xle(t,e={}){var r;let i=e.extending||new cle.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=xle(t.inherits,e);o.push(...l.log),i=l.tag}const u=[];t.blockNotes&&u.push(...t.blockNotes),t.notes&&u.push(...t.notes);const a=[];for(const l of u)l.text.match(s)&&a.push(l);for(let l=0;l<a.length;l++){const c=a[l];if(c.text.match(s)){const f=cle.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(x=>Eet(x,c)))}}return{tag:i,log:o}}gi.annotationToTag=xle;function Eet(t,e){const r={line:e.at.range.start.line,character:e.at.range.start.character+t.offset};return{code:"tag-parse-error",severity:"error",message:t.message,at:{url:e.at.url,range:{start:r,end:r}}}}Object.defineProperty(A2,"__esModule",{value:!0}),A2.buildQueryMaterializationSpec=A2.shouldMaterialize=void 0;const Aet=kt,_et=gi;function vet(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,_et.annotationToTag)(e).tag.has("materialize")}A2.shouldMaterialize=vet;function Cet(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,Aet.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}A2.buildQueryMaterializationSpec=Cet;var dle={},I4={},wn={};Object.defineProperty(wn,"__esModule",{value:!0}),wn.isFilterable=wn.isFilterExpression=wn.isTemporalFilter=wn.isNumberFilter=wn.isBooleanFilter=wn.isStringFilter=wn.isStringCondition=wn.isChainOp=void 0;function bet(t){return["and","or",","].includes(t)}wn.isChainOp=bet;function Tet(t){return["starts","ends","contains","="].includes(t.operator)}wn.isStringCondition=Tet;function Ret(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}wn.isStringFilter=Ret;function Det(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}wn.isBooleanFilter=Det;function Oet(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}wn.isNumberFilter=Oet;function wet(t){return"operator"in t&&typeof t.operator=="string"&&["literal","before","after","to","for","in","and","or","in_last","this","last","next","()","null"].includes(t.operator)}wn.isTemporalFilter=wet;function Fet(t){return"operator"in t}wn.isFilterExpression=Fet;function Net(t){return["string","number","boolean","timestamp","date"].includes(t)}wn.isFilterable=Net;var $4={};Object.defineProperty($4,"__esModule",{value:!0}),$4.BooleanFilterExpression=void 0,$4.BooleanFilterExpression={parse(t){var e;const r={parsed:null,log:[]};let i=t.toLowerCase().trim().replace(/\s\s+/," "),s=!1;if(i.startsWith("not ")&&(s=!0,i=i.slice(4)),i==="true")r.parsed={operator:"true"};else if(i==="false")r.parsed={operator:"false_or_null"};else if(i==="=false")r.parsed={operator:"false"};else if(i==="null")r.parsed={operator:"null"};else if(i==="not null")r.parsed={operator:"null",not:!0};else{const o=t.match(/[^\s]/),u=o&&(e=o.index)!==null&&e!==void 0?e:0;r.log=[{message:"Illegal boolean filter. Must be one of true,false,=false,null,not null",severity:"error",startIndex:u,endIndex:u+t.length-1}]}return s&&r.parsed&&(r.parsed.not=!0),r},unparse(t){if(t===null)return"";const e=t.not?"not ":"";switch(t.operator){case"true":case"null":return e+t.operator;case"false_or_null":return e+"false";case"false":return e+"=false"}}};var hle={},ple={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(T,function(){function e(c,f,x){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=x,this}e.highestId=0,e.prototype.toString=function(c){var f=typeof c>"u"?this.symbols.map(l).join(" "):this.symbols.slice(0,c).map(l).join(" ")+" ● "+this.symbols.slice(c).map(l).join(" ");return this.name+" → "+f};function r(c,f,x,h){this.rule=c,this.dot=f,this.reference=x,this.data=[],this.wantedBy=h,this.isComplete=this.dot===c.symbols.length}r.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},r.prototype.nextState=function(c){var f=new r(this.rule,this.dot+1,this.reference,this.wantedBy);return f.left=this,f.right=c,f.isComplete&&(f.data=f.build(),f.right=void 0),f},r.prototype.build=function(){var c=[],f=this;do c.push(f.right.data),f=f.left;while(f.left);return c.reverse(),c},r.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,u.fail))};function i(c,f){this.grammar=c,this.index=f,this.states=[],this.wants={},this.scannable=[],this.completed={}}i.prototype.process=function(c){for(var f=this.states,x=this.wants,h=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==u.fail){for(var y=m.wantedBy,g=y.length;g--;){var E=y[g];this.complete(E,m)}if(m.reference===this.index){var A=m.rule.name;(this.completed[A]=this.completed[A]||[]).push(m)}}}else{var A=m.rule.symbols[m.dot];if(typeof A!="string"){this.scannable.push(m);continue}if(x[A]){if(x[A].push(m),h.hasOwnProperty(A))for(var _=h[A],g=0;g<_.length;g++){var v=_[g];this.complete(m,v)}}else x[A]=[m],this.predict(A)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],x=0;x<f.length;x++){var h=f[x],p=this.wants[c],m=new r(h,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var x=c.nextState(f);this.states.push(x)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var x=this.byName={};this.rules.forEach(function(h){x.hasOwnProperty(h.name)||(x[h.name]=[]),x[h.name].push(h)})}s.fromCompiled=function(h,f){var x=h.Lexer;h.ParserStart&&(f=h.ParserStart,h=h.ParserRules);var h=h.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(h,f);return p.lexer=x,p};function o(){this.reset("")}o.prototype.reset=function(c,f){this.buffer=c,this.index=0,this.line=f?f.line:1,this.lastLineBreak=f?-f.col:0},o.prototype.next=function(){if(this.index<this.buffer.length){var c=this.buffer[this.index++];return c===`
1422
+ `).join(", ")}castToString(e){return`CONCAT(${e}, '')`}concat(...e){return`CONCAT(${e.join(",")})`}validateTypeName(e){return e.match(/^[A-Za-z\s(),0-9]*$/)!==null}sqlLiteralArray(e){return`JSON_ARRAY(${e.kids.values.map(i=>i.sql).join(",")})`}sqlLiteralRecord(e){return`JSON_OBJECT(${Object.entries(e.kids).map(([i,s])=>`${this.sqlLiteralString(i)},${s.sql}`).join(", ")})`}}F4.MySQLDialect=cet,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(F4,t)}(hB);var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.getDialects=Ma.registerDialect=Ma.getDialect=void 0;const fet=sB,xet=nB,det=aB,het=V$,lle=cB,pet=hB,mB=new Map;function met(t){const e=mB.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}Ma.getDialect=met;function Gc(t){mB.set(t.name,t)}Ma.registerDialect=Gc;function get(){return[...mB.values()]}Ma.getDialects=get,Gc(new xet.PostgresDialect),Gc(new het.StandardSQLDialect),Gc(new fet.DuckDBDialect),Gc(new det.SnowflakeDialect),Gc(new lle.TrinoDialect),Gc(new lle.PrestoDialect),Gc(new pet.MySQLDialect),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TinyParser=t.getMalloyStandardFunctions=t.registerDialect=t.getDialect=t.MySQLDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.variadicParam=t.param=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=lt;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"variadicParam",{enumerable:!0,get:function(){return e.variadicParam}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var r=qc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return r.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return r.qtz}});var i=V$;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return i.StandardSQLDialect}});var s=nB;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return s.PostgresDialect}});var o=sB;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return o.DuckDBDialect}});var u=aB;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return u.SnowflakeDialect}});var a=cB;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return a.TrinoDialect}});var l=hB;Object.defineProperty(t,"MySQLDialect",{enumerable:!0,get:function(){return l.MySQLDialect}});var c=Ma;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return c.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return c.registerDialect}});var f=Qc;Object.defineProperty(t,"getMalloyStandardFunctions",{enumerable:!0,get:function(){return f.getMalloyStandardFunctions}});var x=Cd;Object.defineProperty(t,"TinyParser",{enumerable:!0,get:function(){return x.TinyParser}})}(p2);var Yi={},Hs={},A2={},gi={};Object.defineProperty(gi,"__esModule",{value:!0}),gi.annotationToTag=gi.annotationToTaglines=gi.addModelScope=void 0;const cle=$o;function yet(t,e){const r=t?{...t}:{};return r.scopes?r.scopes=r.scopes.concat(e):r.scopes=[e],r}gi.addModelScope=yet;function fle(t,e){t||(t={});const r=t.inherits?fle(t.inherits,e):[];function i(s){const o=[];for(const u of s||[])(e===void 0||u.text.match(e))&&o.push(u.text);return o}return r.concat(i(t.blockNotes),i(t.notes))}gi.annotationToTaglines=fle;function xle(t,e={}){var r;let i=e.extending||new cle.Tag;const s=e.prefix||/^##? /;t||(t={});const o=[];if(t.inherits){const l=xle(t.inherits,e);o.push(...l.log),i=l.tag}const u=[];t.blockNotes&&u.push(...t.blockNotes),t.notes&&u.push(...t.notes);const a=[];for(const l of u)l.text.match(s)&&a.push(l);for(let l=0;l<a.length;l++){const c=a[l];if(c.text.match(s)){const f=cle.Tag.fromTagLine(c.text,l,i,...(r=e.scopes)!==null&&r!==void 0?r:[]);i=f.tag,o.push(...f.log.map(x=>Eet(x,c)))}}return{tag:i,log:o}}gi.annotationToTag=xle;function Eet(t,e){const r={line:e.at.range.start.line,character:e.at.range.start.character+t.offset};return{code:"tag-parse-error",severity:"error",message:t.message,at:{url:e.at.url,range:{start:r,end:r}}}}Object.defineProperty(A2,"__esModule",{value:!0}),A2.buildQueryMaterializationSpec=A2.shouldMaterialize=void 0;const Aet=kt,_et=gi;function vet(t){const e=structuredClone(t);return e&&(e.inherits=void 0),(0,_et.annotationToTag)(e).tag.has("materialize")}A2.shouldMaterialize=vet;function Cet(t,e,r){if(!e)throw new Error(`Query tagged to materialize, but its name is not specified. ${t}`);if(!t)throw new Error(`Query tagged to materialize, but its path is not specified: ${e}`);const i={path:t,source:void 0,queryName:e},s=(0,Aet.generateHash)(JSON.stringify(i)).replace(/-/g,"_"),o=`${r?`${r}_`:""}${e}_${s}`;return{...i,id:o}}A2.buildQueryMaterializationSpec=Cet;var dle={},I4={},wn={};Object.defineProperty(wn,"__esModule",{value:!0}),wn.isFilterable=wn.isFilterExpression=wn.isTemporalFilter=wn.isNumberFilter=wn.isBooleanFilter=wn.isStringFilter=wn.isStringCondition=wn.isChainOp=void 0;function bet(t){return["and","or",","].includes(t)}wn.isChainOp=bet;function Tet(t){return["starts","ends","contains","="].includes(t.operator)}wn.isStringCondition=Tet;function Ret(t){return"operator"in t&&typeof t.operator=="string"&&["starts","ends","contains","=","~","null","empty","and","or",",","()"].includes(t.operator)}wn.isStringFilter=Ret;function Det(t){return"operator"in t&&typeof t.operator=="string"&&["null","true","false","false_or_null"].includes(t.operator)}wn.isBooleanFilter=Det;function Oet(t){return"operator"in t&&typeof t.operator=="string"&&["range","<=",">=","!=","=",">","<","and","or","()","null"].includes(t.operator)}wn.isNumberFilter=Oet;function wet(t){return"operator"in t&&typeof t.operator=="string"&&["literal","before","after","to","for","in","and","or","in_last","this","last","next","()","null"].includes(t.operator)}wn.isTemporalFilter=wet;function Fet(t){return"operator"in t}wn.isFilterExpression=Fet;function Net(t){return["string","number","boolean","timestamp","date"].includes(t)}wn.isFilterable=Net;var $4={};Object.defineProperty($4,"__esModule",{value:!0}),$4.BooleanFilterExpression=void 0,$4.BooleanFilterExpression={parse(t){var e;if(t.match(/^\s*$/))return{parsed:null,log:[]};const r={parsed:null,log:[]};let i=t.toLowerCase().trim().replace(/\s\s+/," "),s=!1;if(i.startsWith("not ")&&(s=!0,i=i.slice(4)),i==="true")r.parsed={operator:"true"};else if(i==="false")r.parsed={operator:"false_or_null"};else if(i==="=false")r.parsed={operator:"false"};else if(i==="null")r.parsed={operator:"null"};else if(i==="not null")r.parsed={operator:"null",not:!0};else{const o=t.match(/[^\s]/),u=o&&(e=o.index)!==null&&e!==void 0?e:0;r.log=[{message:"Illegal boolean filter. Must be one of true,false,=false,null,not null",severity:"error",startIndex:u,endIndex:u+t.length-1}]}return s&&r.parsed&&(r.parsed.not=!0),r},unparse(t){if(t===null)return"";const e=t.not?"not ":"";switch(t.operator){case"true":case"null":return e+t.operator;case"false_or_null":return e+"false";case"false":return e+"=false"}}};var hle={},ple={exports:{}};(function(t){(function(e,r){t.exports?t.exports=r():e.nearley=r()})(T,function(){function e(c,f,x){return this.id=++e.highestId,this.name=c,this.symbols=f,this.postprocess=x,this}e.highestId=0,e.prototype.toString=function(c){var f=typeof c>"u"?this.symbols.map(l).join(" "):this.symbols.slice(0,c).map(l).join(" ")+" ● "+this.symbols.slice(c).map(l).join(" ");return this.name+" → "+f};function r(c,f,x,h){this.rule=c,this.dot=f,this.reference=x,this.data=[],this.wantedBy=h,this.isComplete=this.dot===c.symbols.length}r.prototype.toString=function(){return"{"+this.rule.toString(this.dot)+"}, from: "+(this.reference||0)},r.prototype.nextState=function(c){var f=new r(this.rule,this.dot+1,this.reference,this.wantedBy);return f.left=this,f.right=c,f.isComplete&&(f.data=f.build(),f.right=void 0),f},r.prototype.build=function(){var c=[],f=this;do c.push(f.right.data),f=f.left;while(f.left);return c.reverse(),c},r.prototype.finish=function(){this.rule.postprocess&&(this.data=this.rule.postprocess(this.data,this.reference,u.fail))};function i(c,f){this.grammar=c,this.index=f,this.states=[],this.wants={},this.scannable=[],this.completed={}}i.prototype.process=function(c){for(var f=this.states,x=this.wants,h=this.completed,p=0;p<f.length;p++){var m=f[p];if(m.isComplete){if(m.finish(),m.data!==u.fail){for(var y=m.wantedBy,g=y.length;g--;){var E=y[g];this.complete(E,m)}if(m.reference===this.index){var A=m.rule.name;(this.completed[A]=this.completed[A]||[]).push(m)}}}else{var A=m.rule.symbols[m.dot];if(typeof A!="string"){this.scannable.push(m);continue}if(x[A]){if(x[A].push(m),h.hasOwnProperty(A))for(var _=h[A],g=0;g<_.length;g++){var v=_[g];this.complete(m,v)}}else x[A]=[m],this.predict(A)}}},i.prototype.predict=function(c){for(var f=this.grammar.byName[c]||[],x=0;x<f.length;x++){var h=f[x],p=this.wants[c],m=new r(h,0,this.index,p);this.states.push(m)}},i.prototype.complete=function(c,f){var x=c.nextState(f);this.states.push(x)};function s(c,f){this.rules=c,this.start=f||this.rules[0].name;var x=this.byName={};this.rules.forEach(function(h){x.hasOwnProperty(h.name)||(x[h.name]=[]),x[h.name].push(h)})}s.fromCompiled=function(h,f){var x=h.Lexer;h.ParserStart&&(f=h.ParserStart,h=h.ParserRules);var h=h.map(function(m){return new e(m.name,m.symbols,m.postprocess)}),p=new s(h,f);return p.lexer=x,p};function o(){this.reset("")}o.prototype.reset=function(c,f){this.buffer=c,this.index=0,this.line=f?f.line:1,this.lastLineBreak=f?-f.col:0},o.prototype.next=function(){if(this.index<this.buffer.length){var c=this.buffer[this.index++];return c===`
1423
1423
  `&&(this.line+=1,this.lastLineBreak=this.index),{value:c}}},o.prototype.save=function(){return{line:this.line,col:this.index-this.lastLineBreak}},o.prototype.formatError=function(c,f){var x=this.buffer;if(typeof x=="string"){var h=x.split(`
1424
1424
  `).slice(Math.max(0,this.line-5),this.line),p=x.indexOf(`
1425
1425
  `,this.index);p===-1&&(p=x.length);var m=this.index-this.lastLineBreak,y=String(this.line).length;return f+=" at line "+this.line+" col "+m+`:
@@ -1437,7 +1437,7 @@ Use (?: … ) instead`);if(!ee.lineBreaks&&j.test(`
1437
1437
  `))throw new Error("Rule should declare lineBreaks: "+j);he.push(l(F))}}var z=U&&U.fallback,L=i&&!z?"ym":"gm",M=i||z?"":"|";Z===!0&&(L+="u");var q=new RegExp(c(he)+M,L);return{regexp:q,groups:de,fast:V,error:U||E}}function _(D){var $=A(g(D));return new b({start:$},"start")}function v(D,$,U){var V=D&&(D.push||D.next);if(V&&!U[V])throw new Error("Missing state '"+V+"' (in token '"+D.defaultType+"' of state '"+$+"')");if(D&&D.pop&&+D.pop!=1)throw new Error("pop must be 1 (in token '"+D.defaultType+"' of state '"+$+"')")}function C(D,$){var U=D.$all?g(D.$all):[];delete D.$all;var V=Object.getOwnPropertyNames(D);$||($=V[0]);for(var Q=Object.create(null),Z=0;Z<V.length;Z++){var de=V[Z];Q[de]=g(D[de]).concat(U)}for(var Z=0;Z<V.length;Z++)for(var de=V[Z],he=Q[de],ie=Object.create(null),ee=0;ee<he.length;ee++){var X=he[ee];if(X.include){var ce=[ee,1];if(X.include!==de&&!ie[X.include]){ie[X.include]=!0;var N=Q[X.include];if(!N)throw new Error("Cannot include nonexistent state '"+X.include+"' (in state '"+de+"')");for(var w=0;w<N.length;w++){var F=N[w];he.indexOf(F)===-1&&ce.push(F)}}he.splice.apply(he,ce),ee--}}for(var j=Object.create(null),Z=0;Z<V.length;Z++){var de=V[Z];j[de]=A(Q[de],!0)}for(var Z=0;Z<V.length;Z++){for(var Y=V[Z],z=j[Y],L=z.groups,ee=0;ee<L.length;ee++)v(L[ee],Y,j);for(var M=Object.getOwnPropertyNames(z.fast),ee=0;ee<M.length;ee++)v(z.fast[M[ee]],Y,j)}return new b(j,$)}function S(D){for(var $=typeof Map<"u",U=$?new Map:Object.create(null),V=Object.getOwnPropertyNames(D),Q=0;Q<V.length;Q++){var Z=V[Q],de=D[Z],he=Array.isArray(de)?de:[de];he.forEach(function(ie){if(typeof ie!="string")throw new Error("keyword must be string (in keyword '"+Z+"')");$?U.set(ie,Z):U[ie]=Z})}return function(ie){return $?U.get(ie):U[ie]}}var b=function(D,$){this.startState=$,this.states=D,this.buffer="",this.stack=[],this.reset()};b.prototype.reset=function(D,$){return this.buffer=D||"",this.index=0,this.line=$?$.line:1,this.col=$?$.col:1,this.queuedToken=$?$.queuedToken:null,this.queuedText=$?$.queuedText:"",this.queuedThrow=$?$.queuedThrow:null,this.setState($?$.state:this.startState),this.stack=$&&$.stack?$.stack.slice():[],this},b.prototype.save=function(){return{line:this.line,col:this.col,state:this.state,stack:this.stack.slice(),queuedToken:this.queuedToken,queuedText:this.queuedText,queuedThrow:this.queuedThrow}},b.prototype.setState=function(D){if(!(!D||this.state===D)){this.state=D;var $=this.states[D];this.groups=$.groups,this.error=$.error,this.re=$.regexp,this.fast=$.fast}},b.prototype.popState=function(){this.setState(this.stack.pop())},b.prototype.pushState=function(D){this.stack.push(this.state),this.setState(D)};var R=i?function(D,$){return D.exec($)}:function(D,$){var U=D.exec($);return U[0].length===0?null:U};b.prototype._getGroup=function(D){for(var $=this.groups.length,U=0;U<$;U++)if(D[U+1]!==void 0)return this.groups[U];throw new Error("Cannot find token type for matched text")};function O(){return this.value}if(b.prototype.next=function(){var D=this.index;if(this.queuedGroup){var $=this._token(this.queuedGroup,this.queuedText,D);return this.queuedGroup=null,this.queuedText="",$}var U=this.buffer;if(D!==U.length){var de=this.fast[U.charCodeAt(D)];if(de)return this._token(de,U.charAt(D),D);var V=this.re;V.lastIndex=D;var Q=R(V,U),Z=this.error;if(Q==null)return this._token(Z,U.slice(D,U.length),D);var de=this._getGroup(Q),he=Q[0];return Z.fallback&&Q.index!==D?(this.queuedGroup=de,this.queuedText=he,this._token(Z,U.slice(D,Q.index),D)):this._token(de,he,D)}},b.prototype._token=function(D,$,U){var V=0;if(D.lineBreaks){var Q=/\n/g,Z=1;if($===`
1438
1438
  `)V=1;else for(;Q.exec($);)V++,Z=Q.lastIndex}var de={type:typeof D.type=="function"&&D.type($)||D.defaultType,value:typeof D.value=="function"?D.value($):$,text:$,toString:O,offset:U,lineBreaks:V,line:this.line,col:this.col},he=$.length;if(this.index+=he,this.line+=V,V!==0?this.col=he-Z+1:this.col+=he,D.shouldThrow){var ie=new Error(this.formatError(de,"invalid syntax"));throw ie}return D.pop?this.popState():D.push?this.pushState(D.push):D.next&&this.setState(D.next),de},typeof Symbol<"u"&&Symbol.iterator){var B=function(D){this.lexer=D};B.prototype.next=function(){var D=this.lexer.next();return{value:D,done:!D}},B.prototype[Symbol.iterator]=function(){return this},b.prototype[Symbol.iterator]=function(){return new B(this)}}return b.prototype.formatError=function(D,$){if(D==null)var U=this.buffer.slice(this.index),D={text:U,offset:this.index,lineBreaks:U.indexOf(`
1439
1439
  `)===-1?0:1,line:this.line,col:this.col};var V=2,Q=Math.max(D.line-V,1),Z=D.line+V,de=String(Z).length,he=h(this.buffer,this.line-D.line+V+1).slice(0,5),ie=[];ie.push($+" at line "+D.line+" col "+D.col+":"),ie.push("");for(var ee=0;ee<he.length;ee++){var X=he[ee],ce=Q+ee;ie.push(x(String(ce),de)+" "+X),ce===D.line&&ie.push(x("",de+D.col+1)+"^")}return ie.join(`
1440
- `)},b.prototype.clone=function(){return new b(this.states,this.state)},b.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:S}})})(mle);var EB=mle.exports,Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.mkUnits=Qt.timeLiteral=Qt.joinTemporal=Qt.temporalNot=Qt.numNot=Qt.mkValues=Qt.mkRange=Qt.joinNumbers=Qt.conjoin=Qt.matchOp=Qt.escape=Qt.unescape=Qt.maybeNot=void 0;const Pa=wn;function Let(t){const[e,r]=t;return e&&r&&(0,Pa.isStringFilter)(r)?{...r,not:!0}:r}Qt.maybeNot=Let;function tE(t){return t.replace(/\\(.)/g,"$1")}Qt.unescape=tE;function Iet(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}Qt.escape=Iet;function B4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function $et(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=B4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!B4(u).hasLike&&u.length>0)return{operator:"contains",values:[tE(u)]}}else if(i){const u=e.slice(0,-1);if(!B4(u).hasLike)return{operator:"starts",values:[tE(u)]}}else if(s){const u=e.slice(1);if(!B4(u).hasLike)return{operator:"ends",values:[tE(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"||e==="NULL"?{operator:"null"}:e==="empty"||e==="EMPTY"?{operator:"empty"}:{operator:"=",values:[tE(e)]}}Qt.matchOp=$et;function AB(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function Bet(t,e,r){if((0,Pa.isStringFilter)(t)&&(0,Pa.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&AB(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Pa.isStringCondition)(t)&&AB(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}Qt.conjoin=Bet;function ket(t,e,r){if((0,Pa.isNumberFilter)(t)&&(0,Pa.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&AB(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}Qt.joinNumbers=ket;function Met(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}Qt.mkRange=Met;function Pet(t,e){return{values:[t,...e]}}Qt.mkValues=Pet;function Uet(t,e){return(0,Pa.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}Qt.numNot=Uet;function jet(t,e){return(0,Pa.isTemporalFilter)(t)&&e?{...t,not:!0}:t}Qt.temporalNot=jet;function qet(t,e,r){return(0,Pa.isTemporalFilter)(t)&&(0,Pa.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}Qt.joinTemporal=qet;function Het(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}Qt.timeLiteral=Het;function Qet(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}Qt.mkUnits=Qet;var zet=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yB,"__esModule",{value:!0});function Wet(t){return t[0]}const gle=zet(EB),_2=Qt,Mn=gle.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:gle.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"})},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),Get=Mn.next;Mn.next=(t=>()=>{for(;;){const e=t.call(Mn);if(e===void 0||e.type!=="WS")return e}})(Get);const Vet={Lexer:Mn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,_2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Mn.has("NOT")?{type:"NOT"}:NOT],postprocess:Wet},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,_2.numNot)(e,t)},{name:"clause",symbols:[Mn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,_2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Mn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,_2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Mn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,_2.mkValues)(e,r)})},{name:"clause",symbols:[Mn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Mn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Mn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Mn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,_2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Mn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Mn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Mn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Mn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Mn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Mn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Mn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Mn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Mn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Mn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};yB.default=Vet;var v2={};Object.defineProperty(v2,"__esModule",{value:!0}),v2.run_parser=void 0;const Yet=wn;function Ket(t,e){try{e.feed(t);const i=e.finish()[0];return(0,Yet.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}v2.run_parser=Ket,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=wn,u=i(gB),a=s(yB),l=v2;t.NumberFilterExpression={parse(c){const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(hle);var yle={},_B={},Jet=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_B,"__esModule",{value:!0});function Xet(t){return t[0]}const Zet=Jet(EB),vB=Qt,Cu=Zet.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),ett=Cu.next;Cu.next=(t=>()=>{for(;;){const e=t.call(Cu);if(e==null||e.type!=="WS")return e}})(ett);const ttt={Lexer:Cu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,vB.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[Cu.has("minus")?{type:"minus"}:minus],postprocess:Xet},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,vB.maybeNot)(t)},{name:"parens",symbols:[Cu.has("open")?{type:"open"}:open,"stringFilter",Cu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[Cu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,vB.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[Cu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[Cu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[Cu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};_B.default=ttt,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=wn,u=i(gB),a=s(_B),l=Qt,c=v2;t.StringFilterExpression={parse(f){const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(yle);var Ele={},CB={},ntt=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(CB,"__esModule",{value:!0});function rtt(t){return t[0]}const Ale=ntt(EB),Su=Qt,Xe=Ale.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:Ale.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"})},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*))/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),itt=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(itt);const stt={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Su.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:rtt},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Su.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Su.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Su.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};CB.default=stt,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,y){y===void 0&&(y=m);var g=Object.getOwnPropertyDescriptor(p,m);(!g||("get"in g?!p.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,y,g)}:function(h,p,m,y){y===void 0&&(y=m),h[y]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=wn,u=s(CB),a=i(gB),l=v2;t.TemporalFilterExpression={parse(h){const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(Ele),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(wn,t);var i=$4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=hle;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=yle;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=Ele;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(I4);var k4={};Object.defineProperty(k4,"__esModule",{value:!0}),k4.TemporalFilterCompiler=void 0;const SB=et,Sd=qr,_le="yyyy",vle=`${_le}-LL`,bB=`${vle}-dd`,Cle=`${bB} HH`,Sle=`${Cle}:mm`,ys=`${Sle}:ss`;class ott{constructor(e,r,i="timestamp"){this.expr=e,this.timetype=i,this.d=r}time(e){return this.timetype==="timestamp"?e:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",e],kids:{args:[]},sql:e},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(e){const r=this.expr;switch(e.operator){case"after":return`${r} ${e.not?"<":">="} ${this.time(this.moment(e.after).end)}`;case"before":return`${r} ${e.not?">=":"<"} ${this.time(this.moment(e.before).begin.sql)}`;case"in":{const i=this.moment(e.in);return i.begin.sql===i.end?e.not?`${r} != ${this.time(i.end)} OR ${r} IS NULL`:`${r} = ${this.time(i.end)}`:this.isIn(e.not,i.begin.sql,i.end)}case"for":{const i=this.moment(e.begin),s=this.delta(i.begin,"+",e.n,e.units);return this.isIn(e.not,i.begin.sql,s.sql)}case"in_last":{const i=Number(e.n)-1,s=this.nowDot(e.units),o=i>0?this.delta(s,"-",i.toString(),e.units):s,u=this.delta(s,"+","1",e.units);return this.isIn(e.not,o.sql,u.sql)}case"to":{const i=this.moment(e.fromMoment),s=this.moment(e.toMoment);return this.isIn(e.not,i.begin.sql,s.begin.sql)}case"last":{const i=this.nowDot(e.units),s=this.delta(i,"-",e.n,e.units);return this.isIn(e.not,s.sql,i.sql)}case"next":{const i=this.nowDot(e.units),s=this.delta(i,"+","1",e.units),o=this.delta(i,"+",(Number(e.n)+1).toString(),e.units);return this.isIn(e.not,s.sql,o.sql)}case"null":return e.not?`${r} IS NOT NULL`:`${r} IS NULL`;case"()":{const i="("+this.compile(e.expr)+")";return e.not?`NOT ${i}`:i}case"and":case"or":return e.members.map(i=>this.compile(i)).join(` ${e.operator.toUpperCase()} `)}}expandLiteral(e){let r=e.literal;switch(e.units){case"year":{const i=Sd.DateTime.fromFormat(r,_le),s=this.literalNode(i.toFormat(ys)),o=i.plus({year:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"month":{const i=Sd.DateTime.fromFormat(r,vle),s=this.literalNode(i.toFormat(ys)),o=i.plus({month:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"day":{const i=Sd.DateTime.fromFormat(r,bB),s=this.literalNode(i.toFormat(ys)),o=i.plus({day:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"hour":{const i=Sd.DateTime.fromFormat(r,Cle),s=this.literalNode(i.toFormat(ys)),o=i.plus({hour:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"minute":{const i=Sd.DateTime.fromFormat(r,Sle),s=this.literalNode(i.toFormat(ys)),o=i.plus({minute:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"week":{const o=Sd.DateTime.fromFormat(r.slice(0,10),bB).plus({day:1}).startOf("week").minus({day:1}),u=this.literalNode(o.toFormat(ys)),a=o.plus({days:7});return{begin:u,end:this.literalNode(a.toFormat(ys)).sql}}case"quarter":{const i=r.slice(0,4),s=r.slice(6);s==="1"?r=`${i}-01-01 00:00:00`:s==="2"?r=`${i}-03-01 00:00:00`:s==="3"?r=`${i}-06-01 00:00:00`:r=`${i}-09-01 00:00:00`;const o=this.literalNode(r),a=Sd.DateTime.fromFormat(r,ys).plus({months:3});return{begin:o,end:this.literalNode(a.toFormat(ys)).sql}}case void 0:case"second":return{begin:this.literalNode(r),end:r}}}literalNode(e){const r={node:"timeLiteral",typeDef:{type:"timestamp"},literal:e};return{...r,sql:this.d.sqlLiteralTime({},r)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(e){return{node:"numberLiteral",literal:e,sql:e}}delta(e,r,i,s){const o={node:"delta",op:r,units:s,kids:{base:(0,SB.mkTemporal)(e,"timestamp"),delta:this.n(i)}};return{...o,sql:this.d.sqlAlterTimeExpr(o)}}dayofWeek(e){const r={node:"extract",e:(0,SB.mkTemporal)(e,"timestamp"),units:"day_of_week"};return{...r,sql:this.d.sqlTimeExtractExpr({},r)}}nowDot(e){const r={node:"trunc",e:this.nowExpr(),units:e};return{...r,sql:this.d.sqlTruncExpr({},r)}}thisUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e);return{begin:r,end:i.sql}}lastUnit(e){const r=this.nowDot(e);return{begin:this.delta(r,"-","1",e),end:r.sql}}nextUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e),s=this.delta(r,"+","2",e);return{begin:i,end:s.sql}}mod7(e){return this.d.hasModOperator?`(${e})%7`:`MOD(${e},7)`}moment(e){switch(e.moment){case"now":{const r=this.nowExpr();return{begin:r,end:r.sql}}case"literal":return this.expandLiteral(e);case"ago":case"from_now":{const r=this.nowDot(e.units),i=(0,SB.mkTemporal)(r,"timestamp"),s=this.delta(i,e.moment==="ago"?"-":"+",e.n,e.units);if(e.moment==="ago"&&e.n==="1")return{begin:s,end:r.sql};const o=Number(e.n)+(e.moment==="ago"?-1:1),u={...s,kids:{base:i,delta:this.n(o.toString())}};return{begin:s,end:this.d.sqlAlterTimeExpr(u)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(e.units);case"last":return this.lastUnit(e.units);case"next":return this.nextUnit(e.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const r=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(e.moment),i=this.dayofWeek(this.nowExpr()).sql;if(e.which==="next"){const a=`${this.mod7(`${r}-(${i}-1)+6`)}+1`,l=this.delta(this.thisUnit("day").begin,"+",a,"day"),c=this.delta(this.thisUnit("day").begin,"+",`${a}+1`,"day");return{begin:l,end:c.sql}}const s=`${this.mod7(`(${i}-1)-${r}+6`)}+1`,o=this.delta(this.thisUnit("day").begin,"-",s,"day"),u=this.delta(this.thisUnit("day").begin,"-",`(${s})-1`,"day");return{begin:o,end:u.sql}}}}isIn(e,r,i){let s=">=",o="<",u="AND";return e&&(u="OR",s="<",o=">="),r=this.time(r),i=this.time(i),`${this.expr} ${s} ${r} ${u} ${this.expr} ${o} ${i}`}}k4.TemporalFilterCompiler=ott,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FilterCompilers=void 0;const e=I4,r=k4;function i(u){return u.replace(/([%_\\])/g,"\\$1")}function s(u){return u===">"?"<=":u==="<"?">=":u===">="?"<":">"}function o(u,a){const l=` OR ${a} IS NULL`;return u.length===1?`${u[0]}${l}`:`(${u.join(" AND ")})${l}`}t.FilterCompilers={compile(u,a,l,c){if(u==="string"&&(0,e.isStringFilter)(a))return t.FilterCompilers.stringCompile(a,l,c);if(u==="number"&&(0,e.isNumberFilter)(a))return t.FilterCompilers.numberCompile(a,l,c);if(u==="boolean"&&(0,e.isBooleanFilter)(a))return t.FilterCompilers.booleanCompile(a,l,c);if((u==="date"||u==="timestamp")&&(0,e.isTemporalFilter)(a))return t.FilterCompilers.temporalCompile(a,l,c,u);throw new Error("INTERNAL ERROR: No filter compiler for "+u)},numberCompile(u,a,l){switch(u.operator){case"!=":case"=":{const c=u.operator==="="&&u.not||u.operator==="!="&&!u.not,f=u.values.join(", ");return u.values.length===1?c?`${a} != ${f} OR ${a} IS NULL`:`${a} = ${f}`:c?`${a} NOT IN (${f}) OR ${a} IS NULL`:`${a} IN (${f})`}case">":case"<":case">=":case"<=":return u.values.map(c=>`${a} ${u.operator} ${c}`).join(u.not?" AND ":" OR ");case"range":{let c=u.startOperator,f=u.endOperator,x=" AND ";return u.not&&(c=s(c),f=s(f),x=" OR "),`${a} ${c} ${u.startValue} ${x} ${a} ${f} ${u.endValue}`}case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"()":{const c="("+t.FilterCompilers.numberCompile(u.expr,a,l)+")";return u.not?`NOT ${c}`:c}case"and":case"or":return u.members.map(c=>t.FilterCompilers.numberCompile(c,a,l)).join(` ${u.operator.toUpperCase()} `)}},booleanCompile(u,a,l){switch(u.operator){case"false":return`${a} = false`;case"false_or_null":return`${a} IS NULL OR ${a} = false`;case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"true":return a}},stringCompile(u,a,l){switch(u.operator){case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"empty":return u.not?`COALESCE(${a},'') != ''`:`COALESCE(${a},'') = ''`;case"=":{if(u.values.length===1){const f=u.not?"!=":"=",x=`${a} ${f} ${l.sqlLiteralString(u.values[0])}`;return u.not?`(${x} OR ${a} IS NULL)`:x}const c="("+u.values.map(f=>l.sqlLiteralString(f)).join(", ")+")";return u.not?`(${a} NOT IN ${c} OR ${a} IS NULL)`:`${a} IN ${c}`}case"()":{const c="("+t.FilterCompilers.stringCompile(u.expr,a,l)+")";return u.not?`not ${c}`:c}case"contains":{const c=u.values.map(f=>"%"+i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"starts":{const c=u.values.map(f=>i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"ends":{const c=u.values.map(f=>"%"+i(f));return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"~":return u.not?o(u.escaped_values.map(c=>l.sqlLike("NOT LIKE",a,c)),a):u.escaped_values.map(c=>l.sqlLike("LIKE",a,c)).join(" OR ");case"and":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case"or":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case",":{const c=[],f=[];let x=!1,h=!1,p=!1,m=!1;for(const E of u.members)switch(E.operator){case"or":case"and":case",":c.push(E);break;case"null":E.not?h=!0:x=!0;break;case"empty":E.not?(m=!0,h=!0):(p=!0,x=!0);break;default:(E.not?f:c).push(E)}if(p&&m||x&&h)return"false";let y="";if(c.length>0||x||p){m=!1,h=!1;const E=c.map(A=>t.FilterCompilers.stringCompile(A,a,l));p&&E.push(`${a} = ''`),x&&E.push(`${a} IS NULL`),y=E.join(" OR ")}let g="";if(f.length>0||m||h){const E=f.map(A=>t.FilterCompilers.stringCompile(A,a,l));m&&E.push(`${a} != ''`),h&&E.push(`${a} IS NOT NULL`),g=E.join(" AND ")}return y?g!==""?`(${y}) AND (${g})`:y:g!==""?g:"true"}}},temporalCompile(u,a,l,c){return new r.TemporalFilterCompiler(a,l,c).compile(u)}}}(dle),Object.defineProperty(Hs,"__esModule",{value:!0}),Hs.QueryModel=Hs.getResultStructDefForQuery=Hs.getResultStructDefForView=Hs.Segment=void 0;const utt=g2,att=p2,ltt=Xy,Ue=et,Fn=kt,M4=A2,ctt=gi,ftt=dle,xtt=I4;function ble(t){return t.map(e=>encodeURIComponent(e)).join("/")}function TB(t){return`'${t}'`}function dtt(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function C2(t){const e=[];for(const r of t.fields.filter(Ue.fieldIsIntrinsic))e.push({type:r.type,sqlExpression:(0,Ue.getIdentifier)(r),rawName:(0,Ue.getIdentifier)(r),sqlOutputName:(0,Ue.getIdentifier)(r)});return e}class htt extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class nE{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Fn.indent)(`
1440
+ `)},b.prototype.clone=function(){return new b(this.states,this.state)},b.prototype.has=function(D){return!0},{compile:_,states:C,error:Object.freeze({error:!0}),fallback:Object.freeze({fallback:!0}),keywords:S}})})(mle);var EB=mle.exports,Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.mkUnits=Qt.timeLiteral=Qt.joinTemporal=Qt.temporalNot=Qt.numNot=Qt.mkValues=Qt.mkRange=Qt.joinNumbers=Qt.conjoin=Qt.matchOp=Qt.escape=Qt.unescape=Qt.maybeNot=void 0;const Pa=wn;function Let(t){const[e,r]=t;return e&&r&&(0,Pa.isStringFilter)(r)?{...r,not:!0}:r}Qt.maybeNot=Let;function tE(t){return t.replace(/\\(.)/g,"$1")}Qt.unescape=tE;function Iet(t){const e=t.toLowerCase();return e==="null"||e==="empty"?"\\"+t:t.replace(/([,; |()\\%_-])/g,"\\$1")}Qt.escape=Iet;function B4(t){let e=!1,r=!1,i=0,s=!1;const o=t.length;for(let u=0;u<o;u+=1){const a=t[u];if(a===" "||a===" "){i+=1;continue}i=0,a==="%"?(s=!0,u===0&&(e=!0),r=!0):(r=!1,a==="\\"?u+=1:a==="_"&&(s=!0))}return{hasLike:s,percentEnd:r&&o>1,percentStart:e&&o>1,endSpace:i}}function $et(t){let e=t.trimStart();const{hasLike:r,percentEnd:i,percentStart:s,endSpace:o}=B4(e);if(o>0&&(e=e.slice(0,-o)),r){if(s&&i){const u=e.slice(1,-1);if(!B4(u).hasLike&&u.length>0)return{operator:"contains",values:[tE(u)]}}else if(i){const u=e.slice(0,-1);if(!B4(u).hasLike)return{operator:"starts",values:[tE(u)]}}else if(s){const u=e.slice(1);if(!B4(u).hasLike)return{operator:"ends",values:[tE(u)]}}return{operator:"~",escaped_values:[e]}}return e.toLowerCase()==="null"||e==="NULL"?{operator:"null"}:e==="empty"||e==="EMPTY"?{operator:"empty"}:{operator:"=",values:[tE(e)]}}Qt.matchOp=$et;function AB(t,e){var r,i;return t.operator===e.operator&&((r=t.not)!==null&&r!==void 0?r:!1)===((i=e.not)!==null&&i!==void 0?i:!1)}function Bet(t,e,r){if((0,Pa.isStringFilter)(t)&&(0,Pa.isStringFilter)(r)){if(e===","){if(t.operator==="~"&&AB(t,r))return{...t,escaped_values:[...t.escaped_values,...r.escaped_values]};if((0,Pa.isStringCondition)(t)&&AB(t,r))return{...t,values:[...t.values,...r.values]}}const i=e===","?",":e==="|"?"or":e===";"?"and":void 0;if(i)return t.operator===i?{...t,members:[...t.members,r]}:{operator:i,members:[t,r]}}return null}Qt.conjoin=Bet;function ket(t,e,r){if((0,Pa.isNumberFilter)(t)&&(0,Pa.isNumberFilter)(r)){if(e==="or"&&t.operator==="="&&AB(t,r)){const i={operator:"=",values:[...t.values,...r.values]};return t.not&&(i.not=!0),i}if(e==="and"||e==="or")return t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}}return null}Qt.joinNumbers=ket;function Met(t,e,r,i){return{operator:"range",startValue:e,startOperator:t==="("?">":">=",endValue:r,endOperator:i===")"?"<":"<="}}Qt.mkRange=Met;function Pet(t,e){return{values:[t,...e]}}Qt.mkValues=Pet;function Uet(t,e){return(0,Pa.isNumberFilter)(t)&&e?t.operator==="="?{operator:"!=",values:t.values}:t.operator==="!="?{operator:"=",values:t.values}:{...t,not:!0}:t}Qt.numNot=Uet;function jet(t,e){return(0,Pa.isTemporalFilter)(t)&&e?{...t,not:!0}:t}Qt.temporalNot=jet;function qet(t,e,r){return(0,Pa.isTemporalFilter)(t)&&(0,Pa.isTemporalFilter)(r)&&(e==="and"||e==="or")?t.operator===e?{...t,members:[...t.members,r]}:{operator:e,members:[t,r]}:null}Qt.joinTemporal=qet;function Het(t,e){const r={moment:"literal",literal:t};return e&&(r.units=e),r}Qt.timeLiteral=Het;function Qet(t){switch(t.toLowerCase()){case"second":case"seconds":return"second";case"minute":case"minutes":return"minute";case"hour":case"hours":return"hour";case"day":case"days":return"day";case"week":case"weeks":return"week";case"month":case"months":return"month";case"quarter":case"quarters":return"quarter";case"year":case"years":return"year"}}Qt.mkUnits=Qet;var zet=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(yB,"__esModule",{value:!0});function Wet(t){return t[0]}const gle=zet(EB),_2=Qt,Mn=gle.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:gle.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to"})},oparen:"(",cparen:")",obrack:"[",cbrack:"]",comma:",",op:/<=|>=|<|>/,ne:"!=",eq:"=",float:/-?(?:\d+)?\.\d+(?:[Ee][+-]?\d+)?/,numberE:/-?\d+[Ee][+-]?\d+/,integer:/-?\d+/}),Get=Mn.next;Mn.next=(t=>()=>{for(;;){const e=t.call(Mn);if(e===void 0||e.type!=="WS")return e}})(Get);const Vet={Lexer:Mn,ParserRules:[{name:"numberFilter",symbols:["numberFilter","conjunction","numberUnary"],postprocess:([t,e,r])=>(0,_2.joinNumbers)(t,e[0].text,r)},{name:"numberFilter",symbols:["numberUnary"],postprocess:t=>t[0]},{name:"numberUnary$ebnf$1",symbols:[Mn.has("NOT")?{type:"NOT"}:NOT],postprocess:Wet},{name:"numberUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"numberUnary",symbols:["numberUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,_2.numNot)(e,t)},{name:"clause",symbols:[Mn.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause$ebnf$1",symbols:[]},{name:"clause$ebnf$1",symbols:["clause$ebnf$1","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:["N","clause$ebnf$1"],postprocess:([t,e])=>({operator:"=",...(0,_2.mkValues)(t,e)})},{name:"clause$ebnf$2",symbols:[]},{name:"clause$ebnf$2",symbols:["clause$ebnf$2","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Mn.has("eq")?{type:"eq"}:eq,"N","clause$ebnf$2"],postprocess:([t,e,r])=>({operator:"=",...(0,_2.mkValues)(e,r)})},{name:"clause$ebnf$3",symbols:[]},{name:"clause$ebnf$3",symbols:["clause$ebnf$3","numberList"],postprocess:t=>t[0].concat([t[1]])},{name:"clause",symbols:[Mn.has("ne")?{type:"ne"}:ne,"N","clause$ebnf$3"],postprocess:([t,e,r])=>({operator:"!=",...(0,_2.mkValues)(e,r)})},{name:"clause",symbols:[Mn.has("op")?{type:"op"}:op,"N"],postprocess:([t,e])=>({operator:t.text,values:[e]})},{name:"clause",symbols:[Mn.has("oparen")?{type:"oparen"}:oparen,"numberFilter",Mn.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:["openInterval","N",Mn.has("TO")?{type:"TO"}:TO,"N","closeInterval"],postprocess:([t,e,r,i,s])=>(0,_2.mkRange)(t[0].text,e,i,s[0].text)},{name:"numberList",symbols:[Mn.has("comma")?{type:"comma"}:comma,"N"],postprocess:([t,e])=>e},{name:"closeInterval",symbols:[Mn.has("cbrack")?{type:"cbrack"}:cbrack]},{name:"closeInterval",symbols:[Mn.has("cparen")?{type:"cparen"}:cparen]},{name:"openInterval",symbols:[Mn.has("obrack")?{type:"obrack"}:obrack]},{name:"openInterval",symbols:[Mn.has("oparen")?{type:"oparen"}:oparen]},{name:"N$subexpression$1",symbols:[Mn.has("float")?{type:"float"}:float]},{name:"N$subexpression$1",symbols:[Mn.has("numberE")?{type:"numberE"}:numberE]},{name:"N$subexpression$1",symbols:[Mn.has("integer")?{type:"integer"}:integer]},{name:"N",symbols:["N$subexpression$1"],postprocess:([t])=>t[0].text},{name:"conjunction",symbols:[Mn.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Mn.has("AND")?{type:"AND"}:AND]}],ParserStart:"numberFilter"};yB.default=Vet;var v2={};Object.defineProperty(v2,"__esModule",{value:!0}),v2.run_parser=void 0;const Yet=wn;function Ket(t,e){try{e.feed(t);const i=e.finish()[0];return(0,Yet.isFilterExpression)(i)?{parsed:i,log:[]}:{parsed:null,log:[]}}catch(r){let i=r.message,s=1,o=t.length;if(r.token){const u=r.token;s=u.col,o=u.text.length;const l=r.message.match(new RegExp("(?<=A ).*(?= based on:)","g")).map(c=>c.replace(/\s+token/i,""));i=`Unexpected ${u.type} token "${u.value}"`,l&&l.length&&(i+=` Tokens expected: ${[...new Set(l)]}`)}return{parsed:null,log:[{message:i,startIndex:s-1,endIndex:s-1+o-1,severity:"error"}]}}}v2.run_parser=Ket,function(t){var e=T&&T.__createBinding||(Object.create?function(c,f,x,h){h===void 0&&(h=x);var p=Object.getOwnPropertyDescriptor(f,x);(!p||("get"in p?!f.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return f[x]}}),Object.defineProperty(c,h,p)}:function(c,f,x,h){h===void 0&&(h=x),c[h]=f[x]}),r=T&&T.__setModuleDefault||(Object.create?function(c,f){Object.defineProperty(c,"default",{enumerable:!0,value:f})}:function(c,f){c.default=f}),i=T&&T.__importStar||function(c){if(c&&c.__esModule)return c;var f={};if(c!=null)for(var x in c)x!=="default"&&Object.prototype.hasOwnProperty.call(c,x)&&e(f,c,x);return r(f,c),f},s=T&&T.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.NumberFilterExpression=void 0;const o=wn,u=i(gB),a=s(yB),l=v2;t.NumberFilterExpression={parse(c){if(c.match(/^\s*$/))return{parsed:null,log:[]};const f=new u.Parser(u.Grammar.fromCompiled(a.default)),x=(0,l.run_parser)(c,f);return x.parsed&&(0,o.isNumberFilter)(x.parsed)?{parsed:x.parsed,log:[]}:{parsed:null,log:x.log}},unparse(c){if(c===null)return"";switch(c.operator){case"=":return c.values.join(", ");case"!=":return"!= "+c.values.join(", ");case">":case"<":case"<=":case">=":return c.not?c.values.map(f=>c.operator==="="?`not ${f}`:`not ${c.operator} ${f}`).join(", "):c.values.map(f=>`${c.operator} ${f}`).join(", ");case"range":{const f=c.startOperator===">"?"(":"[",x=c.endOperator==="<"?")":"]",h=`${f}${c.startValue} to ${c.endValue}${x}`;return c.not?`not ${h}`:h}case"null":return c.not?"not null":"null";case"and":case"or":return c.members.map(f=>t.NumberFilterExpression.unparse(f)).join(` ${c.operator} `);case"()":{const f="("+t.NumberFilterExpression.unparse(c.expr)+")";return c.not?"not "+f:f}}return`no unparse for ${JSON.stringify(c)}`}}}(hle);var yle={},_B={},Jet=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_B,"__esModule",{value:!0});function Xet(t){return t[0]}const Zet=Jet(EB),vB=Qt,Cu=Zet.default.compile({WS:/[ \t]+/,comma:",",semi:";",or:"|",open:"(",close:")",minus:"-",matchStr:/(?:\\[^\n]|[^\n,;()|])+/}),ett=Cu.next;Cu.next=(t=>()=>{for(;;){const e=t.call(Cu);if(e==null||e.type!=="WS")return e}})(ett);const ttt={Lexer:Cu,ParserRules:[{name:"stringFilter",symbols:["stringFilter","conjunction","sfUnary"],postprocess:([t,e,r])=>(0,vB.conjoin)(t,e[0].text,r)},{name:"stringFilter",symbols:["sfUnary"],postprocess:t=>t[0]},{name:"sfUnary$ebnf$1",symbols:[Cu.has("minus")?{type:"minus"}:minus],postprocess:Xet},{name:"sfUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"sfUnary",symbols:["sfUnary$ebnf$1","clause"],postprocess:t=>(0,vB.maybeNot)(t)},{name:"parens",symbols:[Cu.has("open")?{type:"open"}:open,"stringFilter",Cu.has("close")?{type:"close"}:close],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"clause",symbols:[Cu.has("matchStr")?{type:"matchStr"}:matchStr],postprocess:([t])=>(0,vB.matchOp)(t.text)},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"conjunction",symbols:[Cu.has("comma")?{type:"comma"}:comma]},{name:"conjunction",symbols:[Cu.has("semi")?{type:"semi"}:semi]},{name:"conjunction",symbols:[Cu.has("or")?{type:"or"}:or]}],ParserStart:"stringFilter"};_B.default=ttt,function(t){var e=T&&T.__createBinding||(Object.create?function(f,x,h,p){p===void 0&&(p=h);var m=Object.getOwnPropertyDescriptor(x,h);(!m||("get"in m?!x.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return x[h]}}),Object.defineProperty(f,p,m)}:function(f,x,h,p){p===void 0&&(p=h),f[p]=x[h]}),r=T&&T.__setModuleDefault||(Object.create?function(f,x){Object.defineProperty(f,"default",{enumerable:!0,value:x})}:function(f,x){f.default=x}),i=T&&T.__importStar||function(f){if(f&&f.__esModule)return f;var x={};if(f!=null)for(var h in f)h!=="default"&&Object.prototype.hasOwnProperty.call(f,h)&&e(x,f,h);return r(x,f),x},s=T&&T.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.StringFilterExpression=void 0;const o=wn,u=i(gB),a=s(_B),l=Qt,c=v2;t.StringFilterExpression={parse(f){if(f.match(/^\s*$/))return{parsed:null,log:[]};const x=new u.Parser(u.Grammar.fromCompiled(a.default)),h=(0,c.run_parser)(f,x);return h.parsed&&(0,o.isStringFilter)(h.parsed)?{parsed:h.parsed,log:[]}:{parsed:null,log:h.log}},unparse(f){if(f===null)return"";switch(f.operator){case"=":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)).join(", "):f.values.map(x=>(0,l.escape)(x)).join(", ");case"~":return f.not?f.escaped_values.map(x=>"-"+x).join(", "):f.escaped_values.join(", ");case"starts":return f.not?f.values.map(x=>"-"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>(0,l.escape)(x)+"%").join(", ");case"ends":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)).join(", "):f.values.map(x=>"%"+(0,l.escape)(x)).join(", ");case"contains":return f.not?f.values.map(x=>"-%"+(0,l.escape)(x)+"%").join(", "):f.values.map(x=>"%"+(0,l.escape)(x)+"%").join(", ");case"or":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(" | ");case"and":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join("; ");case",":return f.members.map(x=>t.StringFilterExpression.unparse(x)).join(", ");case"()":{const x="("+t.StringFilterExpression.unparse(f.expr)+")";return f.not?"-"+x:x}case"null":return f.not?"-null":"null";case"empty":return f.not?"-empty":"empty"}}}}(yle);var Ele={},CB={},ntt=T&&T.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(CB,"__esModule",{value:!0});function rtt(t){return t[0]}const Ale=ntt(EB),Su=Qt,Xe=Ale.default.compile({WS:/[ \t]+/,id:{match:/[a-zA-Z]+/,type:Ale.default.keywords({AND:"and",OR:"or",NOT:"not",NULL_KW:"null",TO:"to",NOW:"now",LAST:"last",THIS:"this",NEXT:"next",AGO:"ago",FROM:"from",BEFORE:"before",AFTER:"after",FOR:"for",TODAY:"today",YESTERDAY:"yesterday",TOMORROW:"tomorrow",SECOND:"second",MINUTE:"minute",HOUR:"hour",DAY:"day",WEEK:"week",MONTH:"month",QUARTER:"quarter",YEAR:"year",SECONDS:"seconds",MINUTES:"minutes",HOURS:"hours",DAYS:"days",WEEKS:"weeks",MONTHS:"months",QUARTERS:"quarters",YEARS:"years",MONDAY:"monday",TUESDAY:"tuesday",WEDNESDAY:"wednesday",THURSDAY:"thursday",FRIDAY:"friday",SATURDAY:"saturday",SUNDAY:"sunday"})},oparen:"(",cparen:")",comma:",",literal:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d(?::\d\d(?:[.,]\d*))/,lit_week:/\d\d\d\d-\d\d-\d\d-[Ww][Kk]/,lit_quarter:/\d\d\d\d-[qQ][1234]/,lit_min:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d:\d\d/,lit_hour:/\d\d\d\d-\d\d-\d\d[ Tt]\d\d/,lit_day:/\d\d\d\d-\d\d-\d\d/,lit_month:/\d\d\d\d-\d\d/,lit_year:/\d\d\d\d/,n:/\d+/}),itt=Xe.next;Xe.next=(t=>()=>{for(;;){const e=t.call(Xe);if(e===void 0||e.type!=="WS")return e}})(itt);const stt={Lexer:Xe,ParserRules:[{name:"temporalFilter",symbols:["temporalFilter","conjunction","temporalUnary"],postprocess:([t,e,r])=>(0,Su.joinTemporal)(t,e[0].text,r)},{name:"temporalFilter",symbols:["temporalUnary"],postprocess:t=>t[0]},{name:"temporalUnary$ebnf$1",symbols:[Xe.has("NOT")?{type:"NOT"}:NOT],postprocess:rtt},{name:"temporalUnary$ebnf$1",symbols:[],postprocess:()=>null},{name:"temporalUnary",symbols:["temporalUnary$ebnf$1","clause"],postprocess:([t,e])=>(0,Su.temporalNot)(e,t)},{name:"duration",symbols:["number","unit"],postprocess:([t,e])=>({units:e,n:t})},{name:"number",symbols:[Xe.has("n")?{type:"n"}:n],postprocess:([t])=>t.text},{name:"number",symbols:[Xe.has("lityear")?{type:"lityear"}:lityear],postprocess:([t])=>t.text},{name:"unit$subexpression$1",symbols:[Xe.has("SECOND")?{type:"SECOND"}:SECOND]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTE")?{type:"MINUTE"}:MINUTE]},{name:"unit$subexpression$1",symbols:[Xe.has("HOUR")?{type:"HOUR"}:HOUR]},{name:"unit$subexpression$1",symbols:[Xe.has("DAY")?{type:"DAY"}:DAY]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEK")?{type:"WEEK"}:WEEK]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTH")?{type:"MONTH"}:MONTH]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTER")?{type:"QUARTER"}:QUARTER]},{name:"unit$subexpression$1",symbols:[Xe.has("YEAR")?{type:"YEAR"}:YEAR]},{name:"unit$subexpression$1",symbols:[Xe.has("SECONDS")?{type:"SECONDS"}:SECONDS]},{name:"unit$subexpression$1",symbols:[Xe.has("MINUTES")?{type:"MINUTES"}:MINUTES]},{name:"unit$subexpression$1",symbols:[Xe.has("HOURS")?{type:"HOURS"}:HOURS]},{name:"unit$subexpression$1",symbols:[Xe.has("DAYS")?{type:"DAYS"}:DAYS]},{name:"unit$subexpression$1",symbols:[Xe.has("WEEKS")?{type:"WEEKS"}:WEEKS]},{name:"unit$subexpression$1",symbols:[Xe.has("MONTHS")?{type:"MONTHS"}:MONTHS]},{name:"unit$subexpression$1",symbols:[Xe.has("QUARTERS")?{type:"QUARTERS"}:QUARTERS]},{name:"unit$subexpression$1",symbols:[Xe.has("YEARS")?{type:"YEARS"}:YEARS]},{name:"unit",symbols:["unit$subexpression$1"],postprocess:([t])=>(0,Su.mkUnits)(t[0].text)},{name:"clause",symbols:[Xe.has("NULL_KW")?{type:"NULL_KW"}:NULL_KW],postprocess:()=>({operator:"null"})},{name:"clause",symbols:["parens"],postprocess:t=>t[0]},{name:"clause",symbols:["duration"],postprocess:([t])=>({operator:"in_last",...t})},{name:"clause",symbols:[Xe.has("BEFORE")?{type:"BEFORE"}:BEFORE,"moment"],postprocess:([t,e])=>({operator:"before",before:e})},{name:"clause",symbols:[Xe.has("AFTER")?{type:"AFTER"}:AFTER,"moment"],postprocess:([t,e])=>({operator:"after",after:e})},{name:"clause",symbols:["moment",Xe.has("TO")?{type:"TO"}:TO,"moment"],postprocess:([t,e,r])=>({operator:"to",fromMoment:t,toMoment:r})},{name:"clause",symbols:["moment",Xe.has("FOR")?{type:"FOR"}:FOR,"duration"],postprocess:([t,e,r])=>({...r,operator:"for",begin:t})},{name:"clause$subexpression$1",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST]},{name:"clause$subexpression$1",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT]},{name:"clause",symbols:["clause$subexpression$1","duration"],postprocess:([t,e])=>({operator:t[0].text,...e})},{name:"clause",symbols:["moment"],postprocess:([t])=>({operator:"in",in:t})},{name:"lastNextThis",symbols:[Xe.has("THIS")?{type:"THIS"}:THIS],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT],postprocess:([t])=>t.text.toLowerCase()},{name:"lastNextThis",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST],postprocess:([t])=>t.text.toLowerCase()},{name:"moment",symbols:[Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:()=>({moment:"now"})},{name:"moment",symbols:["lastNextThis","unit"],postprocess:([t,e])=>({moment:t,units:e})},{name:"moment",symbols:[Xe.has("TODAY")?{type:"TODAY"}:TODAY],postprocess:()=>({moment:"today"})},{name:"moment",symbols:[Xe.has("YESTERDAY")?{type:"YESTERDAY"}:YESTERDAY],postprocess:()=>({moment:"yesterday"})},{name:"moment",symbols:[Xe.has("TOMORROW")?{type:"TOMORROW"}:TOMORROW],postprocess:()=>({moment:"tomorrow"})},{name:"moment",symbols:["duration",Xe.has("AGO")?{type:"AGO"}:AGO],postprocess:([t,e])=>({moment:"ago",...t})},{name:"moment",symbols:["duration",Xe.has("FROM")?{type:"FROM"}:FROM,Xe.has("NOW")?{type:"NOW"}:NOW],postprocess:([t,e])=>({moment:"from_now",...t})},{name:"moment",symbols:[Xe.has("NEXT")?{type:"NEXT"}:NEXT,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"next"})},{name:"moment",symbols:[Xe.has("LAST")?{type:"LAST"}:LAST,"weekday"],postprocess:([t,e])=>({moment:e.toLowerCase(),which:"last"})},{name:"moment",symbols:["weekday"],postprocess:([t])=>({moment:t.toLowerCase(),which:"last"})},{name:"moment",symbols:["timeLiteral"],postprocess:t=>t[0]},{name:"timeLiteral",symbols:[Xe.has("literal")?{type:"literal"}:literal],postprocess:([t])=>(0,Su.timeLiteral)(t.text)},{name:"timeLiteral",symbols:[Xe.has("lit_day")?{type:"lit_day"}:lit_day],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"day")},{name:"timeLiteral",symbols:[Xe.has("lit_min")?{type:"lit_min"}:lit_min],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"minute")},{name:"timeLiteral",symbols:[Xe.has("lit_hour")?{type:"lit_hour"}:lit_hour],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"hour")},{name:"timeLiteral",symbols:[Xe.has("lit_month")?{type:"lit_month"}:lit_month],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"month")},{name:"timeLiteral",symbols:[Xe.has("lit_quarter")?{type:"lit_quarter"}:lit_quarter],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"quarter")},{name:"timeLiteral",symbols:[Xe.has("lit_week")?{type:"lit_week"}:lit_week],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"week")},{name:"timeLiteral",symbols:[Xe.has("lit_year")?{type:"lit_year"}:lit_year],postprocess:([t])=>(0,Su.timeLiteral)(t.text,"year")},{name:"weekday$subexpression$1",symbols:[Xe.has("MONDAY")?{type:"MONDAY"}:MONDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("TUESDAY")?{type:"TUESDAY"}:TUESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("WEDNESDAY")?{type:"WEDNESDAY"}:WEDNESDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("THURSDAY")?{type:"THURSDAY"}:THURSDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("FRIDAY")?{type:"FRIDAY"}:FRIDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SATURDAY")?{type:"SATURDAY"}:SATURDAY]},{name:"weekday$subexpression$1",symbols:[Xe.has("SUNDAY")?{type:"SUNDAY"}:SUNDAY]},{name:"weekday",symbols:["weekday$subexpression$1"],postprocess:([t])=>t[0].text},{name:"parens",symbols:[Xe.has("oparen")?{type:"oparen"}:oparen,"temporalFilter",Xe.has("cparen")?{type:"cparen"}:cparen],postprocess:([t,e,r])=>({operator:"()",expr:e})},{name:"conjunction",symbols:[Xe.has("OR")?{type:"OR"}:OR]},{name:"conjunction",symbols:[Xe.has("AND")?{type:"AND"}:AND]}],ParserStart:"temporalFilter"};CB.default=stt,function(t){var e=T&&T.__createBinding||(Object.create?function(h,p,m,y){y===void 0&&(y=m);var g=Object.getOwnPropertyDescriptor(p,m);(!g||("get"in g?!p.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return p[m]}}),Object.defineProperty(h,y,g)}:function(h,p,m,y){y===void 0&&(y=m),h[y]=p[m]}),r=T&&T.__setModuleDefault||(Object.create?function(h,p){Object.defineProperty(h,"default",{enumerable:!0,value:p})}:function(h,p){h.default=p}),i=T&&T.__importStar||function(h){if(h&&h.__esModule)return h;var p={};if(h!=null)for(var m in h)m!=="default"&&Object.prototype.hasOwnProperty.call(h,m)&&e(p,h,m);return r(p,h),p},s=T&&T.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=void 0;const o=wn,u=s(CB),a=i(gB),l=v2;t.TemporalFilterExpression={parse(h){if(h.match(/^\s*$/))return{parsed:null,log:[]};const p=new a.Parser(a.Grammar.fromCompiled(u.default)),m=(0,l.run_parser)(h,p);return m.parsed&&(0,o.isTemporalFilter)(m.parsed)?{parsed:m.parsed,log:[]}:{parsed:null,log:m.log}},unparse(h){if(h===null)return"";switch(h.operator){case"null":return c(h,"null");case"in":return c(h,x(h.in));case"()":return"("+t.TemporalFilterExpression.unparse(h.expr)+")";case"in_last":return c(h,f(h));case"last":case"next":return c(h,`${h.operator} ${f(h)}`);case"before":return c(h,`before ${x(h.before)}`);case"after":return c(h,`after ${x(h.after)}`);case"to":return c(h,`${x(h.fromMoment)} to ${x(h.toMoment)}`);case"for":return c(h,`${x(h.begin)} for ${f(h)}`);case"or":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" or ");case"and":return h.members.map(p=>t.TemporalFilterExpression.unparse(p)).join(" and ")}}};function c(h,p){return"not"in h&&h.not?"not "+p:p}function f(h){return h.n==="1"?`1 ${h.units}`:`${h.n} ${h.units}s`}function x(h){switch(h.moment){case"literal":return h.literal;case"now":case"today":case"yesterday":case"tomorrow":return h.moment;case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":return h.which==="next"?"next "+h.moment:h.moment;case"this":case"next":case"last":return`${h.moment} ${h.units}`;case"ago":return`${f(h)} ago`;case"from_now":return`${f(h)} from now`}}}(Ele),function(t){var e=T&&T.__createBinding||(Object.create?function(a,l,c,f){f===void 0&&(f=c);var x=Object.getOwnPropertyDescriptor(l,c);(!x||("get"in x?!l.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(a,f,x)}:function(a,l,c,f){f===void 0&&(f=c),a[f]=l[c]}),r=T&&T.__exportStar||function(a,l){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&e(l,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),t.TemporalFilterExpression=t.StringFilterExpression=t.NumberFilterExpression=t.BooleanFilterExpression=void 0,r(wn,t);var i=$4;Object.defineProperty(t,"BooleanFilterExpression",{enumerable:!0,get:function(){return i.BooleanFilterExpression}});var s=hle;Object.defineProperty(t,"NumberFilterExpression",{enumerable:!0,get:function(){return s.NumberFilterExpression}});var o=yle;Object.defineProperty(t,"StringFilterExpression",{enumerable:!0,get:function(){return o.StringFilterExpression}});var u=Ele;Object.defineProperty(t,"TemporalFilterExpression",{enumerable:!0,get:function(){return u.TemporalFilterExpression}})}(I4);var k4={};Object.defineProperty(k4,"__esModule",{value:!0}),k4.TemporalFilterCompiler=void 0;const SB=et,Sd=qr,_le="yyyy",vle=`${_le}-LL`,bB=`${vle}-dd`,Cle=`${bB} HH`,Sle=`${Cle}:mm`,ys=`${Sle}:ss`;class ott{constructor(e,r,i="timestamp"){this.expr=e,this.timetype=i,this.d=r}time(e){return this.timetype==="timestamp"?e:this.d.sqlCast({},{node:"cast",e:{node:"genericSQLExpr",src:["",e],kids:{args:[]},sql:e},srcType:{type:"timestamp"},dstType:{type:"date"},safe:!1})}compile(e){const r=this.expr;switch(e.operator){case"after":return`${r} ${e.not?"<":">="} ${this.time(this.moment(e.after).end)}`;case"before":return`${r} ${e.not?">=":"<"} ${this.time(this.moment(e.before).begin.sql)}`;case"in":{const i=this.moment(e.in);return i.begin.sql===i.end?e.not?`${r} != ${this.time(i.end)} OR ${r} IS NULL`:`${r} = ${this.time(i.end)}`:this.isIn(e.not,i.begin.sql,i.end)}case"for":{const i=this.moment(e.begin),s=this.delta(i.begin,"+",e.n,e.units);return this.isIn(e.not,i.begin.sql,s.sql)}case"in_last":{const i=Number(e.n)-1,s=this.nowDot(e.units),o=i>0?this.delta(s,"-",i.toString(),e.units):s,u=this.delta(s,"+","1",e.units);return this.isIn(e.not,o.sql,u.sql)}case"to":{const i=this.moment(e.fromMoment),s=this.moment(e.toMoment);return this.isIn(e.not,i.begin.sql,s.begin.sql)}case"last":{const i=this.nowDot(e.units),s=this.delta(i,"-",e.n,e.units);return this.isIn(e.not,s.sql,i.sql)}case"next":{const i=this.nowDot(e.units),s=this.delta(i,"+","1",e.units),o=this.delta(i,"+",(Number(e.n)+1).toString(),e.units);return this.isIn(e.not,s.sql,o.sql)}case"null":return e.not?`${r} IS NOT NULL`:`${r} IS NULL`;case"()":{const i="("+this.compile(e.expr)+")";return e.not?`NOT ${i}`:i}case"and":case"or":return e.members.map(i=>this.compile(i)).join(` ${e.operator.toUpperCase()} `)}}expandLiteral(e){let r=e.literal;switch(e.units){case"year":{const i=Sd.DateTime.fromFormat(r,_le),s=this.literalNode(i.toFormat(ys)),o=i.plus({year:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"month":{const i=Sd.DateTime.fromFormat(r,vle),s=this.literalNode(i.toFormat(ys)),o=i.plus({month:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"day":{const i=Sd.DateTime.fromFormat(r,bB),s=this.literalNode(i.toFormat(ys)),o=i.plus({day:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"hour":{const i=Sd.DateTime.fromFormat(r,Cle),s=this.literalNode(i.toFormat(ys)),o=i.plus({hour:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"minute":{const i=Sd.DateTime.fromFormat(r,Sle),s=this.literalNode(i.toFormat(ys)),o=i.plus({minute:1});return{begin:s,end:this.literalNode(o.toFormat(ys)).sql}}case"week":{const o=Sd.DateTime.fromFormat(r.slice(0,10),bB).plus({day:1}).startOf("week").minus({day:1}),u=this.literalNode(o.toFormat(ys)),a=o.plus({days:7});return{begin:u,end:this.literalNode(a.toFormat(ys)).sql}}case"quarter":{const i=r.slice(0,4),s=r.slice(6);s==="1"?r=`${i}-01-01 00:00:00`:s==="2"?r=`${i}-03-01 00:00:00`:s==="3"?r=`${i}-06-01 00:00:00`:r=`${i}-09-01 00:00:00`;const o=this.literalNode(r),a=Sd.DateTime.fromFormat(r,ys).plus({months:3});return{begin:o,end:this.literalNode(a.toFormat(ys)).sql}}case void 0:case"second":return{begin:this.literalNode(r),end:r}}}literalNode(e){const r={node:"timeLiteral",typeDef:{type:"timestamp"},literal:e};return{...r,sql:this.d.sqlLiteralTime({},r)}}nowExpr(){return{node:"now",typeDef:{type:"timestamp"},sql:this.d.sqlNowExpr()}}n(e){return{node:"numberLiteral",literal:e,sql:e}}delta(e,r,i,s){const o={node:"delta",op:r,units:s,kids:{base:(0,SB.mkTemporal)(e,"timestamp"),delta:this.n(i)}};return{...o,sql:this.d.sqlAlterTimeExpr(o)}}dayofWeek(e){const r={node:"extract",e:(0,SB.mkTemporal)(e,"timestamp"),units:"day_of_week"};return{...r,sql:this.d.sqlTimeExtractExpr({},r)}}nowDot(e){const r={node:"trunc",e:this.nowExpr(),units:e};return{...r,sql:this.d.sqlTruncExpr({},r)}}thisUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e);return{begin:r,end:i.sql}}lastUnit(e){const r=this.nowDot(e);return{begin:this.delta(r,"-","1",e),end:r.sql}}nextUnit(e){const r=this.nowDot(e),i=this.delta(r,"+","1",e),s=this.delta(r,"+","2",e);return{begin:i,end:s.sql}}mod7(e){return this.d.hasModOperator?`(${e})%7`:`MOD(${e},7)`}moment(e){switch(e.moment){case"now":{const r=this.nowExpr();return{begin:r,end:r.sql}}case"literal":return this.expandLiteral(e);case"ago":case"from_now":{const r=this.nowDot(e.units),i=(0,SB.mkTemporal)(r,"timestamp"),s=this.delta(i,e.moment==="ago"?"-":"+",e.n,e.units);if(e.moment==="ago"&&e.n==="1")return{begin:s,end:r.sql};const o=Number(e.n)+(e.moment==="ago"?-1:1),u={...s,kids:{base:i,delta:this.n(o.toString())}};return{begin:s,end:this.d.sqlAlterTimeExpr(u)}}case"today":return this.thisUnit("day");case"yesterday":return this.lastUnit("day");case"tomorrow":return this.nextUnit("day");case"this":return this.thisUnit(e.units);case"last":return this.lastUnit(e.units);case"next":return this.nextUnit(e.units);case"monday":case"tuesday":case"wednesday":case"thursday":case"friday":case"saturday":case"sunday":{const r=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].indexOf(e.moment),i=this.dayofWeek(this.nowExpr()).sql;if(e.which==="next"){const a=`${this.mod7(`${r}-(${i}-1)+6`)}+1`,l=this.delta(this.thisUnit("day").begin,"+",a,"day"),c=this.delta(this.thisUnit("day").begin,"+",`${a}+1`,"day");return{begin:l,end:c.sql}}const s=`${this.mod7(`(${i}-1)-${r}+6`)}+1`,o=this.delta(this.thisUnit("day").begin,"-",s,"day"),u=this.delta(this.thisUnit("day").begin,"-",`(${s})-1`,"day");return{begin:o,end:u.sql}}}}isIn(e,r,i){let s=">=",o="<",u="AND";return e&&(u="OR",s="<",o=">="),r=this.time(r),i=this.time(i),`${this.expr} ${s} ${r} ${u} ${this.expr} ${o} ${i}`}}k4.TemporalFilterCompiler=ott,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FilterCompilers=void 0;const e=I4,r=k4;function i(u){return u.replace(/([%_\\])/g,"\\$1")}function s(u){return u===">"?"<=":u==="<"?">=":u===">="?"<":">"}function o(u,a){const l=` OR ${a} IS NULL`;return u.length===1?`${u[0]}${l}`:`(${u.join(" AND ")})${l}`}t.FilterCompilers={compile(u,a,l,c){if(a===null)return"true";if(u==="string"&&(0,e.isStringFilter)(a))return t.FilterCompilers.stringCompile(a,l,c);if(u==="number"&&(0,e.isNumberFilter)(a))return t.FilterCompilers.numberCompile(a,l,c);if(u==="boolean"&&(0,e.isBooleanFilter)(a))return t.FilterCompilers.booleanCompile(a,l,c);if((u==="date"||u==="timestamp")&&(0,e.isTemporalFilter)(a))return t.FilterCompilers.temporalCompile(a,l,c,u);throw new Error("INTERNAL ERROR: No filter compiler for "+u)},numberCompile(u,a,l){switch(u.operator){case"!=":case"=":{const c=u.operator==="="&&u.not||u.operator==="!="&&!u.not,f=u.values.join(", ");return u.values.length===1?c?`${a} != ${f} OR ${a} IS NULL`:`${a} = ${f}`:c?`${a} NOT IN (${f}) OR ${a} IS NULL`:`${a} IN (${f})`}case">":case"<":case">=":case"<=":return u.values.map(c=>`${a} ${u.operator} ${c}`).join(u.not?" AND ":" OR ");case"range":{let c=u.startOperator,f=u.endOperator,x=" AND ";return u.not&&(c=s(c),f=s(f),x=" OR "),`${a} ${c} ${u.startValue} ${x} ${a} ${f} ${u.endValue}`}case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"()":{const c="("+t.FilterCompilers.numberCompile(u.expr,a,l)+")";return u.not?`NOT ${c}`:c}case"and":case"or":return u.members.map(c=>t.FilterCompilers.numberCompile(c,a,l)).join(` ${u.operator.toUpperCase()} `)}},booleanCompile(u,a,l){switch(u.operator){case"false":return`${a} = false`;case"false_or_null":return`${a} IS NULL OR ${a} = false`;case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"true":return a}},stringCompile(u,a,l){switch(u.operator){case"null":return u.not?`${a} IS NOT NULL`:`${a} IS NULL`;case"empty":return u.not?`COALESCE(${a},'') != ''`:`COALESCE(${a},'') = ''`;case"=":{if(u.values.length===1){const f=u.not?"!=":"=",x=`${a} ${f} ${l.sqlLiteralString(u.values[0])}`;return u.not?`(${x} OR ${a} IS NULL)`:x}const c="("+u.values.map(f=>l.sqlLiteralString(f)).join(", ")+")";return u.not?`(${a} NOT IN ${c} OR ${a} IS NULL)`:`${a} IN ${c}`}case"()":{const c="("+t.FilterCompilers.stringCompile(u.expr,a,l)+")";return u.not?`not ${c}`:c}case"contains":{const c=u.values.map(f=>"%"+i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"starts":{const c=u.values.map(f=>i(f)+"%");return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"ends":{const c=u.values.map(f=>"%"+i(f));return u.not?o(c.map(f=>l.sqlLike("NOT LIKE",a,f)),a):c.map(f=>l.sqlLike("LIKE",a,f)).join(" OR ")}case"~":return u.not?o(u.escaped_values.map(c=>l.sqlLike("NOT LIKE",a,c)),a):u.escaped_values.map(c=>l.sqlLike("LIKE",a,c)).join(" OR ");case"and":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case"or":return u.members.map(f=>t.FilterCompilers.stringCompile(f,a,l)).join(" AND ");case",":{const c=[],f=[];let x=!1,h=!1,p=!1,m=!1;for(const E of u.members)switch(E.operator){case"or":case"and":case",":c.push(E);break;case"null":E.not?h=!0:x=!0;break;case"empty":E.not?(m=!0,h=!0):(p=!0,x=!0);break;default:(E.not?f:c).push(E)}if(p&&m||x&&h)return"false";let y="";if(c.length>0||x||p){m=!1,h=!1;const E=c.map(A=>t.FilterCompilers.stringCompile(A,a,l));p&&E.push(`${a} = ''`),x&&E.push(`${a} IS NULL`),y=E.join(" OR ")}let g="";if(f.length>0||m||h){const E=f.map(A=>t.FilterCompilers.stringCompile(A,a,l));m&&E.push(`${a} != ''`),h&&E.push(`${a} IS NOT NULL`),g=E.join(" AND ")}return y?g!==""?`(${y}) AND (${g})`:y:g!==""?g:"true"}}},temporalCompile(u,a,l,c){return new r.TemporalFilterCompiler(a,l,c).compile(u)}}}(dle),Object.defineProperty(Hs,"__esModule",{value:!0}),Hs.QueryModel=Hs.getResultStructDefForQuery=Hs.getResultStructDefForView=Hs.Segment=void 0;const utt=g2,att=p2,ltt=Xy,Ue=et,Fn=kt,M4=A2,ctt=gi,ftt=dle,xtt=I4;function ble(t){return t.map(e=>encodeURIComponent(e)).join("/")}function TB(t){return`'${t}'`}function dtt(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}function C2(t){const e=[];for(const r of t.fields.filter(Ue.fieldIsIntrinsic))e.push({type:r.type,sqlExpression:(0,Ue.getIdentifier)(r),rawName:(0,Ue.getIdentifier)(r),sqlOutputName:(0,Ue.getIdentifier)(r)});return e}class htt extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class nE{constructor(e=!0,r){this.parent=r,this.withs=[],this.udfs=[],this.pdts=[],this.dependenciesToMaterialize={},this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Fn.indent)(`
1441
1441
  (${e})
1442
1442
  `))}addUDF(e,r,i){var s;let{sql:o,lastStageName:u}=e.combineStages(!0);if(u===void 0)throw new Error("Internal Error: no stage to combine");o+=r.sqlCreateFunctionCombineLastStage(u,C2(i),(s=i.resultMetadata)===null||s===void 0?void 0:s.orderBy);const a=`${r.udfPrefix}${this.root().udfs.length}`;return o=r.sqlCreateFunction(a,o),this.root().udfs.push(o),a}addMaterializedQuery(e,r,i){var s;const o=r.name;if(!o)throw new Error(`Source ${e} on a unnamed query that is tagged as materialize, only named queries can be materialized.`);const u=(s=r.location)===null||s===void 0?void 0:s.url;if(!u)throw new Error(`Trying to materialize query ${o}, but its path is not set.`);const a=(0,M4.buildQueryMaterializationSpec)(u,o,i);return this.root().dependenciesToMaterialize[a.id]=a,a.id}addPDT(e,r){const i=this.combineStages(!1).sql+this.withs[this.withs.length-1],o=`scratch.${e+(0,Fn.generateHash)(i)}`;return this.root().pdts.push(r.sqlCreateTableAsSelect(o,i)),o}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let r=this.getName(0),i="WITH ",s="";for(let o=0;o<this.withs.length-(e?0:1);o++){const u=this.withs[o];if(r=this.getName(o),u===void 0)throw new Error(`Expected sql WITH to be present for stage ${r}.`);s+=`${i}${r} AS (
1443
1443
  ${(0,Fn.indent)(u)})
@@ -1445,7 +1445,7 @@ ${(0,Fn.indent)(u)})
1445
1445
  `),i=this.pdts.join(`
1446
1446
  `),s=this.combineStages(!1).sql;return r+i+s+this.withs[e]}generateCoorelatedSubQuery(e,r){var i,s;return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),C2(r),(s=r.resultMetadata)===null||s===void 0?void 0:s.orderBy):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,C2(r),(i=r.resultMetadata)===null||i===void 0?void 0:i.orderBy)}}class rE{constructor(){this.totalGroupSet=-1}withWhere(e){const r=new rE;return r.whereSQL=e,r.applyValue=this.applyValue,r.totalGroupSet=this.totalGroupSet,r}withApply(e){const r=new rE;return r.whereSQL=this.whereSQL,r.applyValue=e,r.totalGroupSet=this.totalGroupSet,r}withTotal(e){const r=new rE;return r.whereSQL=this.whereSQL,r.applyValue=this.applyValue,r.totalGroupSet=e,r}}class ptt{constructor(e){this.referenceId=e??(0,utt.v4)()}getChildByName(e){}}let RB=class extends ptt{constructor(e,r,i){super(i),this.fieldDef=e,this.parent=r,this.fieldDef=e}getIdentifier(){return(0,Ue.getIdentifier)(this.fieldDef)}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;return e.structDef.type==="record"?e.getJoinableParent():e}isAtomic(){return(0,Ue.isAtomic)(this.fieldDef)}caseGroup(e,r){return e.length===0?r:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
1447
1447
  ${r}
1448
- END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Ue.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Fn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Fn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Fn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Fn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Fn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Fn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((S,b)=>b<c.length&&this.getParamForArgIndex(l.params,b).allowedTypes.every(O=>(0,Ue.isLiteral)(O.evalSpace))?c[b]:(0,Fn.composeSQLExpr)([S])),A=E.slice(0,p.length),_=E.slice(p.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:m[b].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Ue.isLiteral)(_.evalSpace))?g:(0,Fn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Ue.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Fn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Dle(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Dle(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Qr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const S of C){typeof S.field=="string"?v={name:S.field,fif:r.getField(S.field)}:v=r.getFieldByNumber(S.field);const b=v.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(b))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${S.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${S.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const S=o.params.findIndex(R=>R.name===C),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new rE){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Ue.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Ue.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Ue.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(0,xtt.isFilterExpression)(a.filter))return ftt.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Ue.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Ue.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function P4(t){return t instanceof Qs&&t.isCalculated()}function Tle(t){return t instanceof Qs&&t.isAggregate()}function Qr(t){return t instanceof Qs&&!t.isCalculated()&&!t.isAggregate()}class Qs extends RB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class mtt extends Qs{}class gtt extends Qs{}class DB extends Qs{}class ytt extends Qs{}class Ett extends Qs{}class OB extends Qs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Ue.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new OB(r,this.parent)}}class wB extends Qs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new wB(r,this.parent)}}class Att extends Qs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Rle=9;function Dle(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Rle);let a=`(${`
1448
+ END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,r,i,s){const o=r.getFieldByName(i.path);return(0,Ue.hasExpression)(o.fieldDef)?`(${this.exprToSQL(e,o.parent,o.fieldDef.e,s)})`:o.generateExpression(e)}generateOutputFieldFragment(e,r,i,s){return`(${e.getField(i.name).getAnalyticalSQL(!1)})`}*stringsFromSQLExpression(e,r,i,s){const o=[...i.kids.args];for(const u of i.src){yield u;const a=o.shift();a&&(yield this.exprToSQL(e,r,a,s))}}getParameterMap(e,r){return new Map(e.params.map((i,s)=>{const o=i.isVariadic?(0,Fn.range)(s,r):[s];return[i.name,{param:i,argIndexes:o}]}))}expandFunctionCall(e,r,i,s,o){function u(c){const f=[];for(let x=0;x<c.length;)f.push(c[x]),x+=1,x<c.length&&f.push(",");return f}const a=this.getParameterMap(r,i.length);if(r.dialect[e]===void 0)throw new Error(`Function is not defined for '${e}' dialect`);return(0,Fn.exprMap)(r.dialect[e].e,c=>{var f,x;if(c.node==="spread"){const h=c.e;if(h.node!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const p=a.get(h.name);if(p===void 0)return c;const m=p.argIndexes.map(y=>i[y]);return(0,Fn.composeSQLExpr)(u(m))}else if(c.node==="function_parameter"){const h=a.get(c.name);if(h===void 0)return c;if(h.param.isVariadic){const p=h.argIndexes.map(m=>i[m]);return(0,Fn.composeSQLExpr)(u(p))}else return i[h.argIndexes[0]]}else{if(c.node==="aggregate_order_by")return s?(0,Fn.composeSQLExpr)([` ${(f=c.prefix)!==null&&f!==void 0?f:""}${s}${(x=c.suffix)!==null&&x!==void 0?x:""}`]):{node:""};if(c.node==="aggregate_limit")return o?(0,Fn.composeSQLExpr)([` ${o}`]):{node:""}}return c})}getFunctionOrderBy(e,r,i,s,o,u){if(s.length!==0)return"ORDER BY "+s.map(a=>{var l;const c=(l=u.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&l!==void 0?l:0,f=a.node==="functionOrderBy"?a.e:o[c],x=this.generateDimFragment(e,r,f,i),h=a.dir==="asc"?" ASC":a.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,r,i,s,o,u,a,l){if(u)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${a}`);const c=this.generateDimFragment(e,r,i,l),f=s?this.generateDimFragment(e,r,s,l):"";return this.parent.dialect.sqlStringAggDistinct(o,c,f)}getParamForArgIndex(e,r){const i=e.slice(0,r).find(s=>s.isVariadic);return i??e[r]}generateFunctionCallExpression(e,r,i,s){var o,u,a;const l=i.overload,c=i.kids.args,f=(o=i.overload.isSymmetric)!==null&&o!==void 0?o:!1,x=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)&&!f&&this.generateDistinctKeyIfNecessary(e,r,i.structPath),h=i.limit?`LIMIT ${i.limit}`:void 0;if(i.name==="string_agg"&&x&&!r.dialect.supportsAggDistinct&&r.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,r,c[0],c[1],x,i.kids.orderBy,r.dialect.name,s);if(x){if(!r.dialect.supportsAggDistinct)throw new Error(`Function \`${i.name}\` does not support fanning out in ${r.dialect.name}`);const p=c.map(g=>this.generateDimFragment(e,r,g,s)),m=(u=i.kids.orderBy)!==null&&u!==void 0?u:[],y=m.map(g=>{var E;const A=(E=l.dialect[r.dialect.name].defaultOrderByArgIndex)!==null&&E!==void 0?E:0,_=g.node==="functionOrderBy"?g.e:c[A];return this.generateDimFragment(e,r,_,s)});return r.dialect.sqlAggDistinct(x,[...p,...y],g=>{const E=g.map((S,b)=>b<c.length&&this.getParamForArgIndex(l.params,b).allowedTypes.every(O=>(0,Ue.isLiteral)(O.evalSpace))?c[b]:(0,Fn.composeSQLExpr)([S])),A=E.slice(0,p.length),_=E.slice(p.length).map((S,b)=>({node:"functionOrderBy",e:S,dir:m[b].dir})),v=this.getFunctionOrderBy(e,r,s,_,A,l),C=this.expandFunctionCall(r.dialect.name,l,A,v,h);return this.exprToSQL(e,r,C,s)})}else{const p=(0,Ue.expressionIsAggregate)(l.returnType.expressionType)?c.map((g,E)=>this.getParamForArgIndex(l.params,E).allowedTypes.every(_=>(0,Ue.isLiteral)(_.evalSpace))?g:(0,Fn.composeSQLExpr)([this.generateDimFragment(e,r,g,s)])):c,m=i.kids.orderBy?this.getFunctionOrderBy(e,r,s,i.kids.orderBy,c,l):"",y=this.expandFunctionCall(r.dialect.name,l,p,m,h);if((0,Ue.expressionIsAnalytic)(l.returnType.expressionType)){const g=((a=i.partitionBy)!==null&&a!==void 0?a:[]).map(E=>`(${e.getField(E).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(r.dialect.name,e,r,y,l,s,c,g,m)}return this.exprToSQL(e,r,y,s)}}generateSpread(e,r,i,s){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,r,i,s){var o;const u=i.path[0];(o=r.eventStream)===null||o===void 0||o.emit("source-argument-compiled",{name:u});const a=r.arguments()[u];if(a.value)return this.exprToSQL(e,r,a.value,s);throw new Error(`Can't generate SQL, no value for ${i.path}`)}generateFilterFragment(e,r,i,s){const o=new Fn.AndChain(s.whereSQL);for(const u of i.kids.filterList)o.add(this.exprToSQL(e,r,u.e,s.withWhere()));return this.exprToSQL(e,r,i.kids.e,s.withWhere(o.sql()))}generateDimFragment(e,r,i,s){let o=this.exprToSQL(e,r,i,s);return s.whereSQL&&(o=`CASE WHEN ${s.whereSQL} THEN ${o} END`),o}generateUngroupedFragment(e,r,i,s){if(s.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let o,u;if(i.fields&&i.fields.length>0){const x=i.fields.sort().join("|")+i.node;if(u=e.ungroupedSets.get(x),u===void 0)throw new Error(`Internal Error, cannot find groupset with key ${x}`);o=u.groupSet}else o=e.parent?e.parent.groupSet:0;const a=this.exprToSQL(e,r,i.e,s.withTotal(o)),l=e.getUngroupPartitions(u);let c="";const f=l.map(x=>x.getAnalyticalSQL(!0)).join(", ");return f.length>0&&(c=`PARTITION BY ${f}`),`MAX(${a}) OVER (${c})`}generateDistinctKeyIfNecessary(e,r,i){let s=r;if(i&&(s=this.parent.root().getStructByName(i)),s.needsSymetricCalculation(e))return s.getDistinctKey().generateExpression(e)}generateSumFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);let a;return u?this.parent.dialect.supportsSumDistinctFunction?a=this.parent.dialect.sqlSumDistinct(u,o,"SUM"):a=Dle(this.parent.dialect,o,u):a=`SUM(${o})`,`COALESCE(${a},0)`}generateSymmetricFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s);return`${i.function==="distinct"?"count(distinct ":i.function+"("}${o})`}generateAvgFragment(e,r,i,s){const o=this.generateDimFragment(e,r,i.e,s),u=this.generateDistinctKeyIfNecessary(e,r,i.structPath);if(u){let a=u;s.whereSQL&&(a=`CASE WHEN ${s.whereSQL} THEN ${u} END`);let l,c;return this.parent.dialect.supportsSumDistinctFunction?c=this.parent.dialect.sqlSumDistinct(u,o,"AVG"):(l=Dle(this.parent.dialect,o,u),c=`(${l})/NULLIF(COUNT(DISTINCT CASE WHEN ${o} IS NOT NULL THEN ${a} END),0)`),c}else return`AVG(${o})`}generateCountFragment(e,r,i,s){let o="COUNT(",u="1",a=r;i.structPath&&(a=this.parent.root().getStructByName(i.structPath));const l=a.getJoinableParent().getIdentifier(),c=e.root().joins.get(l);if(!c)throw new Error(`Join ${l} not found in result set`);return(!c.leafiest||c.makeUniqueKey)&&(o="COUNT(DISTINCT ",u=a.getDistinctKey().generateExpression(e)),s.whereSQL?`${o}CASE WHEN ${s.whereSQL} THEN ${u} END)`:`${o}${u})`}generateSourceReference(e,r,i){return i.path===void 0?r.getSQLIdentifier():r.getFieldByName(i.path).getIdentifier()}getAnalyticPartitions(e,r){const i=[];let s=e.parent;for(;s!==void 0;){const u=s.fields(a=>Qr(a.f)&&a.fieldUsage.type==="result").map(a=>a.getAnalyticalSQL(!0));i.push(...u),s=s.parent}return r&&i.push(...r),i}generateAnalyticFragment(e,r,i,s,o,u,a,l,c){const f=r.root().isComplexQuery,x=this.getAnalyticPartitions(r,l),h=[...f?["group_set"]:[],...x],p=h.length>0?`PARTITION BY ${h.join(", ")}`:"";let m=c??"";const y=o.dialect[e];if(!c&&y.needsWindowOrderBy){const _=[];let v;const C=r.firstSegment.orderBy||r.calculateDefaultOrderBy();for(const S of C){typeof S.field=="string"?v={name:S.field,fif:r.getField(S.field)}:v=r.getFieldByNumber(S.field);const b=v.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(b))if(r.firstSegment.type==="reduce"){const R=v.fif.getAnalyticalSQL(!1);_.push(` ${R} ${S.dir||"ASC"}`)}else r.firstSegment.type==="project"&&_.push(` ${v.fif.f.generateExpression(r)} ${S.dir||"ASC"}`)}_.length>0&&(m=" "+this.parent.dialect.sqlOrderBy(_,"analytical"))}let g="";if(y.between){const[_,v]=[y.between.preceding,y.between.following].map(C=>{if(C===-1)return"UNBOUNDED";if(typeof C=="number")return C;const S=o.params.findIndex(R=>R.name===C),b=a[S];if(b.node!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return b.literal});g=`ROWS BETWEEN ${_} PRECEDING AND ${v} FOLLOWING`}let A=`${this.exprToSQL(r,i,s,u)} OVER(${p} ${m} ${g})`;return f&&(A=`CASE WHEN group_set=${r.groupSet} THEN ${A} END`),A}generateCaseSQL(e){const r=["CASE"];e.kids.caseValue!==void 0&&r.push(`${e.kids.caseValue.sql}`);for(let i=0;i<e.kids.caseWhen.length;i+=1)r.push(`WHEN ${e.kids.caseWhen[i].sql} THEN ${e.kids.caseThen[i].sql}`);return e.kids.caseElse!==void 0&&r.push(`ELSE ${e.kids.caseElse.sql}`),r.push("END"),r.join(" ")}exprToSQL(e,r,i,s=new rE){var o;const u=function(f,x){const h=f.exprToSQL(e,r,x,s);return(0,Ue.exprHasKids)(x)?`(${h})`:h};let a=i;if((0,Ue.exprHasE)(i)){a={...i};const f=u(this,a.e);a.e={...a.e,sql:f}}else if((0,Ue.exprHasKids)(i)){a={...i};const f=i.kids;for(const[x,h]of Object.entries(f))h!==null&&(Array.isArray(h)?a.kids[x]=h.map(p=>({...p,sql:u(this,p)})):a.kids[x]={...f[x],sql:u(this,h)})}const l=e.getQueryInfo(),c=this.parent.dialect.exprToSQL(l,a);if(c)return c;switch(a.node){case"field":return this.generateFieldFragment(e,r,a,s);case"parameter":return this.generateParameterFragment(e,r,a,s);case"filteredExpr":return this.generateFilterFragment(e,r,a,s);case"all":case"exclude":return this.generateUngroupedFragment(e,r,a,s);case"genericSQLExpr":return Array.from(this.stringsFromSQLExpression(e,r,a,s)).join("");case"aggregate":{let f="";if(a.function==="sum")f=this.generateSumFragment(e,r,a,s);else if(a.function==="avg")f=this.generateAvgFragment(e,r,a,s);else if(a.function==="count")f=this.generateCountFragment(e,r,a,s);else if(a.function==="min"||a.function==="max"||a.function==="distinct")f=this.generateSymmetricFragment(e,r,a,s);else throw new Error(`Internal Error: Unknown aggregate function ${a.function}`);if(e.root().isComplexQuery){let x=e.groupSet;return s.totalGroupSet!==-1&&(x=s.totalGroupSet),this.caseGroup([x],f)}return f}case"function_parameter":throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");case"outputField":return this.generateOutputFieldFragment(e,r,a,s);case"function_call":return this.generateFunctionCallExpression(e,r,a,s);case"spread":return this.generateSpread(e,r,a,s);case"source-reference":return this.generateSourceReference(e,r,a);case"+":case"-":case"*":case"%":case"/":case">":case"<":case">=":case"<=":case"=":return`${a.kids.left.sql}${a.node}${a.kids.right.sql}`;case"!=":return`COALESCE(${`${a.kids.left.sql}!=${a.kids.right.sql}`},true)`;case"and":case"or":return`${a.kids.left.sql} ${a.node} ${a.kids.right.sql}`;case"coalesce":return`COALESCE(${a.kids.left.sql},${a.kids.right.sql})`;case"in":{const f=a.kids.oneOf.map(x=>x.sql).join(",");return`${a.kids.e.sql} ${a.not?"NOT IN":"IN"} (${f})`}case"like":case"!like":{const f=a.node==="like"?"LIKE":"NOT LIKE",x=a.kids.right.node==="stringLiteral"?this.parent.dialect.sqlLike(f,(o=a.kids.left.sql)!==null&&o!==void 0?o:"",a.kids.right.literal):`${a.kids.left.sql} ${f} ${a.kids.right.sql}`;return a.node==="like"?x:`COALESCE(${x},true)`}case"()":return`(${a.e.sql})`;case"not":return`COALESCE(NOT ${a.e.sql},TRUE)`;case"unary-":return`-${a.e.sql}`;case"is-null":return`${a.e.sql} IS NULL`;case"is-not-null":return`${a.e.sql} IS NOT NULL`;case"true":case"false":return a.node;case"null":return"NULL";case"case":return this.generateCaseSQL(a);case"":return"";case"filterCondition":return a.e.sql?(a.sql=a.e.sql,a.sql):"";case"functionDefaultOrderBy":case"functionOrderBy":return"";case"compositeField":return"{COMPOSITE_FIELD}";case"filterMatch":if((a.dataType==="string"||a.dataType==="number"||a.dataType==="date"||a.dataType==="timestamp"||a.dataType==="boolean")&&(a.filter===null||(0,xtt.isFilterExpression)(a.filter)))return ftt.FilterCompilers.compile(a.dataType,a.filter,a.e.sql||"",this.parent.dialect);throw new Error(`Internal Error: Filter Compiler Undefined Type '${a.dataType}'`);default:throw new Error(`Internal Error: Unknown expression node '${a.node}' ${JSON.stringify(a,void 0,2)}`)}}isNestedInParent(e){switch(e.type){case"record":case"array":return!0;default:return!1}}isArrayElement(e){return e.type==="array"&&e.elementTypeDef.type!=="record_element"}generateExpression(e){if((0,Ue.hasExpression)(this.fieldDef))return this.exprToSQL(e,this.parent,this.fieldDef.e);for(let r=this.parent;r!==void 0;r=r.parent)if(r.structDef.type==="record"&&(0,Ue.hasExpression)(r.structDef)&&r.recordAlias===void 0){if(!r.parent)throw new Error("Inconcievable record ancestor with expression but no parent");const i=this.exprToSQL(e,r.parent,r.structDef.e);r.informOfAliasValue(i)}return this.parent.sqlChildReference(this.fieldDef.name,this.parent.structDef.type==="record"?{result:e,field:this}:void 0)}};function P4(t){return t instanceof Qs&&t.isCalculated()}function Tle(t){return t instanceof Qs&&t.isAggregate()}function Qr(t){return t instanceof Qs&&!t.isCalculated()&&!t.isAggregate()}class Qs extends RB{constructor(e,r,i){super(e,r,i),this.fieldDef=e}includeInWildcard(){return!0}isCalculated(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.hasExpression)(this.fieldDef)&&(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}isAtomic(){return!0}}class mtt extends Qs{}class gtt extends Qs{}class DB extends Qs{}class ytt extends Qs{}class Ett extends Qs{}class OB extends Qs{generateExpression(e){const r=this.fieldDef,i=super.generateExpression(e);if(r.timeframe){const s={node:"trunc",e:(0,Ue.mkTemporal)({node:"genericSQLExpr",src:[i],kids:{args:[]}},"date"),units:r.timeframe};return this.exprToSQL(e,this.parent,s)}else return i}getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new OB(r,this.parent)}}class wB extends Qs{getChildByName(e){const r={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new wB(r,this.parent)}}class Att extends Qs{generateExpression(e){var r;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.structDef.type==="array"){const i=(r=this.parent.parent)===null||r===void 0?void 0:r.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(i||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__row_id","string"))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"table","__distinct_key","string")}includeInWildcard(){return!1}}const Rle=9;function Dle(t,e,r){const s=t.sqlSumDistinctHashedKey(r),o=10**(9-Rle);let a=`(${`
1449
1449
  (
1450
1450
  SUM(DISTINCT
1451
1451
  (CAST(ROUND(COALESCE(${e},0)*(${o}*1.0), ${Rle}) AS ${t.defaultDecimalType}) +
@@ -1552,7 +1552,7 @@ ${i} ${o}: [`,u.length>0&&(s+=`
1552
1552
  ${i} `),s+="]")}return s}*walk(){for(const e of Object.keys(this.children)){const r=this.children[e];if(r instanceof ja)yield r;else for(const i of r)yield i}}varInfo(){let e="";for(const[r,i]of Object.entries(this))r!=="elementType"&&(typeof i=="boolean"?e+=i?` ${r}`:` !${r}`:(typeof i=="string"||typeof i=="number")&&(e+=` ${r}=${i}`));return e}internalError(e){return new Error(`INTERNAL ERROR IN TRANSLATION: ${e}`)}needs(e){for(const r of this.walk()){const i=r.needs(e);if(i)return i}}inExperiment(e,r=!1){var i;const s=(i=this.translator())===null||i===void 0?void 0:i.compilerFlags.tag("experimental");return s&&(s.bare()||s.has(e))?!0:(r||this.logError("experiment-not-enabled",{experimentId:e}),!1)}}Ze.MalloyElement=ja;class cnt extends ja{constructor(){super(...arguments),this.elementType="unimplemented",this.reported=!1}}Ze.Unimplemented=cnt;class $B extends ja{constructor(e){super(),this.name=e,this.elementType="modelEntryReference"}get refString(){return this.name}toString(){return this.refString}getNamed(){var e;return(e=this.modelEntry(this))===null||e===void 0?void 0:e.entry}}Ze.ModelEntryReference=$B;class fnt extends ja{constructor(e){super(),this.id=e,this.elementType="experimentalExperiment"}execute(e){this.inExperiment(this.id)}}Ze.ExperimentalExperiment=fnt;function jle(t){return t.execute!==void 0}Ze.isDocStatement=jle;function xnt(t){return t instanceof oE||jle(t)}Ze.isDocStatementOrDocStatementList=xnt;class qle extends ja{constructor(e){super(),this.elements=e,this.newContents()}newContents(){this.has({listOf:this.elements})}get list(){return this.elements}empty(){return this.elements.length===0}notEmpty(){return this.elements.length>0}push(...e){return this.elements.push(...e),this.newContents(),this.elements}needs(e){for(const r of this.elements){const i=r.needs(e);if(i)return i}}}Ze.ListOf=qle;class oE extends qle{constructor(){super(...arguments),this.elementType="topLevelStatements",this.execCursor=0,this.isNoteableObj=!0,this.extendNote=Ule.extendNoteMethod,this.noteCursor=0}executeList(e){for(;this.execCursor<this.elements.length;){const r=this.elements[this.execCursor];if(this.noteCursor===this.execCursor&&(this.note&&(0,Ule.isNoteable)(r)&&r.extendNote(this.note),this.noteCursor+=1),r instanceof oE){const i=r.executeList(e);if(i)return i}else{const i=r.needs(e);if(i)return i;r.execute(e)}this.execCursor+=1}}}Ze.DocStatementList=oE;const dnt="5a79a191-06bc-43cf-9b12-58741cd82970";function Hle(t){const e=t.inherits?Hle(t.inherits):[];return t.blockNotes&&e.push(...t.blockNotes.map(r=>r.text)),t.notes&&e.push(...t.notes.map(r=>r.text)),e}function hnt(t){const e=Hle(t).join("");return(0,lnt.v5)(e,dnt)}class BB extends ja{constructor(e){super(),this.elementType="document",this.globalNameSpace=new ant.GlobalNameSpace,this.documentModel={},this.queryList=[],this.didInitModel=!1,this.annotation={},this.experiments=new int.Tag({}),this.modelAnnotationTodoList=[],this.dialectNameSpaces=new Map,this.statements=new oE(e),this.has({statements:e})}initModelDef(e){if(!this.didInitModel){if(this.documentModel={},this.queryList=[],e){e.annotation&&(this.annotation.inherits=e.annotation);for(const[r,i]of Object.entries(e.contents)){const s=structuredClone(i);if((0,z4.isSourceDef)(s)||s.type==="query"||s.type==="function"){const o=e.exports.includes(r);this.setEntry(r,{entry:s,exported:o})}}}this.didInitModel=!0}}compile(){const e=this.statements.executeList(this),r=this.modelDef();if(e===void 0)for(const s of this.queryList)s.modelAnnotation===void 0&&r.annotation&&(s.modelAnnotation=r.annotation);if(r.annotation)for(const s of this.modelAnnotationTodoList)s.modelAnnotation||(s.modelAnnotation=r.annotation);return{modelDef:{...r,queryList:this.queryList},needs:e}}rememberToAddModelAnnotations(e){this.modelAnnotationTodoList.push(e)}hasAnnotation(){return this.annotation.notes&&this.annotation.notes.length>0||this.annotation.inherits!==void 0}currentModelAnnotation(){if(this.hasAnnotation()){const e={...this.annotation,id:""};return e.id=hnt(e),e}}modelDef(){const e={name:"",exports:[],contents:{},queryList:[],dependencies:{}};this.hasAnnotation()&&(e.annotation=this.currentModelAnnotation());for(const r in this.documentModel){const i=this.documentModel[r].entry;if((0,z4.isSourceDef)(i)||i.type==="query"){this.documentModel[r].exported&&e.exports.push(r);const s=structuredClone(i);s.modelAnnotation===void 0&&e.annotation&&(s.modelAnnotation=e.annotation),e.contents[r]=s}}return e}getEntry(e){var r;return(r=this.globalNameSpace.getEntry(e))!==null&&r!==void 0?r:this.documentModel[e]}setEntry(e,r){this.globalNameSpace.getEntry(e)!==void 0&&this.logError("name-conflict-with-global",`Cannot redefine '${e}', which is in global namespace`),(0,z4.isSourceDef)(r.entry)&&this.checkExperimentalDialect(this,r.entry.dialect),this.documentModel[e]=r}checkExperimentalDialect(e,r){const i=this.translator();i&&i.firstReferenceToDialect(r)&&(0,Ple.getDialect)(r).experimental&&!i.experimentalDialectEnabled(r)&&e.logError("experimental-dialect-not-enabled",{dialect:r})}getDialectNamespace(e){if(this.dialectNameSpaces.has(e))return this.dialectNameSpaces.get(e);const r=(0,Ple.getDialect)(e),i=new unt.DialectNameSpace(r);return this.dialectNameSpaces.set(e,i),i}}Ze.Document=BB;var W4={},R2={},nn={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.atomicDef=t.inspect=t.typeEq=t.typeIn=t.eq=t.any=t.anyAtomicT=t.aggregateBoolT=t.viewT=t.errorT=t.boolT=t.timestampT=t.dateT=t.stringT=t.numberT=t.nullT=void 0;const e=Yi,r=dt;function i(f,x="scalar",h="constant"){return{type:f,expressionType:x,evalSpace:h,compositeFieldUsage:(0,r.emptyCompositeFieldUsage)()}}t.nullT=i("null"),t.numberT=i("number"),t.stringT=i("string"),t.dateT=i("date"),t.timestampT=i("timestamp"),t.boolT=i("boolean"),t.errorT=i("error"),t.viewT=i("turtle"),t.aggregateBoolT=i("boolean","aggregate"),t.anyAtomicT=[t.numberT,t.stringT,t.dateT,t.timestampT,t.boolT];function s(f,x){return f?x.find(p=>o(p,f))!==void 0:!1}t.any=s;function o(f,x){return x!==void 0&&e.TD.eq(f,x)&&f.expressionType===x.expressionType}t.eq=o;function u(f,x){return f?x.find(p=>a(p,f))!==void 0:!1}t.typeIn=u;function a(f,x,h=!1,p=!0){const m=e.TD.eq(f,x),y=h&&(f.type==="null"||x.type==="null"),g=p&&(f.type==="error"||x.type==="error");return m||y||g}t.typeEq=a;function l(...f){return f.map(h=>{if(h){let p=h.type;return(0,e.expressionIsScalar)(h.expressionType)||(p=`${h.expressionType} ${p}`),p}return"undefined"}).join(",")}t.inspect=l;function c(f){if(e.TD.isAtomic(f))switch(f.type){case"array":return(0,e.isRepeatedRecord)(f)?{type:"array",elementTypeDef:f.elementTypeDef,fields:f.fields}:{type:"array",elementTypeDef:f.elementTypeDef};case"record":return{type:"record",fields:f.fields};case"number":return f.numberType?{type:"number",numberType:f.numberType}:{type:"number"};case"sql native":return f.rawType?{type:"sql native",rawType:f.rawType}:{type:"sql native"};default:return{type:f.type}}return{type:"error"}}t.atomicDef=c})(nn);var Wr={},Yc={};Object.defineProperty(Yc,"__esModule",{value:!0}),Yc.canMakeEntry=Yc.SpaceEntry=void 0;class pnt{}Yc.SpaceEntry=pnt;function mnt(t){return"makeEntry"in t}Yc.canMakeEntry=mnt,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.SpaceField=void 0;const gnt=Yc,ynt=dt;class Ent extends gnt.SpaceEntry{constructor(){super(...arguments),this.refType="field"}fieldTypeFromFieldDef(e){var r,i,s;const o=e.expressionType||"scalar";return{...e,expressionType:o,evalSpace:"input",compositeFieldUsage:(r=e.compositeFieldUsage)!==null&&r!==void 0?r:((i=e.e)===null||i===void 0?void 0:i.node)==="compositeField"?{fields:[(s=e.as)!==null&&s!==void 0?s:e.name],joinedUsage:{}}:(0,ynt.emptyCompositeFieldUsage)()}}getQueryFieldDef(e){}fieldDef(){}constructorFieldDef(){}}Wr.SpaceField=Ent;var Ant=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_nt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vnt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ant(e,t,r);return _nt(e,t),e};Object.defineProperty(R2,"__esModule",{value:!0}),R2.ViewField=void 0;const Cnt=dt,Snt=vnt(nn),bnt=Wr;class Tnt extends bnt.SpaceField{constructor(e){super(),this.inSpace=e}typeDesc(){var e;const r=this.fieldDef();return{...Snt.viewT,compositeFieldUsage:(e=r.compositeFieldUsage)!==null&&e!==void 0?e:(0,Cnt.emptyCompositeFieldUsage)()}}}R2.ViewField=Tnt,Object.defineProperty(W4,"__esModule",{value:!0}),W4.ASTViewField=void 0;const Rnt=R2;class Dnt extends Rnt.ViewField{constructor(e,r,i){super(e),this.view=r,this.name=i,this.turtleDef=void 0}getQueryFieldDef(e){return this.view.getFieldDef(e)}fieldDef(){return this.turtleDef===void 0&&(this.turtleDef=this.view.getFieldDef(this.inSpace)),this.turtleDef}}W4.ASTViewField=Dnt,Object.defineProperty(sE,"__esModule",{value:!0}),sE.ViewFieldDeclaration=void 0;const Ont=Ze,wnt=zr,Fnt=S2,Nnt=W4;class Lnt extends Ont.MalloyElement{constructor(e,r){super({view:r}),this.name=e,this.view=r,this.elementType="view-field-declaration",this.isNoteableObj=!0,this.extendNote=wnt.extendNoteMethod}makeEntry(e){const r=new Nnt.ASTViewField(e,this,this.name);e.newEntry(this.name,this,r)}getName(){return this.name}getFieldDef(e){const{pipeline:r,annotation:i}=this.view.pipelineComp(e),s=(0,Fnt.detectAndRemovePartialStages)(r,this);return{type:"turtle",name:this.name,pipeline:s,annotation:{...this.note,inherits:i},location:this.location}}}sE.ViewFieldDeclaration=Lnt;var Wn={};Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.LegalRefinementStage=Wn.QueryClass=void 0;var Qle;(function(t){t.Index="index",t.Project="project",t.Grouping="grouping"})(Qle||(Wn.QueryClass=Qle={}));var zle;(function(t){t[t.Single=0]="Single",t[t.Head=1]="Head",t[t.Tail=2]="Tail"})(zle||(Wn.LegalRefinementStage=zle={}));var Int=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),$nt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Bnt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Int(e,t,r);return $nt(e,t),e};Object.defineProperty(iE,"__esModule",{value:!0}),iE.NestFieldDeclaration=void 0;const knt=Bnt(et),Mnt=S2,Pnt=sE,Wle=Wn;class Unt extends Pnt.ViewFieldDeclaration{constructor(){super(...arguments),this.elementType="nest-field-declaration",this.queryRefinementStage=Wle.LegalRefinementStage.Single,this.forceQueryClass=Wle.QueryClass.Grouping,this.turtleDef=void 0}queryExecute(e){e.resultFS.pushFields(this)}getFieldDef(e){if(this.turtleDef)return this.turtleDef;if(e.isQueryFieldSpace()){const{pipeline:r,annotation:i}=this.view.pipelineComp(e,e.outputSpace()),s=r[0]&&knt.isQuerySegment(r[0])?r[0].compositeFieldUsage:void 0,o=(0,Mnt.detectAndRemovePartialStages)(r,this);return this.turtleDef={type:"turtle",name:this.name,pipeline:o,annotation:{...this.note,inherits:i},location:this.location,compositeFieldUsage:s},this.turtleDef}throw this.internalError("Unexpected namespace for nest")}}iE.NestFieldDeclaration=Unt;var D2={},yi={};Object.defineProperty(yi,"__esModule",{value:!0}),yi.ErrorFactory=void 0;const Gle="~malformed~";class kB{static get structDef(){return{type:"table",name:Gle,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],errorFactory:!0}}static get joinDef(){return{type:"table",name:Gle,dialect:"~malformed~",connection:"~unknown~",tablePath:"//undefined_error_table_path",fields:[],join:"one",matrixOperation:"left",errorFactory:!0}}static didCreate(e){return e.type==="table"&&"errorFactory"in e}static get query(){return{structRef:kB.structDef,pipeline:[]}}static get reduceSegment(){return{type:"reduce",queryFields:[]}}static get projectSegment(){return{type:"project",queryFields:[]}}static get indexSegment(){return{type:"index",indexFields:[]}}}yi.ErrorFactory=kB,Object.defineProperty(D2,"__esModule",{value:!0}),D2.DefineSourceList=D2.DefineSource=void 0;const jnt=yi,Vle=Ze,qnt=zr;class Hnt extends Vle.MalloyElement{constructor(e,r,i,s){super(),this.name=e,this.sourceExpr=r,this.exported=i,this.parameters=s,this.elementType="defineSource",this.isNoteableObj=!0,this.extendNote=qnt.extendNoteMethod,r&&this.has({sourceExpr:r}),s&&this.has({parameters:s})}execute(e){var r;if(e.modelEntry(this.name))this.logError("source-definition-name-conflict",`Cannot redefine '${this.name}'`);else{const i=(r=this.sourceExpr)===null||r===void 0?void 0:r.getSource();if(i===void 0)return;const s=this.deduplicatedParameters(),o=i.withParameters(void 0,this.parameters);if(this.validateParameterShadowing(s,o),jnt.ErrorFactory.didCreate(o))return;const u={...o,as:this.name,location:this.location};this.note&&(u.annotation=o.annotation?{...this.note,inherits:o.annotation}:this.note),e.setEntry(this.name,{entry:u,exported:this.exported})}}deduplicatedParameters(){if(this.parameters===void 0)return[];const e={},r=[];for(const i of this.parameters)i.name in e&&i.logError("parameter-name-conflict",`Cannot redefine parameter \`${i.name}\``),e[i.name]=!0,r.push(i);return r}validateParameterShadowing(e,r){for(const i of e)r.fields.find(s=>{var o;return((o=s.as)!==null&&o!==void 0?o:s.name)===i.name})&&i.logError("parameter-shadowing-field",`Illegal shadowing of field \`${i.name}\` by parameter with the same name`)}}D2.DefineSource=Hnt;class Qnt extends Vle.DocStatementList{constructor(e){super(e),this.elementType="defineSources"}}D2.DefineSourceList=Qnt;var O2={};Object.defineProperty(O2,"__esModule",{value:!0}),O2.DefineQueryList=O2.DefineQuery=void 0;const Yle=Ze,znt=zr;class Wnt extends Yle.MalloyElement{constructor(e,r){super({queryExpr:r}),this.name=e,this.queryExpr=r,this.elementType="defineQuery",this.isNoteableObj=!0,this.extendNote=znt.extendNoteMethod}execute(e){if(e.getEntry(this.name)){this.logError("query-definition-name-conflict",`'${this.name}' is already defined, cannot redefine`);return}const i=this.queryExpr.getQuery();if(!i){this.queryExpr.sqLog("query-definition-from-non-query","Cannot define a query from this expression");return}const s={...i.query(),type:"query",name:this.name,location:this.location};this.note&&(s.annotation=s.annotation?{...this.note,inherits:s.annotation}:this.note),e.setEntry(this.name,{entry:s,exported:!0})}}O2.DefineQuery=Wnt;class Gnt extends Yle.DocStatementList{constructor(e){super(e),this.elementType="defineQueries"}}O2.DefineQueryList=Gnt;var Ro={};Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.Source=void 0;const Vnt=Ze;class Ynt extends Vnt.MalloyElement{structRef(e){return{structRef:this.getSourceDef(e)}}packParameters(e){if(e===void 0)return;const r={};for(const i of e){const s=i.parameter();r[s.name]=s}return r}withParameters(e,r){return{...this.getSourceDef(e),parameters:this.packParameters(r)}}}Ro.Source=Ynt;var uE={},w2={},G4={},Kc={};Object.defineProperty(Kc,"__esModule",{value:!0}),Kc.mergeFields=Kc.nameFromDef=void 0;function MB(t){var e;return t.type==="fieldref"?t.path[t.path.length-1]:(e=t.as)!==null&&e!==void 0?e:t.name}Kc.nameFromDef=MB;function Knt(t,e){if(t===void 0)return e;const r=new Set(e.map(s=>MB(s))),i=t.filter(s=>!r.has(MB(s)));return i.push(...e),i}Kc.mergeFields=Knt;var aE={},Gr={},qa={},Jnt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xnt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Znt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jnt(e,t,r);return Xnt(e,t),e};Object.defineProperty(qa,"__esModule",{value:!0}),qa.DefinedParameter=qa.AbstractParameter=qa.SpaceParam=void 0;const ert=Yc,Kle=Znt(nn),Jle=dt;class PB extends ert.SpaceEntry{constructor(){super(...arguments),this.refType="parameter"}}qa.SpaceParam=PB;class trt extends PB{constructor(e){super(),this.astParam=e,this._parameter=void 0}parameter(){return this._parameter!==void 0?this._parameter:(this._parameter=this.astParam.parameter(),this._parameter)}typeDesc(){return{...Kle.atomicDef(this.parameter()),expressionType:"scalar",evalSpace:"constant",compositeFieldUsage:(0,Jle.emptyCompositeFieldUsage)()}}entryType(){return this.parameter().type}}qa.AbstractParameter=trt;class nrt extends PB{constructor(e){super(),this.paramDef=e}parameter(){return this.paramDef}typeDesc(){return{...Kle.atomicDef(this.paramDef),expressionType:"scalar",evalSpace:"input",compositeFieldUsage:(0,Jle.emptyCompositeFieldUsage)()}}entryType(){return this.paramDef.type}}qa.DefinedParameter=nrt;var bd={},rrt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),irt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),srt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rrt(e,t,r);return irt(e,t),e};Object.defineProperty(bd,"__esModule",{value:!0}),bd.StructSpaceFieldBase=void 0;const Xle=dt,ort=et,urt=srt(nn),art=Wr;class lrt extends art.SpaceField{constructor(e){super(),this.structDef=e}fieldDef(){return this.structDef}get joinPathElement(){return{name:this.structDef.as||this.structDef.name,joinType:this.structDef.join,joinElementType:this.structDef.type}}typeDesc(){var e,r;return(0,ort.isSourceDef)(this.structDef)?{type:this.structDef.type,evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(e=this.structDef.onCompositeFieldUsage)!==null&&e!==void 0?e:(0,Xle.emptyCompositeFieldUsage)()}:{...urt.atomicDef(this.structDef),evalSpace:"input",expressionType:"scalar",compositeFieldUsage:(r=this.structDef.onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Xle.emptyCompositeFieldUsage)()}}}bd.StructSpaceFieldBase=lrt;var lE={};Object.defineProperty(lE,"__esModule",{value:!0}),lE.ColumnSpaceField=void 0;const crt=Wr;class frt extends crt.SpaceField{constructor(e){super(),this.sourceFieldDef=e}fieldDef(){return this.sourceFieldDef}typeDesc(){return this.fieldTypeFromFieldDef(this.sourceFieldDef)}constructorFieldDef(){return this.sourceFieldDef}}lE.ColumnSpaceField=frt;var V4={};Object.defineProperty(V4,"__esModule",{value:!0}),V4.IRViewField=void 0;const xrt=R2;class drt extends xrt.ViewField{constructor(e,r){super(e),this.turtleDef=r}rename(e){this.turtleDef={...this.turtleDef,as:e}}fieldDef(){return this.turtleDef}constructorFieldDef(){return this.turtleDef}getQueryFieldDef(e){return this.fieldDef()}}V4.IRViewField=drt,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.StaticSourceSpace=Gr.StructSpaceField=Gr.StaticSpace=void 0;const hrt=Ma,F2=et,prt=qa,mrt=Wr,cE=bd,grt=lE,yrt=V4;class UB{constructor(e,r){this.type="fieldSpace",this.fromStruct=e,this.structDialect=r}dialectName(){return this.structDialect}dialectObj(){try{return(0,hrt.getDialect)(this.structDialect)}catch{return}}defToSpaceField(e){return(0,F2.isJoined)(e)?new jB(e,this.structDialect):(0,F2.isTurtle)(e)?new yrt.IRViewField(this,e):new grt.ColumnSpaceField(e)}get map(){if(this.memoMap===void 0){this.memoMap={};for(const e of this.fromStruct.fields){const r=e.as||e.name;this.memoMap[r]=this.defToSpaceField(e)}if((0,F2.isSourceDef)(this.fromStruct)&&this.fromStruct.parameters)for(const[e,r]of Object.entries(this.fromStruct.parameters))e in this.memoMap||(this.memoMap[e]=new prt.DefinedParameter(r))}return this.memoMap}isProtectedAccessSpace(){return!1}dropEntries(){this.memoMap={}}dropEntry(e){delete this.map[e]}entry(e){return this.map[e]}setEntry(e,r){this.map[e]=r}entries(){return Object.entries(this.map)}structDef(){return this.fromStruct}emptyStructDef(){const e={...this.fromStruct};return(0,F2.isSourceDef)(e)&&(e.parameters={}),e.fields=[],e}lookup(e){const r=e[0],i=e.slice(1);let s=this.entry(r.refString);if(!s)return{error:{message:`'${r}' is not defined`,code:"field-not-found"},found:s};if(s instanceof mrt.SpaceField){const u=s.fieldDef();if(u&&(!(s instanceof cE.StructSpaceFieldBase)&&(0,F2.isJoined)(u)&&(s=new jB(u,this.structDialect)),r.addReference({type:s instanceof cE.StructSpaceFieldBase?"joinReference":"fieldReference",definition:u,location:r.location,text:r.refString})),u!=null&&u.accessModifier&&!(this.isProtectedAccessSpace()&&u.accessModifier==="internal"&&e.length===1))return{error:{message:`'${r}' is ${u==null?void 0:u.accessModifier}`,code:"field-not-accessible"},found:void 0}}const o=s instanceof cE.StructSpaceFieldBase?[{...s.joinPathElement,name:r.refString}]:[];if(i.length){if(s instanceof cE.StructSpaceFieldBase){const u=s.fieldSpace.lookup(i);return u.found?{...u,joinPath:[...o,...u.joinPath]}:u}return{error:{message:`'${r}' cannot contain a '${i[0]}'`,code:"invalid-property-access-in-field-reference"},found:void 0}}return{found:s,error:void 0,joinPath:o,isOutputField:!1}}isQueryFieldSpace(){return!1}}Gr.StaticSpace=UB;class jB extends cE.StructSpaceFieldBase{constructor(e,r){super(e),this.forDialect=r}get fieldSpace(){return(0,F2.isSourceDef)(this.structDef)?new Zle(this.structDef):new UB(this.structDef,this.forDialect)}}Gr.StructSpaceField=jB;class Zle extends UB{constructor(e){super(e,e.dialect),this.source=e}structDef(){return this.source}emptyStructDef(){const e={...this.source};return e.parameters={},e.fields=[],e}}Gr.StaticSourceSpace=Zle,Object.defineProperty(aE,"__esModule",{value:!0}),aE.JoinSpaceField=void 0;const Ert=Gr;class Art extends Ert.StructSpaceField{constructor(e,r,i){super(r.structDef(e),i),this.parameterSpace=e,this.join=r}}aE.JoinSpaceField=Art;var N2={};Object.defineProperty(N2,"__esModule",{value:!0}),N2.ParameterSpace=void 0;const _rt=qa;class vrt{constructor(e){this.type="fieldSpace",this._map={};for(const r of e)this._map[r.name]=new _rt.AbstractParameter(r)}structDef(){throw new Error("Parameter space does not have a structDef")}emptyStructDef(){throw new Error("Parameter space does not have an emptyStructDef")}entry(e){return this._map[e]}lookup(e){const r=e[0];if(r===void 0)return{error:{message:"Invalid reference",code:"invalid-parameter-reference"},found:void 0};const i=this.entry(r.refString);return i===void 0?{error:{message:`\`${r}\` is not defined`,code:"parameter-not-found"},found:void 0}:e.length>1?{error:{message:`\`${r}\` cannot contain a \`${e.slice(1).join(".")}\``,code:"invalid-parameter-reference"},found:void 0}:{found:i,error:void 0,joinPath:[],isOutputField:!1}}entries(){return Object.entries(this._map)}dialectName(){return"~parameter-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}N2.ParameterSpace=vrt;var Crt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Srt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),brt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Crt(e,t,r);return Srt(e,t),e};Object.defineProperty(G4,"__esModule",{value:!0}),G4.DynamicSpace=void 0;const Trt=brt(et),Rrt=Kc,Drt=yi,Ort=Wr,wrt=aE,Frt=R2,e0e=qa,Nrt=Gr,Lrt=bd,Irt=N2;class $rt extends Nrt.StaticSpace{constructor(e){super(structuredClone(e),e.dialect),this.complete=!1,this.parameters=[],this.newAccessModifiers=new Map,this.newNotes=new Map,this.fromSource=e,this.sourceDef=void 0}setEntry(e,r){if(this.complete)throw new Error("Space already final");super.setEntry(e,r)}addParameters(e){for(const r of e)this.entry(r.name)===void 0&&(this.parameters.push(r),this.setEntry(r.name,new e0e.AbstractParameter(r)));return this}parameterSpace(){return new Irt.ParameterSpace(this.parameters)}newEntry(e,r,i){if(this.entry(e)){r.logError("definition-name-conflict",`Cannot redefine '${e}'`);return}this.setEntry(e,i)}renameEntry(e,r,i){this.dropEntry(e),this.setEntry(r,i)}addFieldDef(e){this.setEntry((0,Rrt.nameFromDef)(e),this.defToSpaceField(e))}setTimezone(e){this.newTimezone=e}structDef(){if(this.complete=!0,this.sourceDef===void 0){const e={};for(const[l,c]of this.entries())c instanceof e0e.SpaceParam&&(e[l]=c.parameter());this.sourceDef={...this.fromSource,fields:[]},this.sourceDef.parameters=e;const r=new Map,i=[],s=[],o=[];for(const[l,c]of this.entries())c instanceof Lrt.StructSpaceFieldBase?s.push([l,c]):c instanceof Frt.ViewField?o.push([l,c]):c instanceof Ort.SpaceField&&i.push([l,c]);const u=[...i,...s,...o],a=this.parameterSpace();for(const[l,c]of u)if(c instanceof wrt.JoinSpaceField){const f=c.join.structDef(a);Drt.ErrorFactory.didCreate(f)||(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f),c.join.fixupJoinOn(this,f))}else{const f=c.fieldDef();f&&(r.set(l,this.sourceDef.fields.length),this.sourceDef.fields.push(f))}for(const[l,c]of this.newAccessModifiers){const f=this.sourceDef.fields.findIndex(x=>{var h;return(h=x.as)!==null&&h!==void 0?h:x.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);c==="public"?delete this.sourceDef.fields[f].accessModifier:this.sourceDef.fields[f]={...this.sourceDef.fields[f],accessModifier:c}}for(const[l,c]of this.newNotes){const f=this.sourceDef.fields.findIndex(h=>{var p;return(p=h.as)!==null&&p!==void 0?p:h.name===l});if(f===-1)throw new Error(`Can't find field '${l}' to set access modifier`);const x=this.sourceDef.fields[f];this.sourceDef.fields[f]={...x,annotation:{...c,inherits:x.annotation}}}}return this.newTimezone&&Trt.isSourceDef(this.sourceDef)&&(this.sourceDef.queryTimezone=this.newTimezone),this.sourceDef}emptyStructDef(){const e={...this.fromSource};return e.fields=[],e}}G4.DynamicSpace=$rt;var fE={};Object.defineProperty(fE,"__esModule",{value:!0}),fE.RenameSpaceField=void 0;const Brt=Wr;class krt extends Brt.SpaceField{constructor(e,r,i){super(),this.otherField=e,this.newName=r,this.location=i}fieldDef(){const e=this.otherField.fieldDef();if(e!==void 0)return{...e,as:this.newName,location:this.location}}typeDesc(){return this.otherField.typeDesc()}}fE.RenameSpaceField=krt,Object.defineProperty(w2,"__esModule",{value:!0}),w2.RefinedSpace=void 0;const Mrt=G4,Prt=Yc,Urt=fE,jrt=Wr;class qB extends Mrt.DynamicSpace{static filteredFrom(e,r,i,s,o){const u=new qB(e),a=new Map;for(const l of s??[])a.has(l.name.refString)?l.name.logError("already-renamed",`${l.name.refString} already renamed to ${l.as}`):a.set(l.name.refString,{as:l.as,location:l.location,logTo:l.name});if(i!==void 0){const l=u.entries();u.dropEntries();for(const[c,f]of l)if(i.has(c)){const x=a.get(c);x?f instanceof jrt.SpaceField?u.setEntry(x.as,new Urt.RenameSpaceField(f,x.as,x.location)):x.logTo.logError("cannot-rename-non-field",`Cannot rename \`${c}\` which is not a field`):u.setEntry(c,f)}r!==void 0&&r.logError("accept-except-not-compatible-with-include","Can't use `accept:` or `except:` with `include`")}else if(r){const l=r.refs.list,c=u.entries();for(const f of l)c.find(([h])=>h===f.refString)===void 0&&(o!=null&&o.entry(f.refString)?f.logError(`${r.edit}-parameter`,`Illegal \`${r.edit}:\` of parameter`):f.logError("field-list-edit-not-found",`\`${f.refString}\` is not defined`));u.dropEntries();for(const[f,x]of c){const h=!!l.find(m=>m.refString===f),p=r.edit==="accept";h===p&&u.setEntry(f,x)}}return u}pushFields(...e){for(const r of e)this.addField(r)}addField(e){(0,Prt.canMakeEntry)(e)?e.makeEntry(this):e.logError("unexpected-element-type",`Internal error, ${e.elementType} not expected in this context`)}addAccessModifiers(e){for(const[r,i]of e)this.newAccessModifiers.set(r,i)}addNotes(e){for(const[r,i]of e)this.newNotes.set(r,i)}isProtectedAccessSpace(){return!0}}w2.RefinedSpace=qB;var Jc={},Ws={};Object.defineProperty(Ws,"__esModule",{value:!0}),Ws.DefinitionList=void 0;const qrt=Ze,t0e=zr;class Hrt extends qrt.ListOf{constructor(){super(...arguments),this.isNoteableObj=!0}extendNote(e){(0,t0e.extendNoteHelper)(this,e),this.distributeAnnotation()}distributeAnnotation(){if(this.note)for(const e of this.elements)(0,t0e.isNoteable)(e)&&e.extendNote(this.note)}newContents(){super.newContents(),this.distributeAnnotation()}}Ws.DefinitionList=Hrt,Object.defineProperty(Jc,"__esModule",{value:!0}),Jc.DeclareFields=void 0;const Qrt=Ws,zrt=Wn;class Wrt extends Qrt.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="declareFields",this.queryRefinementStage=zrt.LegalRefinementStage.Single,this.forceQueryClass=void 0}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r)}get delarationNames(){return this.list.map(e=>e.defineName)}}Jc.DeclareFields=Wrt;var Ha={};Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.Filter=Ha.FilterElement=void 0;const n0e=et,Grt=Jn,r0e=Ze,HB=Wn;class Vrt extends r0e.MalloyElement{constructor(e,r){super({expr:e}),this.expr=e,this.exprSrc=r,this.elementType="filterElement"}filterCondition(e){const r=this.expr.getExpression(e);return r.type!=="boolean"?(this.expr.logError("non-boolean-filter","Filter expression must have boolean value"),{node:"filterCondition",code:this.exprSrc,e:{node:"false"},expressionType:"scalar",compositeFieldUsage:r.compositeFieldUsage}):{node:"filterCondition",code:this.exprSrc,e:r.value,expressionType:r.expressionType,compositeFieldUsage:r.compositeFieldUsage}}}Ha.FilterElement=Vrt;class Yrt extends r0e.ListOf{constructor(){super(...arguments),this.elementType="filter",this.forceQueryClass=void 0,this.queryRefinementStage=HB.LegalRefinementStage.Head}set having(e){this.elementType=e?"having":"where",this.havingClause=e,this.queryRefinementStage=e?HB.LegalRefinementStage.Tail:HB.LegalRefinementStage.Head}checkedFilterCondition(e,r){const i=r.filterCondition(e);if(this.havingClause!==void 0){const s=(0,n0e.expressionIsAggregate)(i.expressionType),o=(0,n0e.expressionIsAnalytic)(i.expressionType);if(this.havingClause){if(o){r.logError("analytic-in-having","Analytic expressions are not allowed in `having:`");return}}else if(o){r.logError("analytic-in-where","Analytic expressions are not allowed in `where:`");return}else s&&r.logError("aggregate-in-where","Aggregate expressions are not allowed in `where:`; use `having:`")}return i}getFilterList(e){return this.list.map(r=>this.checkedFilterCondition(e,r)).filter(Grt.isNotUndefined)}queryExecute(e){const r=this.havingClause?e.resultFS:e.inputFS;for(const i of this.list){const s=this.checkedFilterCondition(r,i);s!==void 0&&(e.filters.push(s),e.resultFS.addCompositeFieldUserFromFilter(s,i))}}}Ha.Filter=Yrt;var L2={};Object.defineProperty(L2,"__esModule",{value:!0}),L2.FieldListEdit=void 0;const Krt=Ze;class Jrt extends Krt.MalloyElement{constructor(e,r){super({refs:r}),this.edit=e,this.refs=r,this.elementType="fieldListEdit"}}L2.FieldListEdit=Jrt;var I2={};Object.defineProperty(I2,"__esModule",{value:!0}),I2.PrimaryKey=void 0;const Xrt=Ze;class Zrt extends Xrt.MalloyElement{constructor(e){super({field:e}),this.field=e,this.elementType="primary key"}}I2.PrimaryKey=Zrt;var $2={};Object.defineProperty($2,"__esModule",{value:!0}),$2.Views=void 0;const eit=Ws;class tit extends eit.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="turtleDefList"}get delarationNames(){return this.list.map(e=>e.name)}}$2.Views=tit;var B2={};Object.defineProperty(B2,"__esModule",{value:!0}),B2.TimezoneStatement=void 0;const nit=Ze,rit=qr;class iit extends nit.MalloyElement{constructor(e){super(),this.tz=e,this.elementType="timezone",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}get isValid(){try{return rit.DateTime.fromISO("2020-02-19T00:00:00",{zone:this.tz}),!0}catch{return!1}}queryExecute(e){e.resultFS.setTimezone(this.tz)}}B2.TimezoneStatement=iit;var Xc={};Object.defineProperty(Xc,"__esModule",{value:!0}),Xc.ModelAnnotation=Xc.ObjectAnnotation=void 0;const sit=Ze,oit=gi;class i0e extends sit.MalloyElement{constructor(e){super(),this.notes=e,this.elementType="annotation",this.forceQueryClass=void 0,this.queryRefinementStage=void 0}queryExecute(){}}Xc.ObjectAnnotation=i0e;class uit extends i0e{constructor(){super(...arguments),this.elementType="modelAnnotation"}getCompilerFlags(e,r){const i=(0,oit.annotationToTag)({notes:this.notes},{prefix:/^##! /,extending:e});return i.log.forEach(s=>r.log(s)),i.tag}execute(e){e.annotation.notes===void 0&&(e.annotation.notes=[]),e.annotation.notes.push(...this.notes)}}Xc.ModelAnnotation=uit;var Zc={};Object.defineProperty(Zc,"__esModule",{value:!0}),Zc.Renames=Zc.RenameField=void 0;const ait=fE,s0e=Ze,lit=Wr;class cit extends s0e.MalloyElement{constructor(e,r){super(),this.newName=e,this.oldName=r,this.elementType="renameField",this.has({oldName:r})}makeEntry(e){if(this.oldName.refString===this.newName){this.logError("invalid-rename-with-same-name","Can't rename field to itself");return}const r=this.oldName.getField(e);r.found?r.found instanceof lit.SpaceField?e.renameEntry(this.oldName.refString,this.newName,new ait.RenameSpaceField(r.found,this.newName,this.location)):this.logError("failed-rename",`'${this.oldName}' cannot be renamed`):this.logError("rename-field-not-found",`Can't rename '${this.oldName}', no such field`)}getName(){return this.newName}}Zc.RenameField=cit;class fit extends s0e.ListOf{constructor(e,r){super(e),this.accessModifier=r,this.elementType="renameFields"}get delarationNames(){return this.list.map(e=>e.getName())}}Zc.Renames=fit;var As={};Object.defineProperty(As,"__esModule",{value:!0}),As.JoinStatement=As.ExpressionJoin=As.KeyJoin=As.Join=void 0;const QB=et,xit=aE,dit=Ws,hit=Ze,pit=zr,o0e=yi,mit=Wn;class zB extends hit.MalloyElement{constructor(){super(...arguments),this.isNoteableObj=!0,this.extendNote=pit.extendNoteMethod}makeEntry(e){e.newEntry(this.name.refString,this,new xit.JoinSpaceField(e.parameterSpace(),this,e.dialectName()))}getName(){return this.name.refString}getStructDefFromExpr(e){const r=this.sourceExpr.getSource();return r?r.getSourceDef(e):(this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),o0e.ErrorFactory.structDef)}}As.Join=zB;class git extends zB{constructor(e,r,i){super({name:e,sourceExpr:r,keyExpr:i}),this.name=e,this.sourceExpr=r,this.keyExpr=i,this.elementType="joinOnKey"}structDef(e){var r;const i=this.getStructDefFromExpr(e);if(!(0,QB.isJoinable)(i))throw this.internalError(`Cannot join struct type '${i.type}'`);const s={...i,name:this.name.refString,join:"one",matrixOperation:"left",onExpression:{node:"error",message:"('join fixup'='not done yet')"},location:this.location};return delete s.as,this.note&&(s.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(s),s}fixupJoinOn(e,r){const i=this.keyExpr.getExpression(e);if((0,QB.isSourceDef)(r)&&r.primaryKey){const s=r.fields.find(o=>(o.as||o.name)===r.primaryKey);if(s)if(s.type===i.type){r.join="one",r.onExpression={node:"=",kids:{left:{node:"field",path:[this.name.refString,r.primaryKey]},right:i.value}},r.onCompositeFieldUsage=i.compositeFieldUsage;return}else this.logError("join-on-primary-key-type-mismatch",`join_one: with type mismatch with primary key: ${i.type}/${s.type}`);else this.logError("join-primary-key-not-found",`join_one: Primary key '${s}' not found in source`)}else this.logError("join-with-without-primary-key","join_one: Cannot use with unless source has a primary key")}}As.KeyJoin=git;class yit extends zB{constructor(e,r){super({name:e,sourceExpr:r}),this.name=e,this.sourceExpr=r,this.elementType="joinOnExpr",this.joinType="one",this.matrixOperation="left"}set joinOn(e){this.expr=e,this.has({on:e})}get joinOn(){return this.expr}fixupJoinOn(e,r){if(this.expr===void 0)return;const i=this.expr.getExpression(e);if(i.type!=="boolean"){this.logError("non-boolean-join-on","join conditions must be boolean expressions");return}r.onExpression=i.value,r.onCompositeFieldUsage=i.compositeFieldUsage}structDef(e){var r;const i=this.sourceExpr.getSource();if(!i)return this.sourceExpr.sqLog("invalid-join-source","Cannot create a source to join from"),o0e.ErrorFactory.joinDef;const s=i.getSourceDef(e);let o="left";if(this.inExperiment("join_types",!0)&&(o=this.matrixOperation),!(0,QB.isJoinable)(s))throw this.internalError(`Can't join struct type ${s.type}`);const u={...s,name:this.name.refString,join:this.joinType,matrixOperation:o,location:this.location};return delete u.as,this.note&&(u.annotation=this.note),(r=this.document())===null||r===void 0||r.rememberToAddModelAnnotations(u),u}}As.ExpressionJoin=yit;class Eit extends dit.DefinitionList{constructor(e,r){super(e),this.accessModifier=r,this.elementType="joinStatement",this.forceQueryClass=void 0,this.queryRefinementStage=mit.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)e.inputFS.extendSource(r),e.alwaysJoins.push(r.name.refString)}get delarationNames(){return this.list.map(e=>e.name.refString)}}As.JoinStatement=Eit;var bu={};Object.defineProperty(bu,"__esModule",{value:!0}),bu.IncludeListItem=bu.IncludeExceptItem=bu.IncludeAccessItem=bu.IncludeItem=void 0;const u0e=Ze,a0e=zr;class WB extends u0e.MalloyElement{}bu.IncludeItem=WB;class Ait extends WB{constructor(e,r){super(),this.kind=e,this.fields=r,this.elementType="include-access-item",this.isNoteableObj=!0,this.extendNote=a0e.extendNoteMethod,this.has({fields:r})}}bu.IncludeAccessItem=Ait;class _it extends WB{constructor(e){super(),this.fields=e,this.elementType="include-except-item",this.kind="except",this.has({fields:e})}}bu.IncludeExceptItem=_it;class vit extends u0e.MalloyElement{constructor(e,r){super({name:e}),this.name=e,this.as=r,this.elementType="include-list-item",this.isNoteableObj=!0,this.extendNote=a0e.extendNoteMethod}}bu.IncludeListItem=vit;var _t={},xE={},Cit=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Sit=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),bit=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Cit(e,t,r);return Sit(e,t),e};Object.defineProperty(xE,"__esModule",{value:!0}),xE.ReferenceField=void 0;const l0e=et,c0e=bit(nn),f0e=Wr,Tit=dt;class Rit extends f0e.SpaceField{constructor(e,r){super(),this.fieldRef=e,this.inFS=r,this.didLookup=!1}get referenceTo(){return this.didLookup||(this.memoReference=this.inFS.lookup(this.fieldRef.list).found,this.didLookup=!0),this.memoReference}getQueryFieldDef(e){if(!this.queryFieldDef){const r=this.fieldRef.getField(e);r.error&&this.fieldRef.logError(r.error.code,r.error.message);const i=this.fieldRef.path;if(r.found&&r.found.refType==="parameter"){const o=r.found.typeDesc();if(l0e.TD.isAtomic(o))this.queryFieldDef={...(0,l0e.mkFieldDef)(c0e.atomicDef(o),i[0]),e:{node:"parameter",path:i}};else throw new Error("impossible turtle/join parameter")}else this.queryFieldDef={type:"fieldref",path:i};const s=this.referenceTo;if(s instanceof f0e.SpaceField){const o=s.constructorFieldDef();if(o){const u=this.fieldRef.note;if(o.annotation||u){const a=u||{};o.annotation&&(a.inherits=o.annotation),this.queryFieldDef.annotation=a}}}}return this.queryFieldDef}typeDesc(){if(this.memoTypeDesc)return this.memoTypeDesc;const e=this.referenceTo;if(e){const r=this.fieldRef.list.slice(0,-1).map(s=>s.refString),i=e.typeDesc();return this.memoTypeDesc={...i,compositeFieldUsage:(0,Tit.joinedCompositeFieldUsage)(r,i.compositeFieldUsage)},this.memoTypeDesc}return c0e.errorT}}xE.ReferenceField=Rit;var lr={};Object.defineProperty(lr,"__esModule",{value:!0}),lr.typecheckGroupBy=lr.typecheckAggregate=lr.typecheckCalculate=lr.typecheckDeclare=lr.typecheckMeasure=lr.typecheckDimension=lr.typecheckIndex=lr.typecheckProject=void 0;const Pn=Yi;function Dit(t,e){if(t.type==="turtle"||!(0,Pn.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="select-of-view";else if((0,Pn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="select-of-analytic";else if((0,Pn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="select-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a select operation, did you mean to use ${r} operation instead?`)}}lr.typecheckProject=Dit;function Oit(t,e){if(t.type==="turtle"||!(0,Pn.expressionIsScalar)(t.expressionType)){let r,i;if(t.type==="turtle")r="a view",i="index-of-view";else if((0,Pn.expressionIsAnalytic)(t.expressionType))r="an analytic",i="index-of-analytic";else if((0,Pn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="index-of-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(i,`Cannot use ${r} field in an index operation`)}}lr.typecheckIndex=Oit;function wit(t,e){if(!(0,Pn.expressionIsScalar)(t.expressionType))if((0,Pn.expressionIsAggregate)(t.expressionType))e.logError("aggregate-in-dimension","Cannot use an aggregate field in a dimension declaration, did you mean to use a measure declaration instead?");else if((0,Pn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-dimension","Cannot use an analytic field in a dimension declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}lr.typecheckDimension=wit;function Fit(t,e){if(!(0,Pn.expressionIsAggregate)(t.expressionType))if((0,Pn.expressionIsScalar)(t.expressionType))e.logError("scalar-in-measure","Cannot use a scalar field in a measure declaration, did you mean to use a dimension declaration instead?");else if((0,Pn.expressionIsAnalytic)(t.expressionType))e.logError("analytic-in-measure","Cannot use an analytic field in a measure declaration");else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`)}lr.typecheckMeasure=Fit;function Nit(t,e){t.type==="turtle"?e.logError("view-in-declare","Views cannot be used in a declare block"):(0,Pn.expressionIsAnalytic)(t.expressionType)&&e.logError("analytic-in-declare","Analytic expressions can not be used in a declare block")}lr.typecheckDeclare=Nit;function Lit(t,e){if(t.type==="turtle"||!(0,Pn.expressionIsAnalytic)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="calculate-of-view";else if((0,Pn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="calculate-of-aggregate";else if((0,Pn.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="calculate-of-scalar";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a calculate operation, did you mean to use ${r} operation instead?`)}}lr.typecheckCalculate=Lit;function Iit(t,e){if(t.type==="turtle"||!(0,Pn.expressionIsAggregate)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="aggregate-of-view";else if((0,Pn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="aggregate-of-analytic";else if((0,Pn.expressionIsScalar)(t.expressionType))r="a group_by or select",i="a scalar",s="aggregate-of-scalar";else throw new Error(`Unexpected expression type ${t} not handled here`);e.logError(s,`Cannot use ${i} field in an aggregate operation, did you mean to use ${r} operation instead?`)}}lr.typecheckAggregate=Iit;function $it(t,e){if(t.type==="turtle"||!(0,Pn.expressionIsScalar)(t.expressionType)){let r,i,s;if(t.type==="turtle")r="a nest",i="a view",s="group-by-view";else if((0,Pn.expressionIsAnalytic)(t.expressionType))r="a calculate",i="an analytic",s="group-by-analytic";else if((0,Pn.expressionIsAggregate)(t.expressionType))r="an aggregate",i="an aggregate",s="group-by-aggregate";else throw new Error(`Unexpected expression type ${t.expressionType} not handled here`);e.logError(s,`Cannot use ${i} field in a group_by operation, did you mean to use ${r} operation instead?`)}}lr.typecheckGroupBy=$it,Object.defineProperty(_t,"__esModule",{value:!0}),_t.FieldReferences=_t.WildcardFieldReference=_t.ViewOrScalarFieldReference=_t.DimensionFieldReference=_t.MeasureFieldReference=_t.DeclareFieldReference=_t.ProjectFieldReference=_t.GroupByFieldReference=_t.AggregateFieldReference=_t.IndexFieldReference=_t.CalculateFieldReference=_t.ParameterFieldReference=_t.PartitionByFieldReference=_t.ExpressionFieldReference=_t.AccessModifierFieldReference=_t.AcceptExceptFieldReference=_t.FieldReference=void 0;const Bit=xE,kit=Ws,x0e=Ze,d0e=zr,ef=lr;class Xi extends x0e.ListOf{constructor(e){super(e),this.isNoteableObj=!0,this.extendNote=d0e.extendNoteMethod}makeEntry(e){const r=this.outputName;if(e.entry(r))this.logError("output-name-conflict",`Output already has a field named '${r}'`);else{const i=e.isQueryFieldSpace()?e.inputSpace():e;e.newEntry(r,this,new Bit.ReferenceField(this,i))}}getName(){return this.nameString}get refToField(){return{type:"fieldref",path:this.list.map(e=>e.refString)}}get refString(){return this.path.join(".")}get path(){return this.list.map(e=>e.refString)}get outputName(){return this.list[this.list.length-1].refString}get sourceString(){if(this.list.length>1)return this.list.slice(0,-1).map(e=>e.refString).join(".")}get nameString(){return this.list[this.list.length-1].refString}getField(e){const r=e.lookup(this.list);if(r.found){const i=r.found.typeDesc();this.typecheck(i)}return r}}_t.FieldReference=Xi;class Mit extends Xi{constructor(){super(...arguments),this.elementType="acceptExceptFieldReference"}typecheck(){}}_t.AcceptExceptFieldReference=Mit;class Pit extends Xi{constructor(){super(...arguments),this.elementType="accessModifierFieldReference"}typecheck(){}}_t.AccessModifierFieldReference=Pit;class Uit extends Xi{constructor(){super(...arguments),this.elementType="expressionFieldReference"}typecheck(){}}_t.ExpressionFieldReference=Uit;class jit extends Xi{constructor(){super(...arguments),this.elementType="partitionByFieldReference"}typecheck(){}}_t.PartitionByFieldReference=jit;class qit extends Xi{constructor(){super(...arguments),this.elementType="parameterFieldReference"}typecheck(){}}_t.ParameterFieldReference=qit;class Hit extends Xi{constructor(){super(...arguments),this.elementType="calculateFieldReference"}typecheck(e){(0,ef.typecheckCalculate)(e,this)}}_t.CalculateFieldReference=Hit;class GB extends Xi{constructor(){super(...arguments),this.elementType="indexFieldReference"}typecheck(e){(0,ef.typecheckIndex)(e,this)}static indexOutputName(e){return e.map(r=>encodeURIComponent(r)).join("/")}get outputName(){return GB.indexOutputName(this.path)}}_t.IndexFieldReference=GB;class Qit extends Xi{constructor(){super(...arguments),this.elementType="aggregateFieldReference"}typecheck(e){(0,ef.typecheckAggregate)(e,this)}}_t.AggregateFieldReference=Qit;class zit extends Xi{constructor(){super(...arguments),this.elementType="groupByFieldReference"}typecheck(e){(0,ef.typecheckGroupBy)(e,this)}}_t.GroupByFieldReference=zit;class Wit extends Xi{constructor(){super(...arguments),this.elementType="projectFieldReference"}typecheck(e){(0,ef.typecheckProject)(e,this)}}_t.ProjectFieldReference=Wit;class Git extends Xi{constructor(){super(...arguments),this.elementType="declareFieldReference"}typecheck(e){(0,ef.typecheckDeclare)(e,this)}}_t.DeclareFieldReference=Git;class Vit extends Xi{constructor(){super(...arguments),this.elementType="measureFieldReference"}typecheck(e){(0,ef.typecheckMeasure)(e,this)}}_t.MeasureFieldReference=Vit;class Yit extends Xi{constructor(){super(...arguments),this.elementType="dimensionFieldReference"}typecheck(e){(0,ef.typecheckDimension)(e,this)}}_t.DimensionFieldReference=Yit;class Kit extends Xi{constructor(){super(...arguments),this.elementType="viewOrScalarFieldReference"}typecheck(e){}}_t.ViewOrScalarFieldReference=Kit;class Jit extends x0e.MalloyElement{constructor(e){super(),this.joinPath=e,this.elementType="wildcardFieldReference",this.isNoteableObj=!0,this.extendNote=d0e.extendNoteMethod,this.except=new Set,this.has({joinPath:e})}getFieldDef(){throw this.internalError("fielddef request from wildcard reference")}get refString(){return this.joinPath?`${this.joinPath.refString}.*`:"*"}}_t.WildcardFieldReference=Jit;class Xit extends kit.DefinitionList{constructor(e){super(e),this.elementType="fieldReferenceList"}}_t.FieldReferences=Xit,Object.defineProperty(uE,"__esModule",{value:!0}),uE.RefinedSource=void 0;const Zit=et,est=w2,tst=Jc,nst=Ha,rst=L2,ist=I2,sst=$2,ost=Ro,ust=B2,ast=Xc,lst=Zc,cst=N2,fst=As,h0e=bu,VB=_t;class xst extends ost.Source{constructor(e,r,i){super({source:e,refinement:r}),this.source=e,this.refinement=r,this.includeList=i,this.elementType="refinedSource",i&&this.has({includeList:i})}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;let s,o;const u=[],a=[];let l;const c=[];for(const v of this.refinement.list){if(v instanceof ast.ObjectAnnotation)continue;const C=v;if(v instanceof ist.PrimaryKey){if(s){const S="multiple-primary-keys";s.logError(S,"Primary key already defined"),v.logError(S,"Primary key redefined")}s=v}else if(v instanceof rst.FieldListEdit){if(o){const S="multiple-field-list-edits";o.logError(S,"Too many accept/except statements"),v.logError(S,"Too many accept/except statements")}o=v}else v instanceof tst.DeclareFields||v instanceof fst.JoinStatement||v instanceof sst.Views||v instanceof lst.Renames?(u.push(...v.list),v.accessModifier&&c.push({fields:v.delarationNames,access:v.accessModifier})):v instanceof nst.Filter?a.push(v):v instanceof ust.TimezoneStatement?l=v.tz:C.logError("unexpected-source-property",`Unexpected source property: '${C.elementType}'`)}const f=r?new cst.ParameterSpace(r):void 0,x=structuredClone(this.source.getSourceDef(f)),{fieldsToInclude:h,modifiers:p,renames:m,notes:y}=dst(this.includeList,x);for(const v of c)for(const C of v.fields)p.set(C,v.access);s&&(x.primaryKey=s.field.name);const g=est.RefinedSpace.filteredFrom(x,o,h,m,f);if(l&&g.setTimezone(l),r&&g.addParameters(r),g.pushFields(...u),s){const v=s.field.getField(g);v.error&&s.logError(v.error.code,v.error.message)}g.addAccessModifiers(p),g.addNotes(y);const E=g.structDef(),A=E.filterList||[];let _=!1;for(const v of a)for(const C of v.list){const S=C.filterCondition(g);(0,Zit.expressionIsCalculation)(S.expressionType)?C.logError("aggregate-in-source-filter","Can't use aggregate computations in top level filters"):(A.push(S),_=!0)}return _?{...E,filterList:A}:((i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(E),E)}}uE.RefinedSource=xst;function dst(t,e){var r,i,s,o,u,a,l,c,f;const x=new Set(e.fields.map(S=>S.name)),h=new Set(e.fields.filter(S=>S.accessModifier==="private").map(S=>S.name));let p;const m=new Set;let y,g;const E=new Map,A=[],_=new Map;if(t===void 0)return{fieldsToInclude:void 0,modifiers:E,renames:A,notes:_};for(const S of t)if(S instanceof h0e.IncludeAccessItem)for(const b of S.fields)if(b.name instanceof VB.WildcardFieldReference)b.name.joinPath&&b.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"),y!==void 0?S.logError("already-used-star-in-include","Wildcard already used in this include block"):(y=(r=S.kind)!==null&&r!==void 0?r:"inherit",g={notes:(s=(i=b.note)===null||i===void 0?void 0:i.notes)!==null&&s!==void 0?s:[],blockNotes:(u=(o=S.note)===null||o===void 0?void 0:o.blockNotes)!==null&&u!==void 0?u:[]});else{if(p==="exclude"){S.logError("include-after-exclude","Cannot include specific fields if specific fields are already excluded");continue}p="include";const R=b.name.refString;h.has(R)&&b.logError("cannot-expand-access",`Cannot expand access of \`${R}\` from private to ${S.kind}`),E.has(R)?b.logError("duplicate-include",`Field \`${R}\` already referenced in include list`):(S.kind!==void 0&&E.set(R,S.kind),m.add(R),(b.note||S.note)&&_.set(R,{notes:(l=(a=b.note)===null||a===void 0?void 0:a.notes)!==null&&l!==void 0?l:[],blockNotes:(f=(c=S.note)===null||c===void 0?void 0:c.blockNotes)!==null&&f!==void 0?f:[]})),b.as&&(b.name instanceof VB.WildcardFieldReference?b.logError("wildcard-include-rename","Cannot rename a wildcard field in an `include` block"):A.push({name:b.name,as:b.as,location:b.location}))}else if(S instanceof h0e.IncludeExceptItem)for(const b of S.fields)b instanceof VB.WildcardFieldReference?b.joinPath?b.logError("unsupported-path-in-include","Wildcards with paths are not supported in `include` blocks"):b.logWarning("wildcard-except-redundant","`except: *` is implied, unless another clause uses *"):p==="include"?S.logError("exclude-after-include","Cannot exclude specific fields if specific fields are already included"):(p="exclude",y="inherit",m.add(b.refString));const v=new Set(x);m.forEach(S=>v.delete(S)),h.forEach(S=>v.delete(S));let C;if(y!==void 0)for(const S of v)y!=="inherit"&&E.set(S,y),g&&_.set(S,{...g});return p!=="exclude"?y!==void 0?C=x:C=m:C=v,{fieldsToInclude:C,modifiers:E,renames:A,notes:_}}var Tu={};Object.defineProperty(Tu,"__esModule",{value:!0}),Tu.SourceQueryElement=void 0;const hst=Ze;class YB extends hst.MalloyElement{constructor(){super(...arguments),this.errored=!1}getSource(){}getQuery(){}isSource(){return!1}sqLog(e,r,i){return this.isErrorFree()&&this.logError(e,r,i),this.errored=!0,e}isErrorFree(){if(this.errored)return!1;let e=!0;for(const r of this.walk())if(r instanceof YB&&r.errored){e=!1;break}return e}}Tu.SourceQueryElement=YB;var Y4={},Td={};Object.defineProperty(Td,"__esModule",{value:!0}),Td.QuerySource=void 0;const pst=Ro,mst=g2;class gst extends pst.Source{constructor(e){super({query:e}),this.query=e,this.elementType="querySource"}getSourceDef(e){return this.withParameters(e,void 0)}withParameters(e,r){var i;const s=this.query.queryComp(!1),o={...s.outputStruct,name:`QuerySource-${(0,mst.v4)()}`,type:"query_source",query:s.query};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(o),{...o,parameters:this.packParameters(r)}}}Td.QuerySource=gst;var k2={},dE={};Object.defineProperty(dE,"__esModule",{value:!0}),dE.QueryBase=void 0;const KB=dt,p0e=et,yst=S2,Est=Ze;class Ast extends Est.MalloyElement{resolveCompositeSource(e,r){var i;const s=r.pipeline[0];if(s&&((0,p0e.isQuerySegment)(s)||(0,p0e.isIndexSegment)(s))){const o=(i=s.compositeFieldUsage)!==null&&i!==void 0?i:(0,KB.emptyCompositeFieldUsage)();if(!(0,KB.isEmptyCompositeFieldUsage)(o)||e.type==="composite")return(0,KB.resolveCompositeSources)(e,o).sourceDef}}query(){const{query:e}=this.queryComp(!0);return{...e,pipeline:(0,yst.detectAndRemovePartialStages)(e.pipeline,this)}}}dE.QueryBase=Ast,Object.defineProperty(k2,"__esModule",{value:!0}),k2.QueryArrow=void 0;const _st=et,vst=Ro,m0e=Gr,Cst=dE;class Sst extends Cst.QueryBase{constructor(e,r){super({source:e,view:r}),this.source=e,this.view=r,this.elementType="arrow"}queryComp(e){var r;let i,s,o;if(this.source instanceof vst.Source){const h=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)};s={type:"query",...h,pipeline:[],location:this.location},i=(0,_st.refIsStructDef)(h.structRef)?h.structRef:this.source.getSourceDef(void 0),o=new m0e.StaticSourceSpace(i)}else{const h=this.source.queryComp(e);s=h.query,i=h.outputStruct,o=new m0e.StaticSourceSpace(h.outputStruct)}const{pipeline:u,annotation:a,outputStruct:l,name:c}=this.view.pipelineComp(o),f={...s,name:c,annotation:a,pipeline:[...s.pipeline,...u]},x=(r=f.compositeResolvedSourceDef)!==null&&r!==void 0?r:this.resolveCompositeSource(i,f);return{query:{...f,compositeResolvedSourceDef:x},outputStruct:l,inputStruct:i}}}k2.QueryArrow=Sst,Object.defineProperty(Y4,"__esModule",{value:!0}),Y4.SQArrow=void 0;const bst=Tu,Tst=Td,Rst=k2;class Dst extends bst.SourceQueryElement{constructor(e,r){super({applyTo:e,operation:r}),this.applyTo=e,this.operation=r,this.elementType="sq-arrow"}getQuery(){const e=this.applyTo.isSource()?this.applyTo.getSource():this.applyTo.getQuery();if(e===void 0){this.sqLog("failed-to-compute-arrow-source","Could not get LHS of arrow operation");return}const r=new Rst.QueryArrow(e,this.operation);return this.has({query:r}),r}getSource(){const e=this.getQuery();if(!e){this.sqLog("failed-to-compute-source-from-query","Couldn't comprehend query well enough to make a source");return}const r=new Tst.QuerySource(e);return this.has({asSource:r}),r}}Y4.SQArrow=Dst;var K4={},M2={},Gs={};Object.defineProperty(Gs,"__esModule",{value:!0}),Gs.getStructFieldDef=Gs.getFinalStruct=Gs.opOutputStruct=void 0;const g0e=O0,Ost=Hs,J4=et,y0e=yi;function E0e(t,e,r){const i=y0e.ErrorFactory.didCreate(e)||(0,J4.structHasErrors)(e);(0,J4.isPartialSegment)(r)&&(r={...r,type:"reduce"});const s=(0,J4.segmentHasErrors)(r);if(!i&&!s)try{const o=Ost.Segment.nextStructDef(e,r);if((0,J4.isSourceDef)(o))return o;t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: RETURNED A NON SOURCE
1553
1553
  STRUCTDEF: ${(0,g0e.inspect)(o,{breakLength:72,depth:1/0})}`)}catch(o){t.logError("failed-to-compute-output-schema",`INTERNAL ERROR model/Segment.nextStructDef: ${o.message}
1554
1554
  QUERY: ${(0,g0e.inspect)(r,{breakLength:72,depth:1/0})}`)}return y0e.ErrorFactory.structDef}Gs.opOutputStruct=E0e;function wst(t,e,r){for(const i of r)e=E0e(t,e,i);return e}Gs.getFinalStruct=wst;function Fst(t,e){return t.fields.find(r=>(r.as||r.name)===e)}Gs.getStructFieldDef=Fst,Object.defineProperty(M2,"__esModule",{value:!0}),M2.QueryRefine=void 0;const Nst=Gr,Lst=Gs,Ist=dE;class $st extends Ist.QueryBase{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="query-refine"}queryComp(e){const r=this.base.queryComp(e),i=new Nst.StaticSourceSpace(r.inputStruct),s=this.refinement.refine(i,r.query.pipeline,void 0),o={...r.query,pipeline:s},u=this.resolveCompositeSource(r.inputStruct,o);return{query:{...o,compositeResolvedSourceDef:u},outputStruct:(0,Lst.getFinalStruct)(this.refinement,r.inputStruct,s),inputStruct:r.inputStruct}}}M2.QueryRefine=$st;var hE={},P2={},_s={};Object.defineProperty(_s,"__esModule",{value:!0}),_s.mkTimeResult=_s.resolution=_s.castTo=_s.timeOffset=void 0;const JB=et;function Bst(t,e,r,i,s){return{node:"delta",kids:{base:(0,JB.mkTemporal)(e,t),delta:i},op:r,units:s}}_s.timeOffset=Bst;function kst(t,e,r,i=!1){let s;return typeof t!="string"?s={node:"cast",dstSQLType:t.raw,e,safe:i}:s={node:"cast",dstType:{type:t},e,safe:i},(0,JB.isCastType)(r)&&(s.srcType={type:r}),s}_s.castTo=kst;function Mst(t){switch(t){case"hour":case"minute":case"second":case"microsecond":case"millisecond":return"timestamp"}return"date"}_s.resolution=Mst;function Pst(t,e){if(e){if(t.type==="timestamp")return{...t,timeframe:e};if((0,JB.isDateUnit)(e))return{...t,timeframe:e}}return t}_s.mkTimeResult=Pst;var Rd={},pt={},zt={};Object.defineProperty(zt,"__esModule",{value:!0}),zt.literalTimeResult=zt.literalExprValue=zt.computedErrorExprValue=zt.computedTimeResult=zt.computedExprValue=void 0;const A0e=Yi,XB=dt;function pE({value:t,dataType:e,from:r}){return{...e,value:t,expressionType:(0,A0e.maxOfExpressionTypes)(r.map(i=>i.expressionType)),evalSpace:(0,A0e.mergeEvalSpaces)(...r.map(i=>i.evalSpace)),compositeFieldUsage:(0,XB.mergeCompositeFieldUsage)(...r.map(i=>i.compositeFieldUsage))}}zt.computedExprValue=pE;function Ust({value:t,dataType:e,from:r,timeframe:i}){const s=pE({value:t,dataType:e,from:r}),o={...e,expressionType:s.expressionType,evalSpace:s.evalSpace,value:s.value,compositeFieldUsage:(0,XB.mergeCompositeFieldUsage)(...r.map(u=>u.compositeFieldUsage))};return i&&(o.timeframe=i),o}zt.computedTimeResult=Ust;function jst({dataType:t,from:e,error:r}){return pE({dataType:t??{type:"error"},value:{node:"error",message:r},from:e})}zt.computedErrorExprValue=jst;function qst(t){return pE({...t,from:[]})}zt.literalExprValue=qst;function Hst({value:t,dataType:e,timeframe:r}){const i=pE({value:t,dataType:e,from:[]}),s={...e,expressionType:i.expressionType,evalSpace:i.evalSpace,value:i.value,compositeFieldUsage:(0,XB.emptyCompositeFieldUsage)()};return r&&(s.timeframe=r),s}zt.literalTimeResult=Hst;var U2={};Object.defineProperty(U2,"__esModule",{value:!0}),U2.isGranularResult=void 0;function Qst(t){return t.type==="date"||t.type==="timestamp"?t.timeframe!==void 0:!1}U2.isGranularResult=Qst;var Ru={};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.isComparison=Ru.isEquality=Ru.getExprNode=void 0;function zst(t){switch(t){case"~":return"like";case"!~":return"!like"}return t}Ru.getExprNode=zst;function _0e(t){return t==="="||t==="!="||t==="~"||t==="!~"}Ru.isEquality=_0e;function Wst(t){return _0e(t)||t===">="||t==="<="||t===">"||t==="<"}Ru.isComparison=Wst;var Gst=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Vst=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Yst=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Gst(e,t,r);return Vst(e,t),e};Object.defineProperty(pt,"__esModule",{value:!0}),pt.applyBinary=pt.getMorphicValue=pt.ExprDuration=pt.ExpressionDef=pt.ATNodeType=void 0;const tf=et,Dd=Yst(nn),ZB=zs,m0=zt,Kst=_s,v0e=U2,Jst=Ze,mE=Ru;class Xst extends Error{}var ek;(function(t){t[t.And=0]="And",t[t.Or=1]="Or",t[t.Value=2]="Value",t[t.Partial=3]="Partial"})(ek||(pt.ATNodeType=ek={}));class C0e extends Jst.MalloyElement{constructor(){super(...arguments),this.legalChildTypes=Dd.anyAtomicT}granular(){return!1}requestExpression(e){return this.getExpression(e)}defaultFieldName(){}typeCheck(e,r){return r.type!=="error"&&!Dd.any(r,this.legalChildTypes)?(r.type==="sql native"?e.logError("sql-native-not-allowed-in-expression",{rawType:r.rawType}):e.logError("expression-type-error",`'${this.elementType}' Can't use type ${Dd.inspect(r)}`),!1):!0}apply(e,r,i,s=!1){return R0e(e,i,r,this)}canSupportPartitionBy(){return!1}canSupportOrderBy(){return!1}canSupportLimit(){return!1}supportsWhere(e){return(0,tf.expressionIsAggregate)(e.expressionType)}atNodeType(){return ek.Value}atExpr(){return this}}pt.ExpressionDef=C0e;class tk extends C0e{constructor(e,r){super({n:e}),this.n=e,this.timeframe=r,this.elementType="duration",this.legalChildTypes=[Dd.timestampT,Dd.dateT]}apply(e,r,i){const s=i.getExpression(e);if(this.typeCheck(this,s),(0,tf.isTemporalType)(s.type)&&(r==="+"||r==="-")){const o=this.n.getExpression(e);if(!Dd.typeEq(o,Dd.numberT))return this.logError("invalid-duration-quantity",`Duration quantity needs number not '${o.type}`),(0,ZB.errorFor)("illegal unit expression");let u;return(0,v0e.isGranularResult)(s)&&s.timeframe===this.timeframe&&(u=s.timeframe),s.type==="date"&&!(0,tf.isDateUnit)(this.timeframe)?this.loggedErrorExpr("invalid-timeframe-for-time-offset",`Cannot offset date by ${this.timeframe}`):(0,m0.computedTimeResult)({dataType:{type:s.type},value:(0,Kst.timeOffset)(s.type,s.value,r,o.value,this.timeframe),timeframe:u,from:[s,o]})}return super.apply(e,r,i)}getExpression(e){const r=this.n.getExpression(e);return(0,m0.computedErrorExprValue)({dataType:{type:"duration"},error:"Duration is not a value",from:[r]})}}pt.ExprDuration=tk;function S0e(t,e){return t.type===e?t.value:t.morphic&&t.morphic[e]}function Zst(t,e){if(t.type===e)return t;if(t.morphic&&t.morphic[e])return(0,m0.computedExprValue)({dataType:{type:e},value:t.morphic[e],from:[t]})}pt.getMorphicValue=Zst;function b0e(t,e,r,i){const s=(0,tf.isTemporalType)(e.type),o=(0,tf.isTemporalType)(i.type),u=(0,mE.getExprNode)(r);if(s&&o)if(e.type!==i.type){const a=S0e(e,"timestamp"),l=S0e(i,"timestamp");if(a&&l)return{node:u,kids:{left:a,right:a}}}else return{node:u,kids:{left:e.value,right:i.value}};if((s||o)&&e.type!=="null"&&i.type!=="null")return t.logError("time-comparison-type-mismatch",`Cannot compare a ${e.type} to a ${i.type}`),{node:"false"}}function eot(t,e){if(t.type==="string"){if(e.type==="regular expression")return{node:"regexpMatch",kids:{expr:t.value,regex:e.value}}}else if(e.type==="string"&&t.type==="regular expression")return{node:"regexpMatch",kids:{expr:e.value,regex:t.value}}}function tot(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=(0,mE.getExprNode)(r),a=gE("boolean",s,o);if(a)return a;const l=tf.TD.isSQL(s)?s.rawType||"typeless-left":void 0,c=tf.TD.isSQL(o)?o.rawType||"typeless-right":void 0;if((l||c)&&!(s.type==="null"||o.type==="null"||l===c)){const h=yE(e,s,i,o);if(h)return{...h,type:"boolean"}}let f=b0e(e,s,r,o)||{node:u,kids:{left:s.value,right:o.value}};if(s.type!=="error"&&o.type!=="error"&&(r==="~"||r==="!~")&&(s.type!=="string"||o.type!=="string")){let x=eot(s,o);if(x)r[0]==="!"&&(x={node:"not",e:{...x}});else throw new Xst("Incompatible types for match('~') operator");f=x}return(0,m0.computedExprValue)({dataType:{type:"boolean"},value:f,from:[s,o]})}function not(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=gE("boolean",s,o);if(u)return u;const a=yE(e,s,i,o);if(a)return{...a,type:"boolean"};const l=b0e(e,s,r,o)||{node:(0,mE.getExprNode)(r),kids:{left:s.value,right:o.value}};return(0,m0.computedExprValue)({dataType:{type:"boolean"},value:l,from:[s,o]})}function T0e(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=gE("number",s,o);if(u)return u;const a=yE(e,s,i,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${s.type}'`);else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch",`The '${r}' operator requires a number, not a '${o.type}'`);else return(0,m0.computedExprValue)({dataType:{type:"number"},value:{node:r,kids:{left:s.value,right:o.value}},from:[s,o]});return(0,ZB.errorFor)("numbers required")}function rot(t,e,r,i){const s=e.getExpression(t),o=i.getExpression(t),u=yE(e,s,i,o);if(u)return u;const a=(0,tf.isTemporalType)(s.type),l=gE(a?"error":"number",s,o);if(l)return l;if(a){let c=i;if(o.type!=="duration")if((0,v0e.isGranularResult)(s))c=new tk(i,s.timeframe);else if(s.type==="date")c=new tk(i,"day");else return e.loggedErrorExpr("time-offset-type-mismatch",`Can not offset time by '${o.type}'`);return c.apply(t,r,e)}return T0e(t,e,r,i)}function R0e(t,e,r,i){if((0,mE.isEquality)(r))return tot(t,e,r,i);if((0,mE.isComparison)(r))return not(t,e,r,i);if(r==="+"||r==="-")return rot(t,e,r,i);if(r==="*")return T0e(t,e,r,i);if(r==="/"||r==="%"){const s=e.getExpression(t),o=i.getExpression(t),u=yE(e,s,i,o);if(u)return u;const a=gE("number",s,o);if(a)return a;if(s.type!=="number")e.logError("arithmetic-operation-type-mismatch","Numerator must be a number");else if(o.type!=="number")i.logError("arithmetic-operation-type-mismatch","Denominator must be a number");else{const l={node:r,kids:{left:s.value,right:o.value}};return(0,m0.computedExprValue)({dataType:{type:"number"},value:l,from:[s,o]})}return(0,ZB.errorFor)("divide type mismatch")}return e.loggedErrorExpr("unexpected-binary-operator",`Cannot use ${r} operator here`)}pt.applyBinary=R0e;function gE(t,...e){if(e.some(r=>r.type==="error"))return(0,m0.computedExprValue)({dataType:{type:t},value:{node:"error",message:"cascading error"},from:e})}function yE(t,e,r,i){const s=(0,m0.computedExprValue)({dataType:e,value:{node:"error",message:"sql-native unsupported"},from:[e,i]});if(e.type==="sql native")return t.logError("sql-native-not-allowed-in-expression",{rawType:e.rawType}),s.type=i.type,s;if(i.type==="sql native")return r.logError("sql-native-not-allowed-in-expression",{rawType:i.rawType}),s}Object.defineProperty(Rd,"__esModule",{value:!0}),Rd.ExprIdReference=void 0;const iot=et,sot=pt,oot=dt;class uot extends sot.ExpressionDef{constructor(e){super(),this.fieldReference=e,this.elementType="ExpressionIdReference",this.has({fieldPath:e})}get refString(){return this.fieldReference.refString}getExpression(e){const r=this.fieldReference.getField(e),i=this.fieldReference.list.map(s=>s.name).slice(0,-1);if(r.found){const s=r.found.typeDesc(),o=(0,oot.joinedCompositeFieldUsage)(i,s.compositeFieldUsage);if(r.isOutputField)return{...s,evalSpace:s.evalSpace==="constant"?"constant":"output",value:{node:"outputField",name:this.refString},compositeFieldUsage:o};const u={node:r.found.refType,path:this.fieldReference.path},a=(0,iot.expressionIsAggregate)(s.expressionType)?"output":s.evalSpace;return{...s,value:u,evalSpace:a,compositeFieldUsage:o}}return this.loggedErrorExpr(r.error.code,r.error.message)}}Rd.ExprIdReference=uot,Object.defineProperty(P2,"__esModule",{value:!0}),P2.NamedSource=void 0;const nk=et,aot=Ro,lot=yi,cot=_s,D0e=Ze,fot=Rd,xot=N2;class dot extends aot.Source{constructor(e,r,i){super(),this.ref=e,this.sourceArguments=r,this.args=i,this.elementType="namedSource",i&&this.has({args:i}),e instanceof D0e.ModelEntryReference&&this.has({ref:e})}get refName(){return this.ref instanceof D0e.ModelEntryReference?this.ref.name:this.ref}structRef(e){const r=this.modelEntry(this.ref);return r&&!r.exported?{structRef:this.getSourceDef(e)}:{structRef:this.refName,sourceArguments:this.evaluateArgumentsForRef(e)}}refLogError(e,r,i){typeof this.ref=="string"?this.logError(e,r,i):this.ref.logError(e,r,i)}modelStruct(){var e;const r=this.modelEntry(this.ref),i=r==null?void 0:r.entry;if(!i){this.refLogError("source-not-found",`Undefined source '${this.refName}'`);return}if(i.type==="query"){this.logError("invalid-source-from-query",`Cannot construct a source from query '${this.refName}'`);return}else if(i.type==="function"){this.logError("invalid-source-from-function",`Cannot construct a source from a function '${this.refName}'`);return}else if(i.type==="connection"){this.logError("invalid-source-from-connection",`Cannot construct a source from a connection '${this.refName}'`);return}else if((e=this.document())===null||e===void 0||e.checkExperimentalDialect(this,i.dialect),(0,nk.isSourceDef)(i))return{...i};this.logError("invalid-source-source","Cannot construct a source from a never type")}evaluateArgumentsForRef(e){const r=this.modelStruct();return r===void 0?{}:this.evaluateArguments(e,r.parameters,[])}evaluateArguments(e,r,i){var s,o;const u={...this.sourceArguments},a=new Set;for(const l of(s=this.args)!==null&&s!==void 0?s:[]){const c=(o=l.id)!==null&&o!==void 0?o:l.value instanceof fot.ExprIdReference?l.value.fieldReference:void 0;if(c===void 0){l.value.logError("unnamed-source-argument","Parameterized source arguments must be named with `parameter_name is`");continue}const f=c.outputName;if(a.has(f)){l.logError("duplicate-source-argument",`Cannot pass argument for \`${f}\` more than once`);continue}a.add(f);const x=(r??{})[f];if(!x)c.logError("source-parameter-not-found",`\`${this.refName}\` has no declared parameter named \`${c.refString}\``);else{const h=e??new xot.ParameterSpace(i??[]),p=l.value.getExpression(h);let m=p.value;p.type!==x.type&&(0,nk.isCastType)(x.type)&&(m=(0,cot.castTo)(x.type,p.value,p.type,!0)),u[f]={...x,value:m}}}for(const l in r)l in u||((0,nk.paramHasValue)(r[l])?u[l]={...r[l]}:this.refLogError("missing-source-argument",`Argument not provided for required parameter \`${l}\``));return u}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){var i;const s=this.modelStruct();if(!s){const l=lot.ErrorFactory.structDef,c=`${this.refName}-undefined`;return l.name=l.name+c,l.dialect=l.dialect+c,l}const o={};for(const l of r??[]){const c=l.parameter();o[c.name]=c}const u=this.evaluateArguments(e,s.parameters,r),a={...s,parameters:o,arguments:u};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(a),a}}P2.NamedSource=dot;var EE={},X4={};Object.defineProperty(X4,"__esModule",{value:!0}),X4.QueryHeadStruct=void 0;const hot=et,pot=Ro,mot=P2;class got extends pot.Source{constructor(e,r){super(),this.fromRef=e,this.sourceArguments=r,this.elementType="internalOnlyQueryHead"}structRef(){return{structRef:this.fromRef}}getSourceDef(e){if((0,hot.refIsStructDef)(this.fromRef))return this.fromRef;const r=new mot.NamedSource(this.fromRef,this.sourceArguments,void 0);return this.has({exploreReference:r}),r.getSourceDef(e)}}X4.QueryHeadStruct=got,Object.defineProperty(EE,"__esModule",{value:!0}),EE.QueryReference=void 0;const rk=yi,yot=Ze,Eot=X4,Aot=et,_ot=Gs;class vot extends yot.MalloyElement{constructor(e){super(),this.name=e,this.elementType="query-reference"}queryComp(e){const r=this.modelEntry(this.name),i=r==null?void 0:r.entry,s=function(){return{inputStruct:rk.ErrorFactory.structDef,outputStruct:rk.ErrorFactory.structDef,query:rk.ErrorFactory.query}};if(!i)return this.logError("query-reference-not-found",`Reference to undefined query '${this.name.refString}'`),s();if(i.type==="query"){const o=new Eot.QueryHeadStruct(i.structRef,i.sourceArguments);this.has({queryHead:o});const u=o.getSourceDef(void 0),a=(0,_ot.getFinalStruct)(this,u,i.pipeline);return{query:e||(0,Aot.refIsStructDef)(i.structRef)?i:{...i,structRef:u},outputStruct:a,inputStruct:u}}return this.logError("non-query-used-as-query",`Illegal reference to '${this.name}', query expected`),s()}query(){return this.queryComp(!0).query}}EE.QueryReference=vot,Object.defineProperty(hE,"__esModule",{value:!0}),hE.SQReference=void 0;const Cot=Tu,Sot=Td,bot=P2,O0e=EE,w0e=Yi;class Tot extends Cot.SourceQueryElement{constructor(e,r){super({ref:e}),this.ref=e,this.args=r,this.elementType="sq-reference",r!==void 0&&this.has({args:r})}getQuery(){const e=this.ref.getNamed();if(e)if(e.type==="query"){const r=new O0e.QueryReference(this.ref);return this.has({query:r}),r}else this.sqLog("cannot-use-as-query",`Illegal reference to '${e.as||e.name}', query expected`);else this.ref.logError("source-or-query-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0}isSource(){const e=this.ref.getNamed();return e!==void 0&&(0,w0e.isSourceDef)(e)}getSource(){if(this.asSource)return this.asSource;const e=this.ref.getNamed();if(!e){this.ref.logError("source-not-found",`Reference to undefined object '${this.ref.refString}'`),this.errored=!0;return}if(e.type==="query"){this.args!==void 0&&this.ref.logError("illegal-query-argument","Arguments cannot be passed to queries");const r=new O0e.QueryReference(this.ref);this.asSource=new Sot.QuerySource(r)}else if((0,w0e.isSourceDef)(e))this.asSource=new bot.NamedSource(this.ref,void 0,this.args);else{this.sqLog("cannot-use-struct-as-source",`Expected '${this.ref.refString}' to be of type query or source, not '${e.type}'`);return}return this.has({asSource:this.asSource}),this.asSource}}hE.SQReference=Tot,Object.defineProperty(K4,"__esModule",{value:!0}),K4.SQRefine=void 0;const Rot=Tu,Dot=Td,Oot=M2,wot=hE;class Fot extends Rot.SourceQueryElement{constructor(e,r){super({toRefine:e,refine:r}),this.toRefine=e,this.refine=r,this.elementType="sq-refine"}getQuery(){if(this.toRefine.isSource()){this.toRefine instanceof wot.SQReference?this.sqLog("illegal-refinement-of-source",`Cannot add view refinements to '${this.toRefine.ref.refString}' because it is a source`):this.sqLog("illegal-refinement-of-source","Cannot add view refinements to a source");return}const e=this.toRefine.getQuery();if(e){const r=new Oot.QueryRefine(e,this.refine);return this.has({query:r}),r}}getSource(){const e=this.getQuery();if(e){const r=new Dot.QuerySource(e);return this.has({queryAsSource:r}),r}}}K4.SQRefine=Fot;var Z4={},AE={};Object.defineProperty(AE,"__esModule",{value:!0}),AE.QueryRaw=void 0;const Not=et,Lot=Ze;class Iot extends Lot.MalloyElement{constructor(e){super({source:e}),this.source=e,this.elementType="query-raw"}queryComp(e){const r=e?this.source.structRef(void 0):{structRef:this.source.getSourceDef(void 0)},i=(0,Not.refIsStructDef)(r.structRef)?r.structRef:this.source.getSourceDef(void 0);return{query:{type:"query",...r,pipeline:[{type:"raw",fields:[]}],location:this.location},outputStruct:i,inputStruct:i}}query(){return this.queryComp(!0).query}}AE.QueryRaw=Iot;var _E={},g0={};Object.defineProperty(g0,"__esModule",{value:!0}),g0.sqlKey=g0.compileSQLInterpolation=void 0;const $ot=Hs,Bot=et,kot=kt;function Mot(t,e,r){let i,s="",o=!1;for(const u of t)if((0,Bot.isSegmentSQL)(u))s+=u.sql,o=u.sql.match(/\(\s*$/)!==null;else{if(!i){if(!r)throw new Error("Internal error: Partial model missing when compiling SQL block");i=new $ot.QueryModel(r)}const a=i.compileQuery(u,{defaultRowLimit:void 0},!1).sql;s+=o?a:`(${a})`,o=!1}return{connection:e,selectStr:s}}g0.compileSQLInterpolation=Mot;function Pot(t,e){return`sql://${t}/${(0,kot.generateHash)(e)}`}g0.sqlKey=Pot,Object.defineProperty(_E,"__esModule",{value:!0}),_E.SQLSource=void 0;const ik=g0,Uot=Ro,vE=yi;class jot extends Uot.Source{constructor(e,r){super({connectionName:e,select:r}),this.connectionName=e,this.select=r,this.elementType="sqlSource",this.connectionNameInvalid=!1}sqlSourceRequest(e){const r=this.select.containsQueries?e.modelDef():void 0;return(0,ik.compileSQLInterpolation)(this.select.sqlPhrases(),this.connectionName.refString,r)}structRef(){return{structRef:this.getSourceDef()}}validateConnectionName(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(this.connectionNameInvalid)return!1;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection")return this.connectionName.logError("invalid-connection-for-sql-source",`${this.connectionName.refString} is not a connection`),this.connectionNameInvalid=!0,!1;return!0}needs(e){var r;if(!this.validateConnectionName())return;const i=super.needs(e);if(i)return i;this.requestBlock===void 0&&(this.requestBlock=this.sqlSourceRequest(e));const s=this.requestBlock,o=(r=this.translator())===null||r===void 0?void 0:r.root.sqlQueryZone;if(!o){this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block");return}const u=(0,ik.sqlKey)(s.connection,s.selectStr);o.reference(u,this.location);const a=o.getEntry(u);if(a.status==="reference")return{compileSQL:s};a.status==="present"&&e.checkExperimentalDialect(this,a.value.dialect)}getSourceDef(){var e;if(!this.validateConnectionName())return vE.ErrorFactory.structDef;const r=(e=this.translator())===null||e===void 0?void 0:e.root.sqlQueryZone;if(!r)return this.logError("failed-to-fetch-sql-source-schema","Cant't look up schema for sql block"),vE.ErrorFactory.structDef;if(this.requestBlock===void 0)return this.logError("failed-to-fetch-sql-source-schema","Expected to have already compiled the sql block"),vE.ErrorFactory.structDef;const i=this.requestBlock,s=(0,ik.sqlKey)(i.connection,i.selectStr);r.reference(s,this.location);const o=r.getEntry(s);if(o.status==="error"){const u=o.message.split(/\r?\n/);return this.select.logError("invalid-sql-source","Invalid SQL, "+u.join(`
1555
- `)),vE.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),vE.ErrorFactory.structDef}}_E.SQLSource=jot,Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.SQSource=void 0;const qot=Tu,Hot=AE,Qot=_E;class zot extends qot.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Qot.SQLSource){const e=new Hot.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}Z4.SQSource=zot;var eT={};Object.defineProperty(eT,"__esModule",{value:!0}),eT.SQExtend=void 0;const Wot=uE,Got=Tu;class Vot extends Got.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Wot.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}eT.SQExtend=Vot;var tT={},nT={};Object.defineProperty(nT,"__esModule",{value:!0}),nT.CompositeSource=void 0;const Yot=et,Kot=Ro;class Jot extends Kot.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,Yot.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,y=l.get(m);if(y===void 0){const g={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,g),a.push(g)}else p.accessModifier==="internal"&&(y.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}nT.CompositeSource=Jot,Object.defineProperty(tT,"__esModule",{value:!0}),tT.SQCompose=void 0;const Xot=nT,Zot=Tu;class eut extends Zot.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(tut(e))return this.asSource=new Xot.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}tT.SQCompose=eut;function tut(t){return t.every(e=>e!==void 0)}var rT={},y0={},CE={},nut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),rut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),iut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nut(e,t,r);return rut(e,t),e};Object.defineProperty(CE,"__esModule",{value:!0}),CE.BinaryBoolean=void 0;const sut=zs,out=iut(nn),uut=Ru,aut=zt,lut=pt;class cut extends lut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[out.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,aut.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,uut.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,sut.errorFor)("logical-op expected boolean")}}CE.BinaryBoolean=cut;var fut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fut(e,t,r);return xut(e,t),e};Object.defineProperty(y0,"__esModule",{value:!0}),y0.ExprLegacyIn=y0.ExprEquality=y0.ExprCompare=void 0;const hn=dut(nn),hut=zt,put=pt,mut=CE,gut={"~":[hn.stringT],"!~":[hn.stringT],"<":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"<=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"!=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT]};class F0e extends mut.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=gut[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}y0.ExprCompare=F0e;class yut extends F0e{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}y0.ExprEquality=yut;class Eut extends put.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,hut.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}y0.ExprLegacyIn=Eut;var SE={},j2={};Object.defineProperty(j2,"__esModule",{value:!0}),j2.ExprTime=void 0;const Aut=et,_ut=zt,vut=pt;class sk extends vut.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,_ut.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,Aut.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new sk(e,i,[r])}}j2.ExprTime=sk;var nf={};Object.defineProperty(nf,"__esModule",{value:!0}),nf.Range=void 0;const Cut=zs,Sut=zt,but=pt;class Tut extends but.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Sut.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Cut.errorFor)("a range is not a value")}}nf.Range=Tut;var Rut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Out=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rut(e,t,r);return Dut(e,t),e};Object.defineProperty(SE,"__esModule",{value:!0}),SE.ExprGranularTime=void 0;const ok=et,wut=zs,N0e=Out(nn),L0e=_s,Fut=pt,iT=j2,I0e=nf;class Nut extends Fut.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[N0e.timestampT,N0e.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(ok.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,ok.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,ok.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,wut.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=iT.ExprTime.fromValue("timestamp",r),l=new iT.ExprTime("timestamp",(0,L0e.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new I0e.Range(a,l)}const s=new iT.ExprTime("date",r.value,[r]),o=(0,L0e.timeOffset)("date",r.value,"+",i,this.units),u=new iT.ExprTime("date",o,[r]);return new I0e.Range(s,u)}}SE.ExprGranularTime=Nut,Object.defineProperty(rT,"__esModule",{value:!0}),rT.Apply=void 0;const Lut=y0,Iut=U2,$0e=SE;class $ut extends Lut.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,Iut.isGranularResult)(i)&&(r=new $0e.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof $0e.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}rT.Apply=$ut;var q2={},But=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&But(e,t,r);return kut(e,t),e};Object.defineProperty(q2,"__esModule",{value:!0}),q2.BinaryNumeric=void 0;const Put=Mut(nn),Uut=pt;class jut extends Uut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[Put.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}q2.BinaryNumeric=jut;var sT={},qut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Hut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qut(e,t,r);return Hut(e,t),e};Object.defineProperty(sT,"__esModule",{value:!0}),sT.Boolean=void 0;const zut=pt,Wut=Qut(nn);let Gut=class extends zut.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Wut.boolT,value:{node:this.value}}}};sT.Boolean=Gut;var rf={};Object.defineProperty(rf,"__esModule",{value:!0}),rf.FunctionOrdering=rf.FunctionOrderBy=void 0;const uk=et,B0e=Ze,Vut=Rd;class Yut extends B0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,uk.expressionIsAggregate)(r.expressionType)||((0,uk.expressionIsScalar)(r.expressionType)?(!(this.field instanceof Vut.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,uk.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}rf.FunctionOrderBy=Yut;class Kut extends B0e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}rf.FunctionOrdering=Kut;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ExprAddSub=void 0;const Jut=q2;class Xut extends Jut.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}oT.ExprAddSub=Xut;var E0={},Zut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zut(e,t,r);return eat(e,t),e};Object.defineProperty(E0,"__esModule",{value:!0}),E0.ExprAggregateFunction=void 0;const bE=et,nat=kt,rat=zs,k0e=Gr,M0e=tat(nn),iat=_t,sat=pt,oat=Wr,uat=Rd;class aat extends sat.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[M0e.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof k0e.StructSpaceField))if((0,bE.isAtomicFieldType)(p.type)){u=this.source,a={...M0e.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(g=>lat(g,m[0])))&&(l=m[0].map(g=>g.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,bE.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=lk(c,x),y=ck(this.elementType,m),g=h?y==null?void 0:y.message:"Join path is required for this calculation";if(g){const E=cat(g,x,u,this.elementType),A=(s=y==null?void 0:y.code)!==null&&s!==void 0?s:"bad-join-usage";y?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,rat.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...ak(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...ak(e,i))}return r}}E0.ExprAggregateFunction=aat;function lat(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function ak(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof k0e.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof oat.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,nat.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,bE.isAtomic)(u)&&!(0,bE.isJoined)(u))if((0,bE.hasExpression)(u)){const a=ak(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function lk(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function ck(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function cat(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let y=0;y<s.length;y++){const g=s[y],E=m[y];if(g.name!==E.name){s=s.slice(0,y);break}}const o=lk(s,e),u=ck(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=lk(c,e),x=ck(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof iat.FieldReference?`${r.refString}.${i}()`:r instanceof uat.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,y=`${p}.${i}(${r.code})`;let g=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(g+=` or \`${y}\` to get a result weighted with respect to \`${p}\``),g}}var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.ExprAlternationTree=void 0;const P0e=zt,H2=pt,fat=Ru;function fk(t){const e=t.atExpr();switch(e.atNodeType()){case H2.ATNodeType.And:case H2.ATNodeType.Partial:return;case H2.ATNodeType.Or:{if(e instanceof U0e){const r=fk(e.left);if(r){const i=fk(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class U0e extends H2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=fk(this)||[]),this.inList}apply(e,r,i,s){if((0,fat.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,P0e.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,P0e.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?H2.ATNodeType.Or:H2.ATNodeType.And}}uT.ExprAlternationTree=U0e;var Q2={};Object.defineProperty(Q2,"__esModule",{value:!0}),Q2.ExprAsymmetric=void 0;const xat=E0;class dat extends xat.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}Q2.ExprAsymmetric=dat;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ExprAvg=void 0;const hat=Q2;class pat extends hat.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}aT.ExprAvg=pat;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ExprCast=void 0;const mat=_s,gat=zt,yat=pt;class Eat extends yat.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,gat.computedExprValue)({dataType:i,value:(0,mat.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}lT.ExprCast=Eat;var cT={},Aat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_at=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Aat(e,t,r);return _at(e,t),e};Object.defineProperty(cT,"__esModule",{value:!0}),cT.ExprCoalesce=void 0;const j0e=Yi,q0e=vat(nn),Cat=pt;class Sat extends Cat.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=q0e.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(q0e.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,j0e.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,j0e.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}cT.ExprCoalesce=Sat;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.ExprCount=void 0;const bat=dt,Tat=E0;class Rat extends Tat.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,bat.emptyCompositeFieldUsage)()}}}fT.ExprCount=Rat;var xT={},Dat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Oat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dat(e,t,r);return Oat(e,t),e};Object.defineProperty(xT,"__esModule",{value:!0}),xT.ExprCountDistinct=void 0;const dT=wat(nn),Fat=E0;class Nat extends Fat.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[dT.numberT,dT.stringT,dT.dateT,dT.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}xT.ExprCountDistinct=Nat;var hT={},sf={};Object.defineProperty(sf,"__esModule",{value:!0}),sf.Limit=void 0;const Lat=Ze,Iat=Wn;class $at extends Lat.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Iat.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}sf.Limit=$at;var z2={};Object.defineProperty(z2,"__esModule",{value:!0}),z2.PartitionBy=void 0;const Bat=Ze;class kat extends Bat.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}z2.PartitionBy=kat;var TE={},of={};Object.defineProperty(of,"__esModule",{value:!0}),of.FieldName=void 0;const Mat=Ze;class Pat extends Mat.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}of.FieldName=Pat;var Uat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uat(e,t,r);return jat(e,t),e};Object.defineProperty(TE,"__esModule",{value:!0}),TE.ExprFunc=void 0;const Or=et,Hat=zs,Qat=bd,zat=zt,Wat=pt,Gat=of,H0e=kt,Q0e=qat(nn),Vat=dt;class Yat extends Wat.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((U,V)=>{V!==0&&B.push(","),B.push(U.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},$=this.rawType?{type:this.rawType}:D;return(0,zat.computedExprValue)({dataType:$,value:(0,H0e.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Hat.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const $=D.typeDesc();if((0,Or.isAtomicFieldType)($.type))x={...Q0e.atomicDef($),expressionType:$.expressionType,value:{node:"field",path:this.source.path},evalSpace:$.evalSpace,compositeFieldUsage:$.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Qat.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${$.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=Kat(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:y,expressionTypeErrors:g,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of g){const D=B.argIndex-(x?1:0),$=(0,Or.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),$=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=y.returnType,C=(0,Or.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Or.expressionIsAggregate)(y.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const S={node:"function_call",overload:y,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let b=S;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Or.expressionIsAnalytic)(y.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),y.supportsOrderBy||B){const D=y.supportsOrderBy!=="only_default",$=r.orderBys.flatMap(U=>B?U.getAnalyticOrderBy(e):U.getAggregateOrderBy(e,D));S.kids.orderBy=$}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(y.supportsLimit?S.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const $ of D.partitionFields){const U=$.getField(e);U.found===void 0?$.logError("partition-by-not-found",`${$.refString} is not defined`):(0,Or.expressionIsAnalytic)(U.found.typeDesc().expressionType)||(0,Or.expressionIsUngroupedAggregate)(U.found.typeDesc().expressionType)?$.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push($.nameString)}S.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,$=Jat(D),U=$.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(U.length>0){const Q=U.length===1?`'.' paths are not yet supported in sql interpolations, found ${U.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${U.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const V=[];for(const Q of $)if(Q.type==="string")V.push(Q.value);else if(Q.name==="TABLE")V.push({node:"source-reference"});else{const Z=new Gat.FieldName(Q.name);this.has({name:Z});const de=e.lookup([Z]);if(de.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${de.error.message}`);de.found.refType==="parameter"?V.push({node:"parameter",path:[Q.name]}):V.push({node:"field",path:[Q.name]})}b=(0,H0e.composeSQLExpr)(V)}}const R=(0,Or.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Or.expressionIsScalar)(C)?R:"output";return{...(0,Or.isAtomic)(_)?Q0e.atomicDef(_):_,expressionType:C,value:b,evalSpace:O,compositeFieldUsage:(0,Vat.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}TE.ExprFunc=Yat;function Kat(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],y=i.params[o];if(y===void 0){u=!1;break}if(!y.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=W2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Or.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:y})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Or.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:y,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:y}),_})){u=!1;break}y.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=pT(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function Jat(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function W2(t,e,r,i){var s,o,u,a;if(Or.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Or.isScalarArray)(r))return(0,Or.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:W2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Or.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return W2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=W2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return W2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=W2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Or.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function pT(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=pT(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=pT(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Or.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=pT(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var Xat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Zat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),elt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xat(e,t,r);return Zat(e,t),e};Object.defineProperty(hT,"__esModule",{value:!0}),hT.ExprProps=void 0;const tlt=et,nlt=zs,rlt=elt(nn),ilt=rf,slt=sf,olt=z2,ult=pt,alt=TE,llt=dt;class clt extends ult.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=rlt.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,tlt.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,llt.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,nlt.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof olt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof slt.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof ilt.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof alt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}hT.ExprProps=clt;var mT={},flt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&flt(e,t,r);return xlt(e,t),e};Object.defineProperty(mT,"__esModule",{value:!0}),mT.ExprLogicalOp=void 0;const hlt=CE,z0e=dlt(nn);class plt extends hlt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[z0e.boolT,z0e.aggregateBoolT]}}mT.ExprLogicalOp=plt;var gT={},mlt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),glt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ylt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mlt(e,t,r);return glt(e,t),e};Object.defineProperty(gT,"__esModule",{value:!0}),gT.ExprMax=void 0;const yT=ylt(nn),Elt=E0;class Alt extends Elt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[yT.numberT,yT.stringT,yT.dateT,yT.timestampT]}returns(e){return e}}gT.ExprMax=Alt;var ET={},_lt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),vlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Clt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_lt(e,t,r);return vlt(e,t),e};Object.defineProperty(ET,"__esModule",{value:!0}),ET.ExprMin=void 0;const AT=Clt(nn),Slt=E0;class blt extends Slt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[AT.numberT,AT.stringT,AT.dateT,AT.timestampT]}returns(e){return e}}ET.ExprMin=blt;var _T={},Tlt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Rlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Tlt(e,t,r);return Rlt(e,t),e};Object.defineProperty(_T,"__esModule",{value:!0}),_T.ExprMinus=void 0;const Olt=zs,W0e=Dlt(nn),wlt=pt;class Flt extends wlt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[W0e.numberT]}getExpression(e){const r=this.expr.getExpression(e);return W0e.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Olt.errorFor)("negate requires number")}}_T.ExprMinus=Flt;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.ExprMulDiv=void 0;const Nlt=q2;class Llt extends Nlt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}vT.ExprMulDiv=Llt;var CT={},RE={};Object.defineProperty(RE,"__esModule",{value:!0}),RE.Unary=void 0;const Ilt=pt;class $lt extends Ilt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}RE.Unary=$lt;var Blt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),klt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Blt(e,t,r);return klt(e,t),e};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ExprNot=void 0;const xk=Mlt(nn),Plt=RE;class Ult extends Plt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[xk.boolT,xk.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(xk.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}CT.ExprNot=Ult;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.ExprNow=void 0;const jlt=pt,qlt=dt;class Hlt extends jlt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,qlt.emptyCompositeFieldUsage)()}}}ST.ExprNow=Hlt;var uf={};Object.defineProperty(uf,"__esModule",{value:!0}),uf.ExprIsNull=uf.PartialIsNull=uf.ExprNULL=void 0;const Qlt=zt,bT=pt;function dk(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class zlt extends bT.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Qlt.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?dk(e,r,i):super.apply(e,r,i,!0)}}uf.ExprNULL=zlt;class Wlt extends bT.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return dk(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return bT.ATNodeType.Partial}}uf.PartialIsNull=Wlt;class Glt extends bT.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return dk(e,this.op,this.expr)}}uf.ExprIsNull=Glt;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.ExprNumber=void 0;const Vlt=zt,Ylt=pt;class Klt extends Ylt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,Vlt.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}TT.ExprNumber=Klt;var RT={};Object.defineProperty(RT,"__esModule",{value:!0}),RT.ExprParens=void 0;const hk=pt;class Jlt extends hk.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===hk.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,hk.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}RT.ExprParens=Jlt;var DT={};Object.defineProperty(DT,"__esModule",{value:!0}),DT.ExprFilterExpression=void 0;const Xlt=zt,Zlt=pt,OT=I4;class e0t extends Zlt.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return this.loggedErrorExpr("filter-expression-type","Filter expression illegal here")}apply(e,r,i,s=!1){var o;if(r==="~"||r==="!~"){const u=i.getExpression(e);if(u.type==="error")return u;let a;switch(u.type){case"string":a=OT.StringFilterExpression.parse(this.filterText);break;case"number":a=OT.NumberFilterExpression.parse(this.filterText);break;case"boolean":if(!((o=e.dialectObj())===null||o===void 0)&&o.booleanAsNumbers)return this.loggedErrorExpr("filter-expression-type","Boolean filters not supported on this connection type");a=OT.BooleanFilterExpression.parse(this.filterText);break;case"date":case"timestamp":a=OT.TemporalFilterExpression.parse(this.filterText);break;default:return i.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${u.type}'`)}if(a.log.length>0)for(const c of a.log)return this.loggedErrorExpr("filter-expression-error",`Filter parse error: ${c.message}`);if(!a.parsed)return this.loggedErrorExpr("filter-expression-type","FJKLD:JDKSL: expression parsed to null");const l={node:"filterMatch",dataType:u.type,filter:a.parsed,e:u.value};return r==="!~"&&(l.notMatch=!0),(0,Xlt.computedExprValue)({value:l,dataType:{type:"boolean"},from:[u]})}return this.loggedErrorExpr("filter-expression-type",`Cannot use the '${r}' operator with a filter expression`)}}DT.ExprFilterExpression=e0t;var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.ExprRegEx=void 0;const t0t=zt,n0t=pt;class r0t extends n0t.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,t0t.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}wT.ExprRegEx=r0t;var FT={};Object.defineProperty(FT,"__esModule",{value:!0}),FT.ExprString=void 0;const i0t=pt,s0t=zt;class o0t extends i0t.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,s0t.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}FT.ExprString=o0t;var NT={};Object.defineProperty(NT,"__esModule",{value:!0}),NT.ExprSum=void 0;const u0t=Q2;class a0t extends u0t.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}NT.ExprSum=a0t;var LT={};Object.defineProperty(LT,"__esModule",{value:!0}),LT.ExprTimeExtract=void 0;const A0=et,IT=zt,pk=pt,l0t=nf;class DE extends pk.ExpressionDef{static extractor(e){const r=DE.pluralMap[e];if(r)return r;if((0,A0.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=DE.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof l0t.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,IT.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,A0.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,A0.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!A0.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,pk.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,pk.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,A0.isTimestampUnit)(r)?(0,IT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,A0.mkTemporal)(s.value,u),right:(0,A0.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,A0.isTemporalType)(s.type)?(0,IT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,A0.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,IT.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}LT.ExprTimeExtract=DE,DE.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var $T={},Du={},BT={};Object.defineProperty(BT,"__esModule",{value:!0}),BT.QueryInputSpace=void 0;const c0t=As,f0t=w2;class x0t extends f0t.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof c0t.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}BT.QueryInputSpace=x0t;var d0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),h0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),p0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&d0t(e,t,r);return h0t(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.ReduceFieldSpace=Du.QuerySpace=Du.QueryOperationSpace=void 0;const kT=p0t(et),mk=Kc,G0e=of,V0e=Wr,m0t=_t,g0t=w2,y0t=lE,E0t=Gr,A0t=BT,Qa=dt,_0t=bd;class Y0e extends g0t.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new A0t.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof E0t.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();kT.TD.isAtomic(c)&&kT.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof V0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new G0e.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof _0t.StructSpaceFieldBase)return(0,Qa.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Qa.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Qa.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Qa.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof V0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Qa.compositeFieldUsageDifference)(s,r));if(r=(0,Qa.mergeCompositeFieldUsage)(r,u),!(0,Qa.isEmptyCompositeFieldUsage)(u)){const a=(0,Qa.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}Du.QueryOperationSpace=Y0e;class K0e extends Y0e{addRefineFromFields(e){var r;if(kT.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new G0e.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new y0t.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof m0t.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Qa.emptyCompositeFieldUsage)(),i=(0,Qa.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!C0t(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(kT.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,mk.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,mk.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,mk.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Du.QuerySpace=K0e;class v0t extends K0e{constructor(){super(...arguments),this.segmentType="reduce"}}Du.ReduceFieldSpace=v0t;function C0t(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var S0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),b0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),T0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&S0t(e,t,r);return b0t(e,t),e};Object.defineProperty($T,"__esModule",{value:!0}),$T.ExprUngroup=void 0;const J0e=et,R0t=Du,X0e=T0t(nn),D0t=pt;class O0t extends D0t.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=X0e.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,J0e.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,J0e.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof R0t.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...X0e.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}$T.ExprUngroup=O0t;var MT={},w0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),F0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),N0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&w0t(e,t,r);return F0t(e,t),e};Object.defineProperty(MT,"__esModule",{value:!0}),MT.ForRange=void 0;const L0t=zs,Z0e=N0t(nn),PT=_s,I0t=zt,$0t=pt,UT=j2,ece=nf;class B0t extends $0t.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Z0e.timestampT,Z0e.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,L0t.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,I0t.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,PT.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,y=(0,PT.timeOffset)("date",s.value,"+",u.value,a),g=new UT.ExprTime("date",y);return new ece.Range(m,g).apply(e,r,i)}const c=UT.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,PT.castTo)("timestamp",x,"date"),f=new UT.ExprTime("timestamp",x,[s])}const h=(0,PT.timeOffset)("timestamp",x,"+",u.value,a),p=new UT.ExprTime("timestamp",h,[s,u]);return new ece.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}MT.ForRange=B0t;var wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.LiteralYear=wr.LiteralQuarter=wr.LiteralMonth=wr.LiteralWeek=wr.LiteralDay=wr.LiteralHour=wr.LiteralTimestamp=wr.TimeFormatError=void 0;const af=qr,k0t=et,M0t=zt,P0t=nf,tce=j2,gk=pt;class U0t extends Error{}wr.TimeFormatError=U0t;function Od(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const nce="yyyy",rce=`${nce}-LL`,Do=`${rce}-dd`,ice=`${Do} HH`,sce=`${ice}:mm`,yk=`${sce}:ss`;class oce extends gk.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,M0t.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class Ek extends oce{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=Od(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=af.DateTime.fromFormat(e,yk);if(o.isValid)return new Ek(i,r);if(o=af.DateTime.fromFormat(e,sce),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(yk);return new Ak(i,r,"timestamp",u)}}}wr.LiteralTimestamp=Ek;class Ak extends oce{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,gk.getMorphicValue)(s,"timestamp"),l=(0,gk.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,k0t.isTemporalType)(u.type)){const a=u.type;return new P0t.Range(new tce.ExprTime(a,s.value),new tce.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class _k extends Ak{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,ice);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(yk),new _k(r,i)}}wr.LiteralHour=_k;class OE extends Ak{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class vk extends OE{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,Do);if(s.isValid)return i=s.plus({day:1}).toFormat(Do),new vk(r,i)}}wr.LiteralDay=vk;class Ck extends OE{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=Od(e,!1);let i=r.text;const s=r.text.slice(0,10),o=af.DateTime.fromFormat(s,Do);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Do),i=a.toFormat(Do),new Ck(r,i)}}}wr.LiteralWeek=Ck;class Sk extends OE{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,rce);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Sk(r,i)}}}wr.LiteralMonth=Sk;class bk extends OE{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=Od(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=af.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Do),i=a.toFormat(Do),new bk(r,i)}}}wr.LiteralQuarter=bk;class Tk extends OE{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,nce);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Tk(r,i)}}}wr.LiteralYear=Tk;var jT={};Object.defineProperty(jT,"__esModule",{value:!0}),jT.PartialCompare=void 0;const uce=pt;class j0t extends uce.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return uce.ATNodeType.Partial}}jT.PartialCompare=j0t;var G2={},q0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),H0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Q0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&q0t(e,t,r);return H0t(e,t),e};Object.defineProperty(G2,"__esModule",{value:!0}),G2.PickWhen=G2.Pick=void 0;const V2=Q0t(nn),ace=zt,z0t=pt,W0t=Ze;function qT(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class G0t extends z0t.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!V2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=qT(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=qT(u,f);return V2.typeEq(x,f,!0)?(o.kids.caseElse=f.value,(0,ace.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!V2.typeEq(l.when,V2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!V2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=qT(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=qT(o,u);return V2.typeEq(a,u,!0)?(r.kids.caseElse=u.value,(0,ace.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}G2.Pick=G0t;class V0t extends W0t.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}G2.PickWhen=V0t;var Y2={},Y0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),K0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),J0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Y0t(e,t,r);return K0t(e,t),e};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.CaseWhen=Y2.Case=void 0;const X0t=zt,Z0t=pt,ect=Ze,K2=J0t(nn);function lce(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class tct extends Z0t.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!K2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!K2.typeEq(a.when,K2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!K2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=lce(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!K2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=lce(u,a),i.push(a),r.kids.caseElse=a.value}return(0,X0t.computedExprValue)({value:r,dataType:u?K2.atomicDef(u):{type:"null"},from:i})}}Y2.Case=tct;class nct extends ect.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}Y2.CaseWhen=nct;var HT={},wd={},rct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ict=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rct(e,t,r);return ict(e,t),e};Object.defineProperty(wd,"__esModule",{value:!0}),wd.RecordLiteral=wd.RecordElement=void 0;const cce=Yi,oct=zt,uct=pt,act=Ze,lct=sct(nn);class cct extends act.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}wd.RecordElement=cct;class fct extends uct.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);cce.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,cce.mkFieldDef)(lct.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,oct.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}wd.RecordLiteral=fct;var xct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),dct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),hct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xct(e,t,r);return dct(e,t),e};Object.defineProperty(HT,"__esModule",{value:!0}),HT.ArrayLiteral=void 0;const pct=zt,mct=pt,fce=hct(nn),gct=wd;class yct extends mct.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof gct.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!fce.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=fce.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,pct.computedExprValue)({dataType:u,value:a,from:i})}}HT.ArrayLiteral=yct;var QT={};Object.defineProperty(QT,"__esModule",{value:!0}),QT.Timeframe=void 0;const Ect=et,Act=Ze;class _ct extends Act.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Ect.isTimestampUnit)(r)?r:"second"}}QT.Timeframe=_ct;var lf={};Object.defineProperty(lf,"__esModule",{value:!0}),lf.ImportStatement=lf.ImportSelect=lf.ImportSourceName=void 0;const Rk=Ze;class vct extends Rk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}lf.ImportSourceName=vct;class Cct extends Rk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}lf.ImportSelect=Cct;class Sct extends Rk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}lf.ImportStatement=Sct;var wE={};Object.defineProperty(wE,"__esModule",{value:!0}),wE.ExtendBlock=void 0;const bct=Ze,Tct=Wn;class Rct extends bct.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Tct.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}wE.ExtendBlock=Rct;var zT={};Object.defineProperty(zT,"__esModule",{value:!0}),zT.Argument=void 0;const Dct=Ze;class Oct extends Dct.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}zT.Argument=Oct;var WT={};Object.defineProperty(WT,"__esModule",{value:!0}),WT.HasParameter=void 0;const xce=et,wct=Ze;class Fct extends wct.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,xce.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const r=this.default.constantValue();return this.type&&this.type!==r.type&&r.type!=="null"&&r.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),r.type==="null"?this.type?{type:this.type,value:r.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:r.value,name:this.name,type:"error"}):!(0,xce.isCastType)(r.type)&&r.type!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${r.type}\``),{value:r.value,name:this.name,type:"error"}):{value:r.value,name:this.name,type:r.type}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}WT.HasParameter=Fct;var GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.AnonymousQuery=void 0;const Nct=Ze,Lct=zr;class Ict extends Nct.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Lct.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}GT.AnonymousQuery=Ict;var cf={};Object.defineProperty(cf,"__esModule",{value:!0}),cf.View=void 0;const $ct=Ze;class Bct extends $ct.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}cf.View=Bct;var VT={};Object.defineProperty(VT,"__esModule",{value:!0}),VT.ViewArrow=void 0;const kct=Gr,Mct=cf;class Pct extends Mct.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new kct.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}VT.ViewArrow=Pct;var YT={},FE={};Object.defineProperty(FE,"__esModule",{value:!0}),FE.refine=void 0;const Dk=Yi,Uct=dt,Ok=Kc;function jct(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,Dk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,Dk.isQuerySegment)(u)&&(0,Dk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,Ok.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,Ok.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(Ok.nameFromDef)}`),o.compositeFieldUsage=(0,Uct.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}FE.refine=jct,Object.defineProperty(YT,"__esModule",{value:!0}),YT.ViewRefine=void 0;const qct=yi,Hct=Gs,Qct=FE,zct=cf;class Wct extends zct.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Hct.getFinalStruct)(this.refinement,e.structDef(),s):qct.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Qct.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}YT.ViewRefine=Wct;var KT={};Object.defineProperty(KT,"__esModule",{value:!0}),KT.ReferenceView=void 0;const wk=et,dce=yi,Gct=Gs,Vct=Wr,Yct=FE,Kct=cf;class Jct extends Kct.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:dce.ErrorFactory.structDef,outputStruct:dce.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof Vct.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,wk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,wk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,wk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,Gct.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,Yct.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}KT.ReferenceView=Jct;var JT={},NE={},XT={},LE={};Object.defineProperty(LE,"__esModule",{value:!0}),LE.Index=void 0;const Xct=Ze,Zct=Wn;class eft extends Xct.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=Zct.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}LE.Index=eft;var IE={};Object.defineProperty(IE,"__esModule",{value:!0}),IE.SampleProperty=void 0;const tft=Ze,hce=Wn;class nft extends tft.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=hce.LegalRefinementStage.Tail,this.forceQueryClass=hce.QueryClass.Index}sampling(){return this.sample}}IE.SampleProperty=nft;var ZT={};Object.defineProperty(ZT,"__esModule",{value:!0}),ZT.IndexFieldSpace=void 0;const pce=dt,mce=et,Fk=_t,rft=Wr,ift=Du,sft=xE,oft=Gr;class uft extends ift.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof Fk.FieldReference?super.pushFields(r):r instanceof Fk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,pce.emptyCompositeFieldUsage)(),i=(0,pce.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof rft.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof sft.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof oft.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=Fk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();mce.TD.isLeafAtomic(f)&&(0,mce.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}ZT.IndexFieldSpace=uft,Object.defineProperty(XT,"__esModule",{value:!0}),XT.IndexBuilder=void 0;const Nk=et,aft=yi,lft=Ha,cft=LE,fft=sf,xft=IE,dft=ZT,Lk=dt;class hft{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new dft.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof lft.Filter?e.queryExecute(this):e instanceof fft.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof cft.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof xft.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,Nk.isIndexSegment)(e)&&!(0,Nk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),aft.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,Nk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,Lk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,Lk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}XT.IndexBuilder=hft;var eR={},$E={};Object.defineProperty($E,"__esModule",{value:!0}),$E.GroupBy=void 0;const pft=Ws,gce=Wn;class mft extends pft.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=gce.LegalRefinementStage.Single,this.forceQueryClass=gce.QueryClass.Grouping}}$E.GroupBy=mft;var tR={};Object.defineProperty(tR,"__esModule",{value:!0}),tR.ProjectFieldSpace=void 0;const nR=et,gft=Du;class yft extends gft.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!nR.TD.isAtomic(e)||(0,nR.expressionIsAggregate)(e.expressionType)?!1:(0,nR.expressionInvolvesAggregate)(e.expressionType)&&(0,nR.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}tR.ProjectFieldSpace=yft;var ff={},Fd={};Object.defineProperty(Fd,"__esModule",{value:!0}),Fd.Ordering=Fd.OrderBy=void 0;const Eft=et,yce=of,Ece=Ze,Aft=Wn;class _ft extends Ece.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof yce.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof yce.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Eft.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}Fd.OrderBy=_ft;class vft extends Ece.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Aft.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}Fd.Ordering=vft,Object.defineProperty(ff,"__esModule",{value:!0}),ff.ReduceBuilder=ff.QuerySegmentBuilder=void 0;const Ou=et,Cft=yi,Sft=of,bft=sf,Tft=Fd,Rft=Du,Dft=Ws,Ik=dt;function Ace(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class _ce{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Dft.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof bft.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Tft.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,Ou.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,Ik.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,Ik.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}ff.QuerySegmentBuilder=_ce;class Oft extends _ce{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Rft.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,Ou.isReduceSegment)(e)||(0,Ou.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),Cft.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=Ace(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=Ace(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Sft.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,Ou.expressionIsAggregate)(h.expressionType),a=(0,Ou.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAggregate)(o.expressionType),a=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAnalytic)(o.expressionType);if((0,Ou.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,Ou.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}ff.ReduceBuilder=Oft,Object.defineProperty(eR,"__esModule",{value:!0}),eR.ProjectBuilder=void 0;const vce=et,wft=yi,Fft=$E,Nft=tR,Lft=ff;class Ift extends Lft.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Nft.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Fft.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,vce.isProjectSegment)(e)||(0,vce.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),wft.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}eR.ProjectBuilder=Ift;var rR={};Object.defineProperty(rR,"__esModule",{value:!0}),rR.PartialBuilder=void 0;const $ft=Yi,Bft=ff;class kft extends Bft.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,$ft.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}rR.PartialBuilder=kft,Object.defineProperty(NE,"__esModule",{value:!0}),NE.QOpDesc=void 0;const Mft=XT,Pft=eR,Uft=ff,jft=Ze,qft=Gs,Hft=Gr,Nd=Wn,Qft=rR;class zft extends jft.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=Nd.QueryClass.Grouping:this.refineThis.type==="project"?r=Nd.QueryClass.Project:this.refineThis.type==="index"&&(r=Nd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=Nd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case Nd.QueryClass.Grouping:return new Uft.ReduceBuilder(e,this.refineThis,r,i);case Nd.QueryClass.Project:return new Pft.ProjectBuilder(e,this.refineThis,r,i);case Nd.QueryClass.Index:return new Mft.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Qft.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Hft.StaticSourceSpace((0,qft.opOutputStruct)(this,e.structDef(),s))}}}NE.QOpDesc=zft,Object.defineProperty(JT,"__esModule",{value:!0}),JT.QOpDescView=void 0;const Wft=et,Gft=Gr,Cce=NE,Vft=Gs,$k=Wn,Yft=cf;class Kft extends Yft.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,Wft.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new Cce.QOpDesc([]),u=new Cce.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case $k.LegalRefinementStage.Head:o.push(a);break;case $k.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case $k.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,Vft.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new Gft.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}JT.QOpDescView=Kft;var Nn={},Jft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jft(e,t,r);return Xft(e,t),e};Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.FieldDefinitionValue=Nn.DefSpace=Nn.DimensionFieldDeclaration=Nn.MeasureFieldDeclaration=Nn.DeclareFieldDeclaration=Nn.ProjectFieldDeclaration=Nn.GroupByFieldDeclaration=Nn.AggregateFieldDeclaration=Nn.CalculateFieldDeclaration=Nn.AtomicFieldDeclaration=void 0;const Bk=et,Sce=Zft(nn),ext=U2,txt=Ze,Ld=lr,nxt=zr,rxt=Wr;class xf extends txt.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=nxt.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new kk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,Bk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,Bk.mkFieldDef)(Sce.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,ext.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof kk&&e.foundCircle)&&i.type!=="error"){const u=Sce.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new bce(e,this))}}Nn.AtomicFieldDeclaration=xf;class ixt extends xf{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Nn.CalculateFieldDeclaration=ixt;class sxt extends xf{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckAggregate)(e,this)}}Nn.AggregateFieldDeclaration=sxt;class oxt extends xf{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckGroupBy)(e,this)}}Nn.GroupByFieldDeclaration=oxt;class uxt extends xf{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckProject)(e,this)}}Nn.ProjectFieldDeclaration=uxt;class axt extends xf{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckDeclare)(e,this)}}Nn.DeclareFieldDeclaration=axt;class lxt extends xf{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckMeasure)(e,this)}}Nn.MeasureFieldDeclaration=lxt;class cxt extends xf{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckDimension)(e,this)}}Nn.DimensionFieldDeclaration=cxt;class kk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Nn.DefSpace=kk;class bce extends rxt.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,Bk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}entryType(){return(this.defInQuery||this.fieldDef()).type}}Nn.FieldDefinitionValue=bce;var iR={};Object.defineProperty(iR,"__esModule",{value:!0}),iR.Aggregate=void 0;const fxt=Ws,Tce=Wn;class xxt extends fxt.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=Tce.LegalRefinementStage.Single,this.forceQueryClass=Tce.QueryClass.Grouping}}iR.Aggregate=xxt;var sR={};Object.defineProperty(sR,"__esModule",{value:!0}),sR.Calculate=void 0;const dxt=Ws,hxt=Wn;class pxt extends dxt.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=hxt.LegalRefinementStage.Single}}sR.Calculate=pxt;var BE={};Object.defineProperty(BE,"__esModule",{value:!0}),BE.Dimensions=void 0;const mxt=Jc;class gxt extends mxt.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}BE.Dimensions=gxt;var kE={};Object.defineProperty(kE,"__esModule",{value:!0}),kE.Measures=void 0;const yxt=Jc;class Ext extends yxt.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}kE.Measures=Ext;var oR={};Object.defineProperty(oR,"__esModule",{value:!0}),oR.Nests=void 0;const Axt=Ws,Rce=Wn;class _xt extends Axt.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=Rce.LegalRefinementStage.Single,this.forceQueryClass=Rce.QueryClass.Grouping}}oR.Nests=_xt;var uR={};Object.defineProperty(uR,"__esModule",{value:!0}),uR.ProjectStatement=void 0;const vxt=Ws,Dce=Wn;class Cxt extends vxt.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=Dce.QueryClass.Project,this.queryRefinementStage=Dce.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}uR.ProjectStatement=Cxt;var df={},_0={},Un={};Object.defineProperty(Un,"__esModule",{value:!0}),Un.getPlainString=Un.unIndent=Un.getOptionalId=Un.idToStr=Un.getId=Un.getStringParts=Un.getStringIfShort=Un.getShortString=void 0;const Oce=$o;function wce(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?Oce.ParseUtil.parseString(i,i[0]):""}Un.getShortString=wce;function Fce(t){const e=t.string().shortString();if(e)return wce(e)}Un.getStringIfShort=Fce;function*Nce(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Un.getStringParts=Nce;function Lce(t){return Ice(t.id())}Un.getId=Lce;function Ice(t){const e=t.BQ_STRING();return e?Oce.ParseUtil.parseString(e.text,"`"):t.text}Un.idToStr=Ice;function Sxt(t){function e(r){return"id"in r}if(e(t)&&t.id())return Lce(t)}Un.getOptionalId=Sxt;function*$ce(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function bxt(t){let e;for(const r of $ce(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function Bce(t){let e;for(const r of t)if(typeof r=="string"){const i=bxt(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of $ce(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Un.unIndent=Bce;function Txt(t,e=!1){const r=[],i=Fce(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of Nce(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return Bce(s),[s.join(""),r]}return["",r]}Un.getPlainString=Txt,Object.defineProperty(_0,"__esModule",{value:!0}),_0.findReferences=_0.deprecatedParseTableURI=_0.constructTableKey=void 0;const Rxt=R0,Mk=Un;function Pk(t){const e=(0,Mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class Dxt{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=kce(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterTableMethod(e){const r=(0,Mk.getId)(e.connectionId()),i=Pk(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterTableFunction(e){const r=Pk(e.tableURI()),{connectionName:i,tablePath:s}=Mce(r),o=this.trans.rangeFromContext(e);this.registerTableReference(i,s,o)}enterImportURL(e){const r=Pk(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function kce(t,e){return t===void 0?e:`${t}:${e}`}_0.constructTableKey=kce;function Mce(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}_0.deprecatedParseTableURI=Mce;function Oxt(t,e,r){const i=new Dxt(t,e),s=i;return Rxt.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}_0.findReferences=Oxt,Object.defineProperty(df,"__esModule",{value:!0}),df.TableFunctionSource=df.TableMethodSource=df.TableSource=void 0;const Pce=_0,wxt=Ro,Uce=yi;class Uk extends wxt.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return Uce.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,Pce.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),Uce.ErrorFactory.structDef}}df.TableSource=Uk;class Fxt extends Uk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}df.TableMethodSource=Fxt;class Nxt extends Uk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,Pce.deprecatedParseTableURI)(this.tableURI)}}df.TableFunctionSource=Nxt;var aR={};Object.defineProperty(aR,"__esModule",{value:!0}),aR.SQLString=void 0;const Lxt=Ze,jce=Tu;class Ixt extends Lxt.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter($xt)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof jce.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}aR.SQLString=Ixt;function $xt(t){return t instanceof jce.SourceQueryElement}var lR={};Object.defineProperty(lR,"__esModule",{value:!0}),lR.SourceDesc=void 0;const Bxt=Ze;class kxt extends Bxt.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}lR.SourceDesc=kxt;var cR={};Object.defineProperty(cR,"__esModule",{value:!0}),cR.isSourceProperty=void 0;const Mxt=Ha,Pxt=Jc,Uxt=L2,jxt=Zc,qxt=I2,Hxt=$2,Qxt=B2,zxt=Xc,Wxt=As;function Gxt(t){return t instanceof Mxt.Filter||t instanceof Wxt.JoinStatement||t instanceof Pxt.DeclareFields||t instanceof Uxt.FieldListEdit||t instanceof jxt.Renames||t instanceof qxt.PrimaryKey||t instanceof zxt.ObjectAnnotation||t instanceof Hxt.Views||t instanceof Qxt.TimezoneStatement}cR.isSourceProperty=Gxt;var fR={};Object.defineProperty(fR,"__esModule",{value:!0}),fR.isFieldCollectionMember=void 0;const Vxt=Nn,qce=_t;function Yxt(t){return t instanceof qce.FieldReference||t instanceof qce.WildcardFieldReference||t instanceof Vxt.AtomicFieldDeclaration}fR.isFieldCollectionMember=Yxt;var xR={};Object.defineProperty(xR,"__esModule",{value:!0}),xR.isQueryElement=void 0;const Kxt=k2,Jxt=M2,Xxt=EE,Zxt=AE;function edt(t){return t instanceof Kxt.QueryArrow||t instanceof Jxt.QueryRefine||t instanceof Xxt.QueryReference||t instanceof Zxt.QueryRaw}xR.isQueryElement=edt;var Hce={};Object.defineProperty(Hce,"__esModule",{value:!0});var dR={};Object.defineProperty(dR,"__esModule",{value:!0}),dR.isQueryProperty=void 0;function tdt(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}dR.isQueryProperty=tdt;var hR={};Object.defineProperty(hR,"__esModule",{value:!0}),hR.isQueryExtendProperty=void 0;const ndt=BE,rdt=As,idt=kE;function sdt(t){return t instanceof ndt.Dimensions||t instanceof idt.Measures||t instanceof rdt.JoinStatement}hR.isQueryExtendProperty=sdt;var pR={};Object.defineProperty(pR,"__esModule",{value:!0}),pR.isFieldPropStatement=void 0;const odt=rf,udt=Ha,adt=sf,ldt=z2;function cdt(t){return t instanceof udt.Filter||t instanceof adt.Limit||t instanceof ldt.PartitionBy||t instanceof odt.FunctionOrdering}pR.isFieldPropStatement=cdt,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(iE,t),r(D2,t),r(O2,t),r(Ro,t),r(uE,t),r(Tu,t),r(Y4,t),r(K4,t),r(Z4,t),r(hE,t),r(eT,t),r(tT,t),r(bu,t),r(L2,t),r(I2,t),r(Zc,t),r($2,t),r(B2,t),r(rT,t),r(q2,t),r(sT,t),r(rf,t),r(oT,t),r(E0,t),r(uT,t),r(Q2,t),r(aT,t),r(lT,t),r(cT,t),r(y0,t),r(fT,t),r(xT,t),r(hT,t),r(TE,t),r(SE,t),r(Rd,t),r(mT,t),r(gT,t),r(ET,t),r(_T,t),r(vT,t),r(CT,t),r(ST,t),r(uf,t),r(TT,t),r(RT,t),r(DT,t),r(wT,t),r(FT,t),r(NT,t),r(LT,t),r($T,t),r(MT,t),r(wr,t),r(jT,t),r(z2,t),r(G2,t),r(Y2,t),r(HT,t),r(wd,t),r(nf,t),r(QT,t),r(RE,t),r(lf,t),r(wE,t),r(zT,t),r(WT,t),r(GT,t),r(M2,t),r(k2,t),r(cf,t),r(VT,t),r(YT,t),r(KT,t),r(JT,t),r(Nn,t),r(_t,t),r(iR,t),r(sR,t),r(Jc,t),r(BE,t),r(wE,t),r(Ha,t),r($E,t),r(LE,t),r(As,t),r(sE,t),r(sf,t),r(kE,t),r(iE,t),r(oR,t),r(Fd,t),r(uR,t),r(NE,t),r(IE,t),r(P2,t),r(Td,t),r(_E,t),r(df,t),r(aR,t),r(Xc,t),r(Ru,t),r(lR,t),r(cR,t),r(pt,t),r(fR,t),r(of,t),r(Ze,t),r(xR,t),r(Hce,t),r(dR,t),r(hR,t),r(pR,t)}(q4);var mR={},J2={};Object.defineProperty(J2,"__esModule",{value:!0}),J2.ConstantExpression=J2.ConstantFieldSpace=void 0;const fdt=pt;class Qce{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}J2.ConstantFieldSpace=Qce;class xdt extends fdt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new Qce),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}J2.ConstantExpression=xdt;var ddt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),hdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),pdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ddt(e,t,r);return hdt(e,t),e};Object.defineProperty(mR,"__esModule",{value:!0}),mR.MalloyToAST=void 0;const zce=tg,mdt=Hd,ue=pdt(q4),jk=b2,Wce=xr,gdt=q4,Xn=Un,qk=et,ydt=$o,Edt=J2,Gce=Jn;class Vce extends ue.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Hk extends ue.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Adt=["##! m4warnings=error"];class _dt extends mdt.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Adt){const o=ydt.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,Gce.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new Wce.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r,i){const s=this.m4Severity();s&&this.contextError(e,r,i,{severity:s})}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Hk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new ue.FieldName((0,Xn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ue.ModelEntryReference((0,Xn.getId)(e)),e.id())}defaultResult(){return new ue.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new Wce.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ue.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof ue.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Xn.getPlainString)(e);for(const s of i)s instanceof zce.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of e.sqlInterpolation())i.CLOSE_CODE()&&this.m4advisory(i,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const i of(0,Xn.getStringParts)(e))i instanceof zce.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new ue.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>ue.isDocStatementOrDocStatementList(i)&&i,"statement");return new ue.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ue.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=e.fieldExpr(),i=r?this.astAt(new Edt.ConstantExpression(this.getFieldExpr(r)),r):void 0,s=e.malloyType(),o=s?this.getMalloyType(s):void 0;return this.astAt(new ue.HasParameter({name:(0,Xn.getId)(e.parameterNameDef()),type:o,default:i}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(r=>this.getSourceParameter(r)))}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ue.DefineSource((0,Xn.getId)(e.sourceNameDef()),r instanceof ue.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>ue.isSourceProperty(s)&&s,"source property");return new ue.SourceDesc(r)}visitTableFunction(e){const r=this.getPlainStringFrom(e.tableURI()),i=this.astAt(new ue.TableFunctionSource(r),e);return this.m4advisory(e,"table-function","`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),i}visitTableMethod(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ue.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ue.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Xn.getShortString)(u));const a=new ue.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof ue.Join&&(i.push(u),u instanceof ue.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ue.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ue.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ue.Join&&(s.push(u),u instanceof ue.ExpressionJoin&&(u.joinType="one"));const o=new ue.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ue.Join&&(s.push(u),u instanceof ue.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ue.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof ue.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new ue.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ue.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new ue.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,qk.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new ue.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Xn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.DimensionFieldDeclaration),s=new ue.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.MeasureFieldDeclaration),s=new ue.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(ue.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ue.ExtendBlock(r);return this.astAt(s,e)}visitDeclareStatement(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.DeclareFieldDeclaration),s=new ue.DeclareFields(i,r),o=this.astAt(s,e);return this.m4advisory(e,"declare","`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),o}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ue.RenameField((0,Xn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new ue.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ue.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new ue.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),e.QUERY()&&this.m4advisory(e,"query-in-source","Use view: inside of a source instead of query:"),s}visitDefExplorePrimaryKey(e){const r=new ue.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new ue.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ue.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ue.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ue.SQExtend(r,new ue.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new ue.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>ue.isQueryProperty(i)&&i,"query statement");return new ue.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof ue.FieldReference||s instanceof ue.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ue.Aggregate(this.getQueryItems(e.queryFieldList(),ue.AggregateFieldDeclaration,ue.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ue.GroupBy(this.getQueryItems(e.queryFieldList(),ue.GroupByFieldDeclaration,ue.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ue.Calculate(this.getQueryItems(e.queryFieldList(),ue.CalculateFieldDeclaration,ue.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),ue.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ue.ExprGranularTime(new ue.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ue.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,ue.ProjectFieldDeclaration,ue.ProjectFieldReference));return this.astAt(new ue.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","project: keyword is deprecated, use select:");const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,ue.ProjectFieldReference):void 0,o=this.astAt(new ue.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Xn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new ue.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ue.IndexFieldReference);return i.STAR()?this.astAt(new ue.WildcardFieldReference(o),e):this.astAt(o,e)});return new ue.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ue.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new ue.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new ue.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new ue.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ue.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ue.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new ue.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ue.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ue.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Xn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof ue.SourceQueryElement){const o=new ue.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitAnonymousQuery(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ue.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.m4advisory(r,"anonymous-query","Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(s,e)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ue.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new ue.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ue.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Xn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new ue.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Xn.getId)(e.exploreQueryNameDef()),i=new ue.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new ue.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ue.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ue.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ue.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ue.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ue.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ue.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ue.isComparison(r))return this.astAt(new ue.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new ue.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new ue.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1555
+ `)),vE.ErrorFactory.structDef}else if(o.status==="present"){const u=this.select.location,a={...o.value,fields:o.value.fields.map(f=>({...f,location:u})),location:this.location},l=this.document(),c=l==null?void 0:l.currentModelAnnotation();return c&&(a.modelAnnotation=c),a}else return this.logError("non-top-level-sql-source","`connection_name.sql(...)` can currently only be used in top level source/query definitions"),vE.ErrorFactory.structDef}}_E.SQLSource=jot,Object.defineProperty(Z4,"__esModule",{value:!0}),Z4.SQSource=void 0;const qot=Tu,Hot=AE,Qot=_E;class zot extends qot.SourceQueryElement{constructor(e){super({theSource:e}),this.theSource=e,this.elementType="sq-source"}isSource(){return!0}getSource(){return this.theSource}getQuery(){if(this.theSource instanceof Qot.SQLSource){const e=new Hot.QueryRaw(this.theSource);return this.has({rawQuery:e}),e}else this.sqLog("invalid-source-as-query","This source cannot be used as a query")}}Z4.SQSource=zot;var eT={};Object.defineProperty(eT,"__esModule",{value:!0}),eT.SQExtend=void 0;const Wot=uE,Got=Tu;class Vot extends Got.SourceQueryElement{constructor(e,r,i){super({sqSrc:e,extend:r}),this.sqSrc=e,this.extend=r,this.includeList=i,this.elementType="sq-extend"}getSource(){if(this.asSource)return this.asSource;const e=this.sqSrc.getSource();if(e)return this.asSource=new Wot.RefinedSource(e,this.extend,this.includeList),this.has({asSource:this.asSource}),this.asSource;this.sqLog("failed-to-compute-source-to-extend","Could not compute source to extend")}isSource(){return!0}}eT.SQExtend=Vot;var tT={},nT={};Object.defineProperty(nT,"__esModule",{value:!0}),nT.CompositeSource=void 0;const Yot=et,Kot=Ro;class Jot extends Kot.Source{constructor(e){super({sources:e}),this.sources=e,this.elementType="compositeSource"}getSourceDef(e){return this.withParameters(e,[])}withParameters(e,r){const i=this.sources.map(c=>c.withParameters(e,r)),s=i[0].connection,o=i[0].dialect,u="composite_source",a=[],l=new Map;return this.sources.forEach((c,f)=>{var x;const h=i[f];h.connection!==s&&c.logError("composite-source-connection-mismatch",`All sources in a composite source must share the same connection; connection \`${h.connection}\` differs from previous connection \`${s}\``);for(const p of h.fields){if(!(0,Yot.isAtomic)(p)){c.logWarning("composite-source-atomic-fields-only",`Only atomic fields are supported in composite sources; field \`${p.name}\` is not atomic and will be ignored`);continue}if(p.accessModifier==="private")continue;const m=(x=p.as)!==null&&x!==void 0?x:p.name,y=l.get(m);if(y===void 0){const g={...p,name:m,as:void 0,e:{node:"compositeField"},compositeFieldUsage:{fields:[m],joinedUsage:{}},code:this.code,location:this.codeLocation};l.set(m,g),a.push(g)}else p.accessModifier==="internal"&&(y.accessModifier="internal")}}),{type:"composite",sources:i,connection:s,fields:a,dialect:o,name:u,parameters:i[0].parameters}}}nT.CompositeSource=Jot,Object.defineProperty(tT,"__esModule",{value:!0}),tT.SQCompose=void 0;const Xot=nT,Zot=Tu;class eut extends Zot.SourceQueryElement{constructor(e){super({sources:e}),this.sources=e,this.elementType="sq-compose"}getSource(){if(this.asSource)return this.asSource;const e=this.sources.map(r=>r.getSource());if(e.length===0){this.sqLog("empty-composite-source","Composite source must have at least one input source");return}else e.length===1&&this.sqLog("unnecessary-composite-source","A composite source with one input is equivalent to that input",{severity:"warn"});if(tut(e))return this.asSource=new Xot.CompositeSource(e),this.has({asSource:this.asSource}),this.asSource;this.sqLog("invalid-composite-source-input","All composite source inputs must be valid sources")}isSource(){return!0}}tT.SQCompose=eut;function tut(t){return t.every(e=>e!==void 0)}var rT={},y0={},CE={},nut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),rut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),iut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&nut(e,t,r);return rut(e,t),e};Object.defineProperty(CE,"__esModule",{value:!0}),CE.BinaryBoolean=void 0;const sut=zs,out=iut(nn),uut=Ru,aut=zt,lut=pt;class cut extends lut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="abstract boolean binary",this.legalChildTypes=[out.boolT]}getExpression(e){const r=this.left.getExpression(e),i=this.right.getExpression(e);return this.typeCheck(this.left,r)&&this.typeCheck(this.right,i)?(0,aut.computedExprValue)({dataType:{type:"boolean"},value:{node:(0,uut.getExprNode)(this.op),kids:{left:r.value,right:i.value}},from:[r,i]}):(0,sut.errorFor)("logical-op expected boolean")}}CE.BinaryBoolean=cut;var fut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&fut(e,t,r);return xut(e,t),e};Object.defineProperty(y0,"__esModule",{value:!0}),y0.ExprLegacyIn=y0.ExprEquality=y0.ExprCompare=void 0;const hn=dut(nn),hut=zt,put=pt,mut=CE,gut={"~":[hn.stringT],"!~":[hn.stringT],"<":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"<=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],"!=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">=":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT],">":[hn.numberT,hn.stringT,hn.dateT,hn.timestampT]};class F0e extends mut.BinaryBoolean{constructor(e,r,i){super(e,r,i),this.elementType="a<=>b",this.legalChildTypes=gut[r]}getExpression(e){return this.right.apply(e,this.op,this.left)}}y0.ExprCompare=F0e;class yut extends F0e{constructor(e,r,i){super(e,r,i),this.elementType="a~=b"}getExpression(e){return this.right.apply(e,this.op,this.left,!0)}apply(e,r,i){return super.apply(e,r,i,!0)}}y0.ExprEquality=yut;class Eut extends put.ExpressionDef{constructor(e,r,i){super(),this.expr=e,this.notIn=r,this.choices=i,this.elementType="in",this.has({expr:e,choices:i})}getExpression(e){const r=this.expr.getExpression(e),i=this.choices.map(s=>s.getExpression(e));return(0,hut.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:this.notIn,kids:{e:r.value,oneOf:i.map(s=>s.value)}},from:[r,...i]})}}y0.ExprLegacyIn=Eut;var SE={},j2={};Object.defineProperty(j2,"__esModule",{value:!0}),j2.ExprTime=void 0;const Aut=et,_ut=zt,vut=pt;class sk extends vut.ExpressionDef{constructor(e,r,i){super(),this.elementType="timestampOrDate",this.elementType=e,this.translationValue=(0,_ut.computedExprValue)({dataType:{type:e},value:r,from:i??[]})}getExpression(e){return this.translationValue}static fromValue(e,r){let i=r.value;if(e!==r.type){const s={node:"cast",safe:!1,dstType:{type:e},e:r.value};(0,Aut.isTemporalType)(r.type)&&(s.srcType={type:r.type}),i=s}return new sk(e,i,[r])}}j2.ExprTime=sk;var nf={};Object.defineProperty(nf,"__esModule",{value:!0}),nf.Range=void 0;const Cut=zs,Sut=zt,but=pt;class Tut extends but.ExpressionDef{constructor(e,r){super({first:e,last:r}),this.first=e,this.last=r,this.elementType="range"}apply(e,r,i){switch(r){case"=":case"!=":{const s=r==="="?">=":"<",o=r==="="?"and":"or",u=r==="="?"<":">=",a=this.first.apply(e,s,i),l=this.last.apply(e,u,i);return(0,Sut.computedExprValue)({dataType:{type:"boolean"},value:{node:o,kids:{left:a.value,right:l.value}},from:[a,l]})}case">":return this.last.apply(e,">=",i);case">=":return this.first.apply(e,">=",i);case"<":return this.first.apply(e,"<",i);case"<=":return this.last.apply(e,"<",i)}throw new Error("mysterious error in range computation")}requestExpression(e){}getExpression(e){return this.logError("range-as-value","A Range is not a value"),(0,Cut.errorFor)("a range is not a value")}}nf.Range=Tut;var Rut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Dut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Out=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Rut(e,t,r);return Dut(e,t),e};Object.defineProperty(SE,"__esModule",{value:!0}),SE.ExprGranularTime=void 0;const ok=et,wut=zs,N0e=Out(nn),L0e=_s,Fut=pt,iT=j2,I0e=nf;class Nut extends Fut.ExpressionDef{constructor(e,r,i){super({expr:e}),this.expr=e,this.units=r,this.truncate=i,this.elementType="granularTime",this.legalChildTypes=[N0e.timestampT,N0e.dateT]}granular(){return!0}getExpression(e){const r=this.units,i=this.expr.getExpression(e);if(ok.TD.isTemporal(i)){const o={...i,timeframe:r};return this.truncate&&(o.value={node:"trunc",e:(0,ok.mkTemporal)(i.value,i.type),units:r}),o}i.type!=="error"&&this.logError("unsupported-type-for-time-truncation",`Cannot do time truncation on type '${i.type}'`);const s={...i};return i.type==="error"&&(s.type=(0,ok.isDateUnit)(r)?"date":"timestamp"),{...s,value:(0,wut.errorFor)("granularity typecheck").value,evalSpace:"constant"}}toRange(e){const r=this.getExpression(e),i={node:"numberLiteral",literal:"1"};if(r.type==="timestamp"){const a=iT.ExprTime.fromValue("timestamp",r),l=new iT.ExprTime("timestamp",(0,L0e.timeOffset)("timestamp",r.value,"+",i,this.units),[r]);return new I0e.Range(a,l)}const s=new iT.ExprTime("date",r.value,[r]),o=(0,L0e.timeOffset)("date",r.value,"+",i,this.units),u=new iT.ExprTime("date",o,[r]);return new I0e.Range(s,u)}}SE.ExprGranularTime=Nut,Object.defineProperty(rT,"__esModule",{value:!0}),rT.Apply=void 0;const Lut=y0,Iut=U2,$0e=SE;class $ut extends Lut.ExprCompare{constructor(e,r){super(e,"=",r),this.left=e,this.right=r,this.elementType="apply"}getExpression(e){let r=this.right;if(!this.right.granular()){const i=this.right.requestExpression(e);i&&(0,Iut.isGranularResult)(i)&&(r=new $0e.ExprGranularTime(this.right,i.timeframe,!1))}return r instanceof $0e.ExprGranularTime?r.toRange(e).apply(e,this.op,this.left):super.getExpression(e)}}rT.Apply=$ut;var q2={},But=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),kut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&But(e,t,r);return kut(e,t),e};Object.defineProperty(q2,"__esModule",{value:!0}),q2.BinaryNumeric=void 0;const Put=Mut(nn),Uut=pt;class jut extends Uut.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="numeric binary abstract",this.legalChildTypes=[Put.numberT]}getExpression(e){return this.right.apply(e,this.op,this.left)}}q2.BinaryNumeric=jut;var sT={},qut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Hut=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Qut=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&qut(e,t,r);return Hut(e,t),e};Object.defineProperty(sT,"__esModule",{value:!0}),sT.Boolean=void 0;const zut=pt,Wut=Qut(nn);let Gut=class extends zut.ExpressionDef{constructor(e){super(),this.value=e,this.elementType="boolean literal"}getExpression(){return{...Wut.boolT,value:{node:this.value}}}};sT.Boolean=Gut;var rf={};Object.defineProperty(rf,"__esModule",{value:!0}),rf.FunctionOrdering=rf.FunctionOrderBy=void 0;const uk=et,B0e=Ze,Vut=Rd;class Yut extends B0e.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e&&this.has({field:e})}getAnalyticOrderBy(e){if(!this.field)return this.logError("analytic-order-by-missing-field","analytic `order_by` must specify an aggregate expression or output field reference"),{node:"functionOrderBy",e:{node:"error"},dir:this.dir};const r=this.field.getExpression(e);return(0,uk.expressionIsAggregate)(r.expressionType)||((0,uk.expressionIsScalar)(r.expressionType)?(!(this.field instanceof Vut.ExprIdReference)||r.evalSpace==="input")&&this.field.logError("analytic-order-by-not-output","analytic `order_by` must be an aggregate or an output field reference"):this.field.logError("analytic-order-by-not-aggregate-or-output","analytic `order_by` must be scalar or aggregate")),{node:"functionOrderBy",e:r.value,dir:this.dir}}getAggregateOrderBy(e,r){if(this.field){const i=this.field.getExpression(e);return(0,uk.expressionIsScalar)(i.expressionType)||this.field.logError("aggregate-order-by-not-scalar","aggregate `order_by` must be scalar"),r||this.field.logError("aggregate-order-by-expression-not-allowed","`order_by` must be only `asc` or `desc` with no expression"),{node:"functionOrderBy",e:i.value,dir:this.dir}}else return this.dir===void 0?(this.logError("aggregate-order-by-without-field-or-direction","field or order direction must be specified"),{node:"functionDefaultOrderBy",dir:"asc"}):{node:"functionDefaultOrderBy",dir:this.dir}}}rf.FunctionOrderBy=Yut;class Kut extends B0e.ListOf{constructor(e){super(e),this.elementType="function-ordering"}getAnalyticOrderBy(e){return this.list.map(r=>r.getAnalyticOrderBy(e))}getAggregateOrderBy(e,r){return this.list.map(i=>i.getAggregateOrderBy(e,r))}}rf.FunctionOrdering=Kut;var oT={};Object.defineProperty(oT,"__esModule",{value:!0}),oT.ExprAddSub=void 0;const Jut=q2;class Xut extends Jut.BinaryNumeric{constructor(){super(...arguments),this.elementType="+-"}}oT.ExprAddSub=Xut;var E0={},Zut=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),eat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),tat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Zut(e,t,r);return eat(e,t),e};Object.defineProperty(E0,"__esModule",{value:!0}),E0.ExprAggregateFunction=void 0;const bE=et,nat=kt,rat=zs,k0e=Gr,M0e=tat(nn),iat=_t,sat=pt,oat=Wr,uat=Rd;class aat extends sat.ExpressionDef{constructor(e,r,i){super(),this.func=e,this.legalChildTypes=[M0e.numberT],this.elementType=e,this.explicitSource=i,r&&(this.expr=r,this.has({expr:r}))}getExpression(e){var r,i,s;const o=e.isQueryFieldSpace()?e.inputSpace():e;let u=this.expr,a=(r=this.expr)===null||r===void 0?void 0:r.getExpression(o),l=(i=this.source)===null||i===void 0?void 0:i.path,c=[];if(this.source){const x=this.source.getField(o);if(x.found){c=x.joinPath;const h=x.found,p=h.typeDesc();if(!(h instanceof k0e.StructSpaceField))if((0,bE.isAtomicFieldType)(p.type)){u=this.source,a={...M0e.atomicDef(p),expressionType:p.expressionType,value:p.evalSpace==="output"?{node:"outputField",name:this.source.refString}:{node:"field",path:this.source.path},evalSpace:p.evalSpace,compositeFieldUsage:p.compositeFieldUsage},l=this.source.path.slice(0,-1);const m=this.getJoinUsage(o);(m.length===1||m.length>1&&m.slice(1).every(g=>lat(g,m[0])))&&(l=m[0].map(g=>g.name),c=m[0])}else return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${p.type}`)}else return this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}if(a===void 0)return this.loggedErrorExpr("missing-aggregate-expression","Missing expression for aggregate function");if((0,bE.expressionIsAggregate)(a.expressionType))return this.loggedErrorExpr("aggregate-of-aggregate","Aggregate expression cannot be aggregate");if(!(a.type==="error")){const x=this.getJoinUsage(o),h=this.source!==void 0||this.explicitSource;if(u&&!(!this.source&&x.every(m=>m.length===0))&&!this.isSymmetricFunction()){const m=lk(c,x),y=ck(this.elementType,m),g=h?y==null?void 0:y.message:"Join path is required for this calculation";if(g){const E=cat(g,x,u,this.elementType),A=(s=y==null?void 0:y.code)!==null&&s!==void 0?s:"bad-join-usage";y?this.logError(A,E):this.logWarning(A,E)}}}if(this.typeCheck(this.expr||this,{...a,expressionType:"scalar"})){const x={node:"aggregate",function:this.func,e:a.value};return l&&l.length>0&&(x.structPath=l),{...this.returns(a),expressionType:"aggregate",value:x,evalSpace:"output"}}return(0,rat.errorFor)("aggregate type check")}isSymmetricFunction(){return!0}getJoinUsage(e){const r=[];if(this.source&&this.source.getField(e).found){const s={node:"field",path:this.source.path};r.push(...ak(e,s))}if(this.expr){const i=this.expr.getExpression(e).value;r.push(...ak(e,i))}return r}}E0.ExprAggregateFunction=aat;function lat(t,e){let r=t.length;if(r!==e.length)return!1;for(;r>0;)if(r-=1,t[r].name!==e[r].name)return!1;return!0}function ak(t,e){const r=[],i=(s,o)=>{const u=o[0],a=o.slice(1),l=s.entry(u);if(l===void 0)throw new Error(`Invalid field lookup ${u}`);if(l instanceof k0e.StructSpaceField&&a.length>0){const c=i(l.fieldSpace,a);return{...c,joinPath:[{...l.joinPathElement,name:u},...c.joinPath]}}else if(l instanceof oat.SpaceField){if(a.length!==0)throw new Error(`${u} cannot contain a ${a.join(".")}`);const c=l.fieldDef();if(c)return{fs:s,def:c,joinPath:[]};throw new Error("No field def")}else throw new Error("expected a field def or struct")};for(const s of(0,nat.exprWalk)(e))if(s.node==="field"){const o=i(t,s.path),u=o.def;if((0,bE.isAtomic)(u)&&!(0,bE.isJoined)(u))if((0,bE.hasExpression)(u)){const a=ak(o.fs,u.e);r.push(...a.map(l=>[...o.joinPath,...l]))}else r.push(o.joinPath)}else if(s.node==="source-reference")if(s.path){const o=i(t,s.path);r.push(o.joinPath)}else r.push([]);return r}function lk(t,e){const r=[];for(const i of e){let s=0;for(let l=0;l<t.length&&l<i.length&&t[l].name===i[l].name;l++)s=l+1;const o=t.slice(s),u=i.slice(s),a=[...o.map(l=>({...l,reverse:!0})),...u.map(l=>({...l,reverse:!1}))];r.push(a)}return r}function ck(t,e){for(const r of e)for(const i of r){if(i.joinType==="cross")return{code:"aggregate-traverses-join-cross",message:`Cannot compute \`${t}\` across \`join_cross\` relationship \`${i.name}\``};if(i.joinElementType==="array"&&!i.reverse)return{code:"aggregate-traverses-repeated-relationship",message:`Cannot compute \`${t}\` across repeated relationship \`${i.name}\``};if(i.joinType==="many"&&!i.reverse)return{code:"aggregate-traverses-join-many",message:`Cannot compute \`${t}\` across \`join_many\` relationship \`${i.name}\``}}}function cat(t,e,r,i){if(e.length===0)return t;let s=e[0];for(const m of e.slice(1))for(let y=0;y<s.length;y++){const g=s[y],E=m[y];if(g.name!==E.name){s=s.slice(0,y);break}}const o=lk(s,e),u=ck(i,o),a=s.slice().reverse().findIndex(m=>m.joinType==="many"||m.joinType==="cross"),l=a===-1?0:s.length-a,c=s.slice(0,l),f=lk(c,e),x=ck(i,f),h=s.length>0?s.map(m=>m.name).join("."):"source",p=c.length>0?c.map(m=>m.name).join("."):"source";if(u)return"Aggregated dimensional expression contains multiple join paths; rewrite, for example `sum(first_join.field + second_join.field)` as `first_join.field.sum() + second_join.field.sum()`";{const m=r instanceof iat.FieldReference?`${r.refString}.${i}()`:r instanceof uat.ExprIdReference?`${r.fieldReference.refString}.${i}()`:`${h}.${i}(${r.code})`,y=`${p}.${i}(${r.code})`;let g=`${t}; use \`${m}\``;return x===void 0&&p!==h&&(g+=` or \`${y}\` to get a result weighted with respect to \`${p}\``),g}}var uT={};Object.defineProperty(uT,"__esModule",{value:!0}),uT.ExprAlternationTree=void 0;const P0e=zt,H2=pt,fat=Ru;function fk(t){const e=t.atExpr();switch(e.atNodeType()){case H2.ATNodeType.And:case H2.ATNodeType.Partial:return;case H2.ATNodeType.Or:{if(e instanceof U0e){const r=fk(e.left);if(r){const i=fk(e.right);if(i)return[...r,...i]}}return}default:return e.granular()?void 0:[e]}}class U0e extends H2.ExpressionDef{constructor(e,r,i){super({left:e,right:i}),this.left=e,this.op=r,this.right=i,this.elementType="alternation",this.elementType=`${r}alternation${r}`}equalityList(){return this.inList===void 0&&(this.inList=fk(this)||[]),this.inList}apply(e,r,i,s){if((0,fat.isEquality)(r)){const a=this.equalityList();if(a.length>0&&(r==="="||r==="!=")){const l=i.getExpression(e),c=a.map(f=>f.getExpression(e));return(0,P0e.computedExprValue)({dataType:{type:"boolean"},value:{node:"in",not:r==="!=",kids:{e:l.value,oneOf:c.map(f=>f.value)}},from:[l,...c]})}a.length===0&&s&&this.logWarning("or-choices-only",`Only | seperated values are legal when used with ${r} operator`)}const o=this.left.apply(e,r,i),u=this.right.apply(e,r,i);return(0,P0e.computedExprValue)({dataType:{type:"boolean"},value:{node:this.op==="&"?"and":"or",kids:{left:o.value,right:u.value}},from:[o,u]})}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("alternation-as-value","Alternation tree has no value")}atNodeType(){return this.op==="|"?H2.ATNodeType.Or:H2.ATNodeType.And}}uT.ExprAlternationTree=U0e;var Q2={};Object.defineProperty(Q2,"__esModule",{value:!0}),Q2.ExprAsymmetric=void 0;const xat=E0;class dat extends xat.ExprAggregateFunction{constructor(e,r,i,s){super(e,r,s),this.func=e,this.expr=r,this.source=i,this.has({source:i})}isSymmetricFunction(){return!1}returns(e){return e}defaultFieldName(){if(this.source&&this.expr===void 0){const e=this.source.nameString;switch(this.func){case"sum":return`total_${e}`;case"avg":return`avg_${e}`}}}}Q2.ExprAsymmetric=dat;var aT={};Object.defineProperty(aT,"__esModule",{value:!0}),aT.ExprAvg=void 0;const hat=Q2;class pat extends hat.ExprAsymmetric{constructor(e,r,i){super("avg",e,r,i),this.has({source:r})}}aT.ExprAvg=pat;var lT={};Object.defineProperty(lT,"__esModule",{value:!0}),lT.ExprCast=void 0;const mat=_s,gat=zt,yat=pt;class Eat extends yat.ExpressionDef{constructor(e,r,i=!1){super({expr:e}),this.expr=e,this.castType=r,this.safe=i,this.elementType="cast"}getExpression(e){const r=this.expr.getExpression(e);let i={type:"error"};if(typeof this.castType=="string")i={type:this.castType};else{const s=e.dialectObj();s&&(s.validateTypeName(this.castType.raw)?i=s.sqlTypeToMalloyType(this.castType.raw):this.logError("invalid-sql-native-type",`Cast type \`${this.castType.raw}\` is invalid for ${s.name} dialect`),this.safe&&!s.supportsSafeCast&&this.logError("dialect-cast-unsafe-only",`The SQL dialect '${e.dialectName()}' does not supply a safe cast operator`))}return(0,gat.computedExprValue)({dataType:i,value:(0,mat.castTo)(this.castType,r.value,r.type,this.safe),from:[r]})}}lT.ExprCast=Eat;var cT={},Aat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),_at=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),vat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Aat(e,t,r);return _at(e,t),e};Object.defineProperty(cT,"__esModule",{value:!0}),cT.ExprCoalesce=void 0;const j0e=Yi,q0e=vat(nn),Cat=pt;class Sat extends Cat.ExpressionDef{constructor(e,r){super({expr:e,altExpr:r}),this.expr=e,this.altExpr=r,this.elementType="coalesce expression",this.legalChildTypes=q0e.anyAtomicT}getExpression(e){const r=this.expr.getExpression(e),i=this.altExpr.getExpression(e);return r.type==="null"?i:(q0e.typeEq(r,i)||this.logError("mismatched-coalesce-types",`Mismatched types for coalesce (${r.type}, ${i.type})`),{...r.type==="error"?i:r,expressionType:(0,j0e.maxExpressionType)(r.expressionType,i.expressionType),value:{node:"coalesce",kids:{left:r.value,right:i.value}},evalSpace:(0,j0e.mergeEvalSpaces)(r.evalSpace,i.evalSpace)})}}cT.ExprCoalesce=Sat;var fT={};Object.defineProperty(fT,"__esModule",{value:!0}),fT.ExprCount=void 0;const bat=dt,Tat=E0;class Rat extends Tat.ExprAggregateFunction{constructor(e){super("count"),this.source=e,this.elementType="count",this.has({source:e})}defaultFieldName(){if(this.source)return"count_"+this.source.nameString}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}getExpression(e){const r={node:"aggregate",function:"count",e:{node:""}};return this.source&&(r.structPath=this.source.path),{type:"number",numberType:"integer",expressionType:"aggregate",value:r,evalSpace:"output",compositeFieldUsage:(0,bat.emptyCompositeFieldUsage)()}}}fT.ExprCount=Rat;var xT={},Dat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Oat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),wat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Dat(e,t,r);return Oat(e,t),e};Object.defineProperty(xT,"__esModule",{value:!0}),xT.ExprCountDistinct=void 0;const dT=wat(nn),Fat=E0;class Nat extends Fat.ExprAggregateFunction{constructor(e){super("distinct",e),this.legalChildTypes=[dT.numberT,dT.stringT,dT.dateT,dT.timestampT]}returns(e){return{type:"number",numberType:"integer",evalSpace:e.evalSpace,expressionType:"aggregate",value:e.value,compositeFieldUsage:e.compositeFieldUsage}}}xT.ExprCountDistinct=Nat;var hT={},sf={};Object.defineProperty(sf,"__esModule",{value:!0}),sf.Limit=void 0;const Lat=Ze,Iat=Wn;class $at extends Lat.MalloyElement{constructor(e){super(),this.limit=e,this.elementType="limit",this.queryRefinementStage=Iat.LegalRefinementStage.Tail,this.forceQueryClass=void 0}}sf.Limit=$at;var z2={};Object.defineProperty(z2,"__esModule",{value:!0}),z2.PartitionBy=void 0;const Bat=Ze;class kat extends Bat.ListOf{constructor(e){super(e),this.partitionFields=e,this.elementType="partition_by"}}z2.PartitionBy=kat;var TE={},of={};Object.defineProperty(of,"__esModule",{value:!0}),of.FieldName=void 0;const Mat=Ze;class Pat extends Mat.MalloyElement{constructor(e){super(),this.name=e,this.elementType="fieldName"}get refString(){return this.name}toString(){return this.refString}getField(e){return e.lookup([this])}}of.FieldName=Pat;var Uat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),jat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),qat=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Uat(e,t,r);return jat(e,t),e};Object.defineProperty(TE,"__esModule",{value:!0}),TE.ExprFunc=void 0;const Or=et,Hat=zs,Qat=bd,zat=zt,Wat=pt,Gat=of,H0e=kt,Q0e=qat(nn),Vat=dt;class Yat extends Wat.ExpressionDef{constructor(e,r,i,s,o){super({args:r}),this.name=e,this.args=r,this.isRaw=i,this.rawType=s,this.source=o,this.elementType="function call()",this.has({source:o})}canSupportPartitionBy(){return!0}canSupportOrderBy(){return!0}canSupportLimit(){return!0}getExpression(e){return this.getPropsExpression(e)}findFunctionDef(e){var r,i,s;const o=this.name.toLowerCase(),u=e?(i=(r=this.getDialectNamespace(e))===null||r===void 0?void 0:r.getEntry(o))===null||i===void 0?void 0:i.entry:void 0,a=u??((s=this.modelEntry(o))===null||s===void 0?void 0:s.entry);return a===void 0?(this.logError("function-not-found",`Unknown function '${this.name}'. Use '${this.name}!(...)' to call a SQL function directly.`),{found:void 0,error:"unknown function"}):a.type!=="function"?(this.logError("call-of-non-function",`'${this.name}' (with type ${a.type}) is not a function`),{found:void 0,error:"called non function"}):(a.name!==this.name&&this.logWarning("case-insensitive-function",`Case insensitivity for function names is deprecated, use '${a.name}' instead`),{found:a,error:void 0})}getPropsExpression(e,r){var i,s,o,u;const a=this.args.map(B=>B.getExpression(e));if(this.isRaw){const B=[`${this.name}(`];a.forEach((U,V)=>{V!==0&&B.push(","),B.push(U.value)}),B.push(")");const D=(i=a[0])!==null&&i!==void 0?i:{type:"number"},$=this.rawType?{type:this.rawType}:D;return(0,zat.computedExprValue)({dataType:$,value:(0,H0e.composeSQLExpr)(B),from:a})}const l=(s=e.dialectObj())===null||s===void 0?void 0:s.name,{found:c,error:f}=this.findFunctionDef(l);if(c===void 0)return(0,Hat.errorFor)(f);let x,h=(o=this.source)===null||o===void 0?void 0:o.path;if(this.source){const D=this.source.getField(e).found;if(D){const $=D.typeDesc();if((0,Or.isAtomicFieldType)($.type))x={...Q0e.atomicDef($),expressionType:$.expressionType,value:{node:"field",path:this.source.path},evalSpace:$.evalSpace,compositeFieldUsage:$.compositeFieldUsage},h=this.source.path.slice(0,-1);else if(!(D instanceof Qat.StructSpaceFieldBase))return this.loggedErrorExpr("invalid-aggregate-source",`Aggregate source cannot be a ${$.type}`)}else this.loggedErrorExpr("aggregate-source-not-found",`Reference to undefined value ${this.source.refString}`)}const p=[...x?[x]:[],...a],m=Kat(c,p);if(m===void 0)return this.loggedErrorExpr("no-matching-function-overload",`No matching overload for function ${this.name}(${p.map(B=>B.type).join(", ")})`);const{overload:y,expressionTypeErrors:g,evalSpaceErrors:E,nullabilityErrors:A,returnType:_}=m;for(const B of g){const D=B.argIndex-(x?1:0),$=(0,Or.expressionIsScalar)(B.maxExpressionType)?"scalar":"scalar or aggregate";this.args[D].logError("invalid-function-argument-expression-type",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualExpressionType}`)}for(const B of E){const D=B.argIndex-(x?1:0),$=B.maxEvalSpace==="literal"?"literal":B.maxEvalSpace==="constant"?"literal or constant":"literal, constant or output";this.args[D].logError("invalid-function-argument-evaluation-space",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must be ${$}, but received ${B.actualEvalSpace}`)}for(const B of A){const D=B.argIndex-(x?1:0);this.args[D].logError("literal-null-function-argument",`Parameter ${B.argIndex+1} ('${B.param.name}') of ${this.name} must not be a literal null`)}m.returnTypeError&&this.logError(m.returnTypeError.code,m.returnTypeError.parameters);const v=y.returnType,C=(0,Or.maxOfExpressionTypes)([(u=v.expressionType)!==null&&u!==void 0?u:"scalar",...p.map(B=>B.expressionType)]);if(!(0,Or.expressionIsAggregate)(y.returnType.expressionType)&&this.source!==void 0)return this.loggedErrorExpr("non-aggregate-function-with-source",`Cannot call function ${this.name}(${p.map(B=>B.type).join(", ")}) with source`);const S={node:"function_call",overload:y,name:this.name,kids:{args:p.map(B=>B.value)},expressionType:C,structPath:h};let b=S;if(r!=null&&r.orderBys&&r.orderBys.length>0){const B=(0,Or.expressionIsAnalytic)(y.returnType.expressionType);if(B||this.inExperiment("aggregate_order_by",!0)||r.orderBys[0].logError("aggregate-order-by-experiment-not-enabled","Enable experiment `aggregate_order_by` to use `order_by` with an aggregate function"),y.supportsOrderBy||B){const D=y.supportsOrderBy!=="only_default",$=r.orderBys.flatMap(U=>B?U.getAnalyticOrderBy(e):U.getAggregateOrderBy(e,D));S.kids.orderBy=$}else r.orderBys[0].logError("function-does-not-support-order-by",`Function \`${this.name}\` does not support \`order_by\``)}if((r==null?void 0:r.limit)!==void 0&&(y.supportsLimit?S.limit=r.limit.limit:this.logError("function-does-not-support-limit",`Function ${this.name} does not support limit`)),r!=null&&r.partitionBys&&r.partitionBys.length>0){const B=[];for(const D of r.partitionBys)for(const $ of D.partitionFields){const U=$.getField(e);U.found===void 0?$.logError("partition-by-not-found",`${$.refString} is not defined`):(0,Or.expressionIsAnalytic)(U.found.typeDesc().expressionType)||(0,Or.expressionIsUngroupedAggregate)(U.found.typeDesc().expressionType)?$.logError("non-scalar-or-aggregate-partition-by","Partition expression must be scalar or aggregate"):B.push($.nameString)}S.partitionBy=B}if(["sql_number","sql_string","sql_date","sql_timestamp","sql_boolean"].includes(c.name)){if(!this.inExperiment("sql_functions",!0))return this.loggedErrorExpr("sql-functions-experiment-not-enabled",`Cannot use sql_function \`${c.name}\`; use \`sql_functions\` experiment to enable this behavior`);const B=p[0].value;if(B.node!=="stringLiteral")this.logError("invalid-sql-function-argument",`Invalid string literal for \`${c.name}\``);else{const D=B.literal,$=Jat(D),U=$.filter(Q=>Q.type==="interpolation"&&Q.name.includes(".")).map(Q=>Q.type==="interpolation"?`\${${Q.name}}`:`\${${Q.value}}`);if(U.length>0){const Q=U.length===1?`'.' paths are not yet supported in sql interpolations, found ${U.at(0)}`:`'.' paths are not yet supported in sql interpolations, found (${U.join(", ")})`;return this.loggedErrorExpr("unsupported-sql-function-interpolation",Q)}const V=[];for(const Q of $)if(Q.type==="string")V.push(Q.value);else if(Q.name==="TABLE")V.push({node:"source-reference"});else{const Z=new Gat.FieldName(Q.name);this.has({name:Z});const de=e.lookup([Z]);if(de.found===void 0)return this.loggedErrorExpr("sql-function-interpolation-not-found",`Invalid interpolation: ${de.error.message}`);de.found.refType==="parameter"?V.push({node:"parameter",path:[Q.name]}):V.push({node:"field",path:[Q.name]})}b=(0,H0e.composeSQLExpr)(V)}}const R=(0,Or.mergeEvalSpaces)(...p.map(B=>B.evalSpace)),O=R==="constant"?"constant":(0,Or.expressionIsScalar)(C)?R:"output";return{...(0,Or.isAtomic)(_)?Q0e.atomicDef(_):_,expressionType:C,value:b,evalSpace:O,compositeFieldUsage:(0,Vat.mergeCompositeFieldUsage)(...p.map(B=>B.compositeFieldUsage))}}}TE.ExprFunc=Yat;function Kat(t,e){var r;for(const i of t.overloads){const s=new Map;let o=0,u=!0,a=!1;const l=[],c=[],f=[];for(let p=0;p<e.length;p++){const m=e[p],y=i.params[o];if(y===void 0){u=!1;break}if(!y.allowedTypes.some(E=>{var A;const{dataTypeMatch:_,genericsSet:v}=W2(s,(A=i.genericTypes)!==null&&A!==void 0?A:[],m,E);for(const C of v)s.set(C.name,C.type);return E.expressionType&&((0,Or.isExpressionTypeLEQ)(m.expressionType,E.expressionType)||l.push({argIndex:p,maxExpressionType:E.expressionType,actualExpressionType:m.expressionType,param:y})),(E.evalSpace==="literal"&&m.evalSpace!=="literal"||E.evalSpace==="constant"&&(m.evalSpace==="input"||m.evalSpace==="output")||(0,Or.expressionIsAnalytic)(i.returnType.expressionType)&&m.evalSpace==="input")&&c.push({argIndex:p,param:y,maxEvalSpace:E.evalSpace,actualEvalSpace:m.evalSpace}),E.evalSpace==="literal"&&m.type==="null"&&f.push({argIndex:p,param:y}),_})){u=!1;break}y.isVariadic?p===e.length-1&&(a=!0):o++}if(!a&&(o!==e.length||o!==i.params.length))continue;const x=pT(i.returnType,s),h=(r=x.returnType)!==null&&r!==void 0?r:{type:"number"};if(u)return{overload:i,expressionTypeErrors:l,evalSpaceErrors:c,nullabilityErrors:f,returnTypeError:x.error,returnType:h}}}function Jat(t){const e=[];let r=t;for(;r.length;){const i=r.indexOf("${");if(i===-1){e.push({type:"string",value:r});break}else{const s=r.slice(i).indexOf("}");if(s===-1){e.push({type:"string",value:r});break}i>0&&e.push({type:"string",value:r.slice(0,i)}),e.push({type:"interpolation",name:r.slice(i+2,s+i)}),r=r.slice(s+i+1)}}return e}function W2(t,e,r,i){var s,o,u,a;if(Or.TD.eq(i,r)||i.type==="any"||i.type!=="generic"&&(r.type==="null"||r.type==="error"))return{dataTypeMatch:!0,genericsSet:[]};if(i.type==="array"&&r.type==="array"){if((0,Or.isScalarArray)(r))return(0,Or.isRepeatedRecordFunctionParam)(i)?{dataTypeMatch:!1,genericsSet:[]}:W2(t,e,r.elementTypeDef,i.elementTypeDef);if((0,Or.isRepeatedRecordFunctionParam)(i)){const l={type:"record",fields:i.fields},c={type:"record",fields:r.fields};return W2(t,e,c,l)}else return{dataTypeMatch:!1,genericsSet:[]}}else if(i.type==="record"&&r.type==="record"){const l=[],c=new Map;for(const f of i.fields)c.set((s=f.as)!==null&&s!==void 0?s:f.name,f);for(const f of r.fields){const x=c.get((o=f.as)!==null&&o!==void 0?o:f.name);if(x===void 0)return{dataTypeMatch:!1,genericsSet:[]};const h=W2(new Map([...t.entries(),...l.map(p=>[p.name,p.type])]),e,f,x);l.push(...h.genericsSet)}return{dataTypeMatch:!0,genericsSet:l}}else if(i.type==="generic"){const l=t.get(i.generic);if(l!==void 0&&l.type!=="null"&&l.type!=="error")return W2(t,e,r,l);const c=(a=(u=e.find(f=>f.name===i.generic))===null||u===void 0?void 0:u.acceptibleTypes)!==null&&a!==void 0?a:[];for(const f of c){const x=W2(t,e,r,f);if(x.dataTypeMatch){if(!(0,Or.isAtomic)(r)&&r.type!=="null")continue;const h={name:i.generic,type:r};return{dataTypeMatch:!0,genericsSet:[...x.genericsSet,h]}}}}return{dataTypeMatch:!1,genericsSet:[]}}function pT(t,e){switch(t.type){case"array":{if("fields"in t){const s=t.fields.map(o=>{const u=pT(o,e);return{...o,...u}});return{error:void 0,returnType:{type:"array",elementTypeDef:t.elementTypeDef,fields:s}}}const r=pT(t.elementTypeDef,e);if(r.error)return r;const i=r.returnType;return i.type==="record"?{error:void 0,returnType:{type:"array",elementTypeDef:{type:"record_element"},fields:i.fields}}:(0,Or.isAtomic)(i)?{error:void 0,returnType:{type:"array",elementTypeDef:i}}:{error:{code:"invalid-resolved-type-for-array",parameters:"Invalid resolved type for array; cannot be non-atomic"},returnType:void 0}}case"record":return{error:void 0,returnType:{type:"record",fields:t.fields.map(i=>{const s=pT(i,e);return{...i,...s}})}};case"generic":{const r=e.get(t.generic);return r===void 0?{error:{code:"generic-not-resolved",parameters:`Generic ${t.generic} in return type could not be resolved`},returnType:void 0}:{error:void 0,returnType:r}}default:return{error:void 0,returnType:t}}}var Xat=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Zat=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),elt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Xat(e,t,r);return Zat(e,t),e};Object.defineProperty(hT,"__esModule",{value:!0}),hT.ExprProps=void 0;const tlt=et,nlt=zs,rlt=elt(nn),ilt=rf,slt=sf,olt=z2,ult=pt,alt=TE,llt=dt;class clt extends ult.ExpressionDef{constructor(e,r){super({expr:e,statements:r}),this.expr=e,this.statements=r,this.elementType="expression with props",this.legalChildTypes=rlt.anyAtomicT}getFilteredExpression(e,r,i){if(i.length>0){if(!this.expr.supportsWhere(r))return this.expr.logError("filter-of-non-aggregate","Filtered expression requires an aggregate computation"),r;const s=[];for(const o of i){const u=o.getFilterList(e);if(u.find(a=>(0,tlt.expressionIsCalculation)(a.expressionType)))return o.logError("aggregate-filter-expression-not-scalar","Cannot filter an expresion with an aggregate or analytical computation"),r;s.push(...u)}return this.typeCheck(this.expr,{...r,expressionType:"scalar"})?{...r,compositeFieldUsage:(0,llt.mergeCompositeFieldUsage)(r.compositeFieldUsage,...s.map(o=>o.compositeFieldUsage)),value:{node:"filteredExpr",kids:{e:r.value,filterList:s}}}:(this.expr.logError("filter-of-non-aggregate",`Cannot filter '${r.expressionType}' data`),(0,nlt.errorFor)("cannot filter type"))}return r}getExpression(e){const r=[];let i;const s=[],o=[];for(const a of this.statements)a instanceof olt.PartitionBy?this.expr.canSupportPartitionBy()?r.push(a):a.logError("partition-by-of-non-window-function","`partition_by` is not supported for this kind of expression"):a instanceof slt.Limit?i?a.logError("expression-limit-already-specified","limit already specified"):this.expr.canSupportLimit()?i=a:a.logError("limit-of-non-aggregate-function","`limit` is not supported for this kind of expression"):a instanceof ilt.FunctionOrdering?this.expr.canSupportOrderBy()?s.push(a):a.logError("order-by-of-non-aggregate-function","`order_by` is not supported for this kind of expression"):o.push(a);const u=this.expr instanceof alt.ExprFunc?this.expr.getPropsExpression(e,{partitionBys:r,limit:i,orderBys:s}):this.expr.getExpression(e);return this.getFilteredExpression(e,u,o)}}hT.ExprProps=clt;var mT={},flt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),xlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),dlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&flt(e,t,r);return xlt(e,t),e};Object.defineProperty(mT,"__esModule",{value:!0}),mT.ExprLogicalOp=void 0;const hlt=CE,z0e=dlt(nn);class plt extends hlt.BinaryBoolean{constructor(){super(...arguments),this.elementType="logical operator",this.legalChildTypes=[z0e.boolT,z0e.aggregateBoolT]}}mT.ExprLogicalOp=plt;var gT={},mlt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),glt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),ylt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&mlt(e,t,r);return glt(e,t),e};Object.defineProperty(gT,"__esModule",{value:!0}),gT.ExprMax=void 0;const yT=ylt(nn),Elt=E0;class Alt extends Elt.ExprAggregateFunction{constructor(e){super("max",e),this.legalChildTypes=[yT.numberT,yT.stringT,yT.dateT,yT.timestampT]}returns(e){return e}}gT.ExprMax=Alt;var ET={},_lt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),vlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Clt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&_lt(e,t,r);return vlt(e,t),e};Object.defineProperty(ET,"__esModule",{value:!0}),ET.ExprMin=void 0;const AT=Clt(nn),Slt=E0;class blt extends Slt.ExprAggregateFunction{constructor(e){super("min",e),this.legalChildTypes=[AT.numberT,AT.stringT,AT.dateT,AT.timestampT]}returns(e){return e}}ET.ExprMin=blt;var _T={},Tlt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Rlt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Dlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Tlt(e,t,r);return Rlt(e,t),e};Object.defineProperty(_T,"__esModule",{value:!0}),_T.ExprMinus=void 0;const Olt=zs,W0e=Dlt(nn),wlt=pt;class Flt extends wlt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="unary minus",this.legalChildTypes=[W0e.numberT]}getExpression(e){const r=this.expr.getExpression(e);return W0e.typeIn(r,this.legalChildTypes)?{...r,type:"number",value:{node:"unary-",e:r.value}}:(0,Olt.errorFor)("negate requires number")}}_T.ExprMinus=Flt;var vT={};Object.defineProperty(vT,"__esModule",{value:!0}),vT.ExprMulDiv=void 0;const Nlt=q2;class Llt extends Nlt.BinaryNumeric{constructor(){super(...arguments),this.elementType="*/%"}}vT.ExprMulDiv=Llt;var CT={},RE={};Object.defineProperty(RE,"__esModule",{value:!0}),RE.Unary=void 0;const Ilt=pt;class $lt extends Ilt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e}}RE.Unary=$lt;var Blt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),klt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mlt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Blt(e,t,r);return klt(e,t),e};Object.defineProperty(CT,"__esModule",{value:!0}),CT.ExprNot=void 0;const xk=Mlt(nn),Plt=RE;class Ult extends Plt.Unary{constructor(e){super(e),this.elementType="not",this.legalChildTypes=[xk.boolT,xk.nullT]}getExpression(e){var r;const i=this.expr.getExpression(e);!((r=e.dialectObj())===null||r===void 0)&&r.booleanAsNumbers&&this.legalChildTypes.find(o=>o.type==="number")===void 0&&this.legalChildTypes.push(xk.numberT);const s=this.typeCheck(this.expr,i);return{...i,type:"boolean",value:{node:"not",e:s?i.value:{node:"false"}}}}}CT.ExprNot=Ult;var ST={};Object.defineProperty(ST,"__esModule",{value:!0}),ST.ExprNow=void 0;const jlt=pt,qlt=dt;class Hlt extends jlt.ExpressionDef{constructor(){super(...arguments),this.elementType="timestamp"}getExpression(e){return{type:"timestamp",expressionType:"scalar",evalSpace:"constant",value:{node:"now",typeDef:{type:"timestamp"}},compositeFieldUsage:(0,qlt.emptyCompositeFieldUsage)()}}}ST.ExprNow=Hlt;var uf={};Object.defineProperty(uf,"__esModule",{value:!0}),uf.ExprIsNull=uf.PartialIsNull=uf.ExprNULL=void 0;const Qlt=zt,bT=pt;function dk(t,e,r){const i=r.getExpression(t);return i.type="boolean",i.value={node:e==="="?"is-null":"is-not-null",e:i.value},i}class zlt extends bT.ExpressionDef{constructor(){super(...arguments),this.elementType="NULL"}getExpression(){return(0,Qlt.literalExprValue)({dataType:{type:"null"},value:{node:"null"}})}apply(e,r,i){return r==="!="||r==="="?dk(e,r,i):super.apply(e,r,i,!0)}}uf.ExprNULL=zlt;class Wlt extends bT.ExpressionDef{constructor(e){super(),this.op=e,this.elementType="<=> NULL"}apply(e,r,i){return dk(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial null check does not have a value")}atNodeType(){return bT.ATNodeType.Partial}}uf.PartialIsNull=Wlt;class Glt extends bT.ExpressionDef{constructor(e,r){super(),this.expr=e,this.op=r,this.elementType="is null",this.has({expr:e})}getExpression(e){return dk(e,this.op,this.expr)}}uf.ExprIsNull=Glt;var TT={};Object.defineProperty(TT,"__esModule",{value:!0}),TT.ExprNumber=void 0;const Vlt=zt,Ylt=pt;class Klt extends Ylt.ExpressionDef{constructor(e){super(),this.n=e,this.elementType="numeric literal"}getExpression(e){return this.constantExpression()}constantExpression(){const e=Number(this.n),r=Number.isNaN(e)?{type:"number"}:{type:"number",numberType:Number.isInteger(e)?"integer":"float"};return(0,Vlt.literalExprValue)({dataType:r,value:{node:"numberLiteral",literal:this.n}})}}TT.ExprNumber=Klt;var RT={};Object.defineProperty(RT,"__esModule",{value:!0}),RT.ExprParens=void 0;const hk=pt;class Jlt extends hk.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="(expression)"}requestExpression(e){return this.expr.requestExpression(e)}getExpression(e){const r=this.expr.getExpression(e);return{...r,value:{node:"()",e:r.value}}}apply(e,r,i,s){return this.expr.atNodeType()===hk.ATNodeType.Or?this.expr.apply(e,r,i,s):(0,hk.applyBinary)(e,i,r,this)}atNodeType(){return this.expr.atNodeType()}atExpr(){return this.expr}}RT.ExprParens=Jlt;var DT={};Object.defineProperty(DT,"__esModule",{value:!0}),DT.ExprFilterExpression=void 0;const Xlt=zt,Zlt=pt,OT=I4;class e0t extends Zlt.ExpressionDef{constructor(e){super(),this.filterText=e,this.elementType="filter expression literal"}getExpression(){return this.loggedErrorExpr("filter-expression-type","Filter expression illegal here")}apply(e,r,i,s=!1){var o;if(r==="~"||r==="!~"){const u=i.getExpression(e);if(u.type==="error")return u;let a;switch(u.type){case"string":a=OT.StringFilterExpression.parse(this.filterText);break;case"number":a=OT.NumberFilterExpression.parse(this.filterText);break;case"boolean":if(!((o=e.dialectObj())===null||o===void 0)&&o.booleanAsNumbers)return this.loggedErrorExpr("filter-expression-type","Boolean filters not supported on this connection type");a=OT.BooleanFilterExpression.parse(this.filterText);break;case"date":case"timestamp":a=OT.TemporalFilterExpression.parse(this.filterText);break;default:return i.loggedErrorExpr("filter-expression-type",`Cannot use filter expressions with type '${u.type}'`)}if(a.log.length>0)for(const c of a.log)return this.loggedErrorExpr("filter-expression-error",`Filter parse error: ${c.message}`);const l={node:"filterMatch",dataType:u.type,filter:a.parsed,e:u.value};return r==="!~"&&(l.notMatch=!0),(0,Xlt.computedExprValue)({value:l,dataType:{type:"boolean"},from:[u]})}return this.loggedErrorExpr("filter-expression-type",`Cannot use the '${r}' operator with a filter expression`)}}DT.ExprFilterExpression=e0t;var wT={};Object.defineProperty(wT,"__esModule",{value:!0}),wT.ExprRegEx=void 0;const t0t=zt,n0t=pt;class r0t extends n0t.ExpressionDef{constructor(e){super(),this.regex=e,this.elementType="regular expression literal"}getExpression(){return(0,t0t.literalExprValue)({dataType:{type:"regular expression"},value:{node:"regexpLiteral",literal:this.regex}})}}wT.ExprRegEx=r0t;var FT={};Object.defineProperty(FT,"__esModule",{value:!0}),FT.ExprString=void 0;const i0t=pt,s0t=zt;class o0t extends i0t.ExpressionDef{constructor(e){super(),this.elementType="string literal",this.value=e}getExpression(e){return(0,s0t.literalExprValue)({dataType:{type:"string"},value:{node:"stringLiteral",literal:this.value}})}}FT.ExprString=o0t;var NT={};Object.defineProperty(NT,"__esModule",{value:!0}),NT.ExprSum=void 0;const u0t=Q2;class a0t extends u0t.ExprAsymmetric{constructor(e,r,i){super("sum",e,r,i),this.has({source:r})}}NT.ExprSum=a0t;var LT={};Object.defineProperty(LT,"__esModule",{value:!0}),LT.ExprTimeExtract=void 0;const A0=et,IT=zt,pk=pt,l0t=nf;class DE extends pk.ExpressionDef{static extractor(e){const r=DE.pluralMap[e];if(r)return r;if((0,A0.isExtractUnit)(e))return e}constructor(e,r){super({args:r}),this.extractText=e,this.args=r,this.elementType="timeExtract"}getExpression(e){const r=DE.extractor(this.extractText);if(r){if(this.args.length!==1)return this.loggedErrorExpr("too-many-arguments-for-time-extraction",`Extraction function ${r} requires one argument`);const i=this.args[0];if(i instanceof l0t.Range){let s=i.first.getExpression(e),o=i.last.getExpression(e);if(s.type==="error"||o.type==="error")return(0,IT.computedErrorExprValue)({dataType:{type:"number"},error:"extract from error",from:[s,o]});if(!(0,A0.isTemporalType)(s.type))return i.first.loggedErrorExpr("invalid-type-for-time-extraction",`Can't extract ${r} from '${s.type}'`);if(!(0,A0.isTemporalType)(o.type))return i.last.loggedErrorExpr("invalid-type-for-time-extraction",`Cannot extract ${r} from '${o.type}'`);let u=s.type;if(!A0.TD.eq(s,o)){let a=!0;if(u="timestamp",s.type==="date"){const l=(0,pk.getMorphicValue)(s,"timestamp");l&&(s=l,a=!1)}else{const l=(0,pk.getMorphicValue)(o,"timestamp");l&&(o=l,a=!1)}if(a)return i.first.loggedErrorExpr("invalid-types-for-time-measurement",`Cannot measure from ${s.type} to ${o.type}`)}return["week","month","quarter","year"].includes(r)?this.loggedErrorExpr("invalid-timeframe-for-time-measurement",`Cannot measure interval using '${r}'`):(0,A0.isTimestampUnit)(r)?(0,IT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"timeDiff",units:r,kids:{left:(0,A0.mkTemporal)(s.value,u),right:(0,A0.mkTemporal)(o.value,u)}},from:[s,o]}):this.loggedErrorExpr("invalid-time-extraction-unit",`Cannot extract ${r} from a range`)}else{const s=i.getExpression(e);return(0,A0.isTemporalType)(s.type)?(0,IT.computedExprValue)({dataType:{type:"number",numberType:"integer"},value:{node:"extract",e:(0,A0.mkTemporal)(s.value,s.type),units:r},from:[s]}):(s.type!=="error"&&this.logError("unsupported-type-for-time-extraction",`${this.extractText}() requires time type, not '${s.type}'`),(0,IT.computedErrorExprValue)({dataType:{type:"number",numberType:"integer"},error:`${this.extractText} bad type ${s.type}`,from:[s]}))}}throw this.internalError(`Illegal extraction unit '${this.extractText}'`)}}LT.ExprTimeExtract=DE,DE.pluralMap={years:"year",quarters:"quarter",months:"month",weeks:"week",days:"day",hours:"hour",minutes:"minute",seconds:"second"};var $T={},Du={},BT={};Object.defineProperty(BT,"__esModule",{value:!0}),BT.QueryInputSpace=void 0;const c0t=As,f0t=w2;class x0t extends f0t.RefinedSpace{constructor(e,r,i){super(e),this.queryOutput=r,this._isProtectedAccessSpace=i,this.extendList=[]}extendSource(e){this.pushFields(e),e instanceof c0t.Join?this.extendList.push(e.name.refString):this.extendList.push(e.defineName)}isQueryFieldSpace(){return!0}outputSpace(){return this.queryOutput}inputSpace(){return this}isProtectedAccessSpace(){return this._isProtectedAccessSpace}}BT.QueryInputSpace=x0t;var d0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),h0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),p0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&d0t(e,t,r);return h0t(e,t),e};Object.defineProperty(Du,"__esModule",{value:!0}),Du.ReduceFieldSpace=Du.QuerySpace=Du.QueryOperationSpace=void 0;const kT=p0t(et),mk=Kc,G0e=of,V0e=Wr,m0t=_t,g0t=w2,y0t=lE,E0t=Gr,A0t=BT,Qa=dt,_0t=bd;class Y0e extends g0t.RefinedSpace{get compositeFieldUsage(){if(this._compositeFieldUsage===void 0)throw new Error("Composite field usage accessed before computed");return this._compositeFieldUsage}constructor(e,r,i,s){super(e.emptyStructDef()),this.queryInputSpace=e,this.nestParent=i,this.astEl=s,this.expandedWild={},this.compositeFieldUsers=[],this._compositeFieldUsage=void 0,this.exprSpace=new A0t.QueryInputSpace(e.structDef(),this,e.isProtectedAccessSpace()),r&&this.addRefineFromFields(r)}logError(e,r,i){return this.astEl&&this.astEl.logError(e,r,i),e}inputSpace(){return this.exprSpace}outputSpace(){return this}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof E0t.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-defined",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries())if(!e.except.has(a)&&l.refType!=="parameter")if(this.entry(a)){const c=(r=this.expandedWild[a])===null||r===void 0?void 0:r.path.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${c?` (conflicts with ${c})`:""}`)}else{const c=l.typeDesc();kT.TD.isAtomic(c)&&kT.expressionIsScalar(c.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:a,entry:l}),this.expandedWild[a]={path:s.concat(a),entry:l})}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.newEntry(a.name,e,a.entry)}addValidatedCompositeFieldUserFromEntry(e,r){r instanceof V0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:r,logTo:void 0})}getJoinOnCompositeFieldUsage(e){var r;const i=e.map(o=>new G0e.FieldName(o));this.astEl.has({reference:i});const s=this.exprSpace.lookup(i);if(s.found&&s.found instanceof _0t.StructSpaceFieldBase)return(0,Qa.joinedCompositeFieldUsage)(e.slice(0,-1),(r=s.found.fieldDef().onCompositeFieldUsage)!==null&&r!==void 0?r:(0,Qa.emptyCompositeFieldUsage)());throw new Error("Unexpected join lookup was not found or not a struct")}getCompositeFieldUsageIncludingJoinOns(e){let r=e;const i=(0,Qa.compositeFieldUsageJoinPaths)(e);for(const s of i)r=(0,Qa.mergeCompositeFieldUsage)(this.getJoinOnCompositeFieldUsage(s),r);return r}addCompositeFieldUserFromFilter(e,r){e.compositeFieldUsage!==void 0&&this.compositeFieldUsers.push({type:"filter",filter:e,logTo:r})}newEntry(e,r,i){i instanceof V0e.SpaceField&&this.compositeFieldUsers.push({type:"field",name:e,field:i,logTo:r}),super.newEntry(e,r,i)}applyNextCompositeFieldUsage(e,r,i,s,o){if(s){const u=this.getCompositeFieldUsageIncludingJoinOns((0,Qa.compositeFieldUsageDifference)(s,r));if(r=(0,Qa.mergeCompositeFieldUsage)(r,u),!(0,Qa.isEmptyCompositeFieldUsage)(u)){const a=(0,Qa.narrowCompositeFieldResolution)(e,r,i);a.error?(o??this).logError("invalid-composite-field-usage",{newUsage:u,allUsage:r}):i=a.narrowedCompositeFieldResolution}}return{compositeFieldUsage:r,narrowedCompositeFieldResolution:i}}}Du.QueryOperationSpace=Y0e;class K0e extends Y0e{addRefineFromFields(e){var r;if(kT.isQuerySegment(e)){if(e!=null&&e.extendSource)for(const i of e.extendSource)this.exprSpace.addFieldDef(i);for(const i of e.queryFields)if(i.type==="fieldref"){const s=this.exprSpace.lookup(i.path.map(o=>new G0e.FieldName(o)));if(s.found){const o=i.path[i.path.length-1];this.setEntry(o,s.found),this.addValidatedCompositeFieldUserFromEntry(o,s.found)}}else if(i.type!=="turtle"){const s=new y0t.ColumnSpaceField(i),o=(r=i.as)!==null&&r!==void 0?r:i.name;this.setEntry(o,s),this.addValidatedCompositeFieldUserFromEntry(o,s)}}}pushFields(...e){for(const r of e)r instanceof m0t.WildcardFieldReference?this.addWild(r):super.pushFields(r)}canContain(e){return!0}queryFieldDefs(){const e=[];let r=(0,Qa.emptyCompositeFieldUsage)(),i=(0,Qa.emptyNarrowedCompositeFieldResolution)();const s=this.inputSpace().structDef();for(const o of this.compositeFieldUsers){let u;if(o.type==="filter")o.filter.compositeFieldUsage&&(u=o.filter.compositeFieldUsage);else{const{name:l,field:c}=o,f=this.expandedWild[l];if(f)e.push({type:"fieldref",path:f.path}),u=f.entry.typeDesc().compositeFieldUsage;else{const x=c.getQueryFieldDef(this.exprSpace);if(x){const h=c.typeDesc();u=h.compositeFieldUsage,h&&h.type!=="error"&&this.canContain(h)&&!C0t(x)&&e.push(x)}}}const a=this.applyNextCompositeFieldUsage(s,r,i,u,o.logTo);r=a.compositeFieldUsage,i=a.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,e}getQuerySegment(e){const r=this.getPipeSegment(e);if(kT.isQuerySegment(r))return r;throw new Error("TODO NOT POSSIBLE")}getPipeSegment(e){if(this.segmentType==="index")return this.logError("unexpected-index-segment","internal error generating index segment from non index query"),{type:"reduce",queryFields:[]};const r={type:this.segmentType,queryFields:this.queryFieldDefs()};if(r.queryFields=(0,mk.mergeFields)(e==null?void 0:e.queryFields,r.queryFields),e!=null&&e.extendSource&&(r.extendSource=e.extendSource),this.exprSpace.extendList.length>0){const i=[],s=this.exprSpace.structDef();for(const o of this.exprSpace.extendList){const u=s.fields.find(a=>(0,mk.nameFromDef)(a)===o);u&&i.push(u)}r.extendSource=(0,mk.mergeFields)(r.extendSource,i)}return this.newTimezone&&(r.queryTimezone=this.newTimezone),r}lookup(e){const r=super.lookup(e);return r.found?{...r,isOutputField:!0}:this.exprSpace.lookup(e)}isQueryFieldSpace(){return!0}}Du.QuerySpace=K0e;class v0t extends K0e{constructor(){super(...arguments),this.segmentType="reduce"}}Du.ReduceFieldSpace=v0t;function C0t(t){return typeof t!="string"&&t.type==="turtle"&&t.pipeline.length===0}var S0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),b0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),T0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&S0t(e,t,r);return b0t(e,t),e};Object.defineProperty($T,"__esModule",{value:!0}),$T.ExprUngroup=void 0;const J0e=et,R0t=Du,X0e=T0t(nn),D0t=pt;class O0t extends D0t.ExpressionDef{constructor(e,r,i){super({expr:r,fields:i}),this.control=e,this.expr=r,this.fields=i,this.legalChildTypes=X0e.anyAtomicT,this.elementType="ungroup"}getExpression(e){const r=this.expr.getExpression(e);if(!(0,J0e.expressionIsAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-non-aggregate",`${this.control}() expression must be an aggregate`);if((0,J0e.expressionIsUngroupedAggregate)(r.expressionType))return this.expr.loggedErrorExpr("ungroup-of-ungrouped-aggregate",`${this.control}() expression must not already be ungrouped`);const i={node:this.control,e:r.value};if(this.typeCheck(this.expr,{...r,expressionType:"scalar"})){if(e.isQueryFieldSpace()&&this.fields.length>0){const s=[],o=this.control==="exclude";for(const u of this.fields){let a=e.outputSpace(),l=!0;for(;a;){const c=a.lookup([u]);if(c.found&&c.isOutputField)s.push(u.refString),l=!1;else if(a instanceof R0t.QuerySpace){a=a.nestParent;continue}break}if(l){const c=o?"exclude()":"all()";u.logError("ungroup-field-not-in-output",`${c} '${u.refString}' is missing from query output`)}}i.fields=s}return{...X0e.atomicDef(r),expressionType:"ungrouped_aggregate",value:i,evalSpace:"output",compositeFieldUsage:r.compositeFieldUsage}}return this.loggedErrorExpr("ungroup-with-non-scalar",`${this.control}() incompatible type`)}}$T.ExprUngroup=O0t;var MT={},w0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),F0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),N0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&w0t(e,t,r);return F0t(e,t),e};Object.defineProperty(MT,"__esModule",{value:!0}),MT.ForRange=void 0;const L0t=zs,Z0e=N0t(nn),PT=_s,I0t=zt,$0t=pt,UT=j2,ece=nf;class B0t extends $0t.ExpressionDef{constructor(e,r,i){super({from:e,duration:r,timeframe:i}),this.from=e,this.duration=r,this.timeframe=i,this.elementType="forRange",this.legalChildTypes=[Z0e.timestampT,Z0e.dateT]}apply(e,r,i){const s=this.from.getExpression(e),o=i.getExpression(e);if(!this.typeCheck(i,o))return(0,L0t.errorFor)("no time for range");const u=this.duration.getExpression(e);if(u.type!=="number")return u.type!=="error"&&this.logError("invalid-duration-quantity",`FOR duration count must be a number, not '${u.type}'`),(0,I0t.computedErrorExprValue)({dataType:{type:"boolean"},error:"for not number",from:[s,o]});const a=this.timeframe.text;let l=(0,PT.resolution)(a);if(s.type==="timestamp"&&(l="timestamp"),o.type==="date"&&l==="date"){const m=this.from,y=(0,PT.timeOffset)("date",s.value,"+",u.value,a),g=new UT.ExprTime("date",y);return new ece.Range(m,g).apply(e,r,i)}const c=UT.ExprTime.fromValue("timestamp",o);let f=this.from,x=s.value;if(s.type==="date"){const m=s.morphic&&s.morphic.timestamp;m?x=m:x=(0,PT.castTo)("timestamp",x,"date"),f=new UT.ExprTime("timestamp",x,[s])}const h=(0,PT.timeOffset)("timestamp",x,"+",u.value,a),p=new UT.ExprTime("timestamp",h,[s,u]);return new ece.Range(f,p).apply(e,r,c)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("range-as-value","A Range is not a value")}}MT.ForRange=B0t;var wr={};Object.defineProperty(wr,"__esModule",{value:!0}),wr.LiteralYear=wr.LiteralQuarter=wr.LiteralMonth=wr.LiteralWeek=wr.LiteralDay=wr.LiteralHour=wr.LiteralTimestamp=wr.TimeFormatError=void 0;const af=qr,k0t=et,M0t=zt,P0t=nf,tce=j2,gk=pt;class U0t extends Error{}wr.TimeFormatError=U0t;function Od(t,e){const r=t.slice(1);if(e){const i=r.match(/\[[^\]]+]$/);if(i)return{tzSpec:i[0].slice(1,-1),text:r.slice(0,-i[0].length)}}return{text:r}}const nce="yyyy",rce=`${nce}-LL`,Do=`${rce}-dd`,ice=`${Do} HH`,sce=`${ice}:mm`,yk=`${sce}:ss`;class oce extends gk.ExpressionDef{constructor(e,r,i){super(),this.units=r,this.timeType=i,this.literalPart=e.text,e.tzSpec&&(this.timeZone=e.tzSpec)}makeLiteral(e,r){const i={node:"timeLiteral",literal:e,typeDef:{type:r}};return this.timeZone&&(i.timezone=this.timeZone),i}makeValue(e,r){const i=this.makeLiteral(e,r);return(0,M0t.literalTimeResult)({value:i,dataType:{type:r},timeframe:this.units})}getExpression(e){return this.makeValue(this.literalPart,this.timeType)}getNext(){if(this.nextLit)return this.makeValue(this.nextLit,this.timeType)}granular(){return this.nextLit!==void 0}}class Ek extends oce{constructor(e,r){super(e,r,"timestamp"),this.elementType="literal:timestamp"}static parse(e){let r;const i=Od(e,!0);e=i.text,e[10]==="T"&&(e=e.slice(0,10)+" "+e.slice(11),i.text=e);const s=e.match(/^([^.,]+)[,.](\d+)$/);s&&(e=s[1]);let o=af.DateTime.fromFormat(e,yk);if(o.isValid)return new Ek(i,r);if(o=af.DateTime.fromFormat(e,sce),o.isValid){i.text=i.text+":00",r="minute";const u=o.plus({minute:1}).toFormat(yk);return new Ak(i,r,"timestamp",u)}}}wr.LiteralTimestamp=Ek;class Ak extends oce{constructor(e,r,i,s){super(e,r,i),this.nextLit=s,this.elementType="granularTimeLiteral"}apply(e,r,i){let s=this.getExpression(e),o=this.getNext();if(o){const u=i.getExpression(e);if(u.type==="timestamp"){const a=(0,gk.getMorphicValue)(s,"timestamp"),l=(0,gk.getMorphicValue)(o,"timestamp");if(a&&l)s=a,o=l;else return super.apply(e,r,i)}if(o&&(0,k0t.isTemporalType)(u.type)){const a=u.type;return new P0t.Range(new tce.ExprTime(a,s.value),new tce.ExprTime(a,o.value)).apply(e,r,i)}}return super.apply(e,r,i)}}class _k extends Ak{constructor(e,r){super(e,"hour","timestamp",r),this.elementType="literal:hour"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,ice);if(s.isValid)return r.text=r.text+":00:00",i=s.plus({hour:1}).toFormat(yk),new _k(r,i)}}wr.LiteralHour=_k;class OE extends Ak{constructor(e,r,i){super(e,r,"date",i)}getExpression(e){const r=this.makeValue(this.literalPart,"date"),i=this.makeLiteral(`${this.literalPart} 00:00:00`,"timestamp");return{...r,morphic:{timestamp:i},evalSpace:"literal"}}getNext(){const e=this.makeValue(this.nextLit,"date"),r=this.makeLiteral(`${this.nextLit} 00:00:00`,"timestamp");return{...e,morphic:{timestamp:r}}}}class vk extends OE{constructor(e,r){super(e,"day",r),this.elementType="literal:day"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,Do);if(s.isValid)return i=s.plus({day:1}).toFormat(Do),new vk(r,i)}}wr.LiteralDay=vk;class Ck extends OE{constructor(e,r){super(e,"week",r),this.elementType="literal:week"}static parse(e){const r=Od(e,!1);let i=r.text;const s=r.text.slice(0,10),o=af.DateTime.fromFormat(s,Do);if(o.isValid&&o.weekday===7){const a=o.plus({days:7});return r.text=o.toFormat(Do),i=a.toFormat(Do),new Ck(r,i)}}}wr.LiteralWeek=Ck;class Sk extends OE{constructor(e,r){super(e,"month",r),this.elementType="literal:month"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,rce);if(s.isValid){const o=s.plus({months:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Sk(r,i)}}}wr.LiteralMonth=Sk;class bk extends OE{constructor(e,r){super(e,"quarter",r),this.elementType="literal:quarter"}static parse(e){const r=Od(e,!1);let i=r.text;const s=r.text.match(/(^\d{4})-[qQ](\d)$/);if(s){const o=Number.parseInt(s[2])-1;let u=af.DateTime.fromFormat(s[1],"yyyy");o>0&&(u=u.plus({quarters:o}));const a=u.plus({quarter:1});return r.text=u.toFormat(Do),i=a.toFormat(Do),new bk(r,i)}}}wr.LiteralQuarter=bk;class Tk extends OE{constructor(e,r){super(e,"year",r),this.elementType="literal:year"}static parse(e){const r=Od(e,!1);let i=r.text;const s=af.DateTime.fromFormat(r.text,nce);if(s.isValid){const o=s.plus({year:1});return r.text=s.toFormat(Do),i=o.toFormat(Do),new Tk(r,i)}}}wr.LiteralYear=Tk;var jT={};Object.defineProperty(jT,"__esModule",{value:!0}),jT.PartialCompare=void 0;const uce=pt;class j0t extends uce.ExpressionDef{constructor(e,r){super({right:r}),this.op=e,this.right=r,this.elementType="<=> a"}granular(){return this.right.granular()}apply(e,r,i){return this.right.apply(e,this.op,i)}requestExpression(e){}getExpression(e){return this.loggedErrorExpr("partial-as-value","Partial comparison does not have a value")}atNodeType(){return uce.ATNodeType.Partial}}jT.PartialCompare=j0t;var G2={},q0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),H0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Q0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&q0t(e,t,r);return H0t(e,t),e};Object.defineProperty(G2,"__esModule",{value:!0}),G2.PickWhen=G2.Pick=void 0;const V2=Q0t(nn),ace=zt,z0t=pt,W0t=Ze;function qT(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class G0t extends z0t.ExpressionDef{constructor(e,r){super({choices:e}),this.choices=e,this.elsePick=r,this.elementType="pick",this.has({elsePick:r})}requestExpression(e){if(this.elsePick!==void 0){for(const r of this.choices){if(r.pick===void 0)return;const i=r.when.requestExpression(e);if(i===void 0||i.type!=="boolean")return}return this.getExpression(e)}}apply(e,r,i){var s;const o={node:"case",kids:{caseWhen:[],caseThen:[]}};let u;const a=[];for(const h of this.choices){const p=h.when.apply(e,"=",i),m=h.pick?h.pick.getExpression(e):i.getExpression(e);if(a.push(p,m),u&&!V2.typeEq(u,m,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:m.type,returnType:u.type});u=qT(u,m),o.kids.caseWhen.push(p.value),o.kids.caseThen.push(m.value)}const l=(s=this.elsePick)===null||s===void 0?void 0:s.getExpression(e),c=i.getExpression(e);a.push(c),l&&a.push(l);const f=l??c,x=qT(u,f);return V2.typeEq(x,f,!0)?(o.kids.caseElse=f.value,(0,ace.computedExprValue)({dataType:x,value:o,from:a})):this.elsePick?this.loggedErrorExpr("pick-else-type-does-not-match",{elseType:f.type,returnType:x.type}):this.loggedErrorExpr("pick-default-type-does-not-match",{defaultType:f.type,returnType:x.type})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}};if(this.elsePick===void 0)return this.loggedErrorExpr("pick-missing-else","pick incomplete, missing 'else'");const i=[],s=[];for(const l of this.choices){if(l.pick===void 0)return this.loggedErrorExpr("pick-missing-value","pick with no value can only be used with apply");l.when.requestExpression(e)===void 0&&this.loggedErrorExpr("pick-illegal-partial","pick with partial when can only be used with apply");const f=l.pick.getExpression(e),x=l.when.getExpression(e);i.push({pick:f,when:x}),s.push(f,x)}let o;for(const l of i){if(!V2.typeEq(l.when,V2.boolT))return this.loggedErrorExpr("pick-when-must-be-boolean",{whenType:l.when.type});if(o&&!V2.typeEq(o,l.pick,!0))return this.loggedErrorExpr("pick-type-does-not-match",{pickType:l.pick.type,returnType:o.type});o=qT(o,l.pick),r.kids.caseWhen.push(l.when.value),r.kids.caseThen.push(l.pick.value)}const u=this.elsePick.getExpression(e);s.push(u);const a=qT(o,u);return V2.typeEq(a,u,!0)?(r.kids.caseElse=u.value,(0,ace.computedExprValue)({dataType:a,value:r,from:s})):this.elsePick.loggedErrorExpr("pick-else-type-does-not-match",{elseType:u.type,returnType:a.type})}}G2.Pick=G0t;class V0t extends W0t.MalloyElement{constructor(e,r){super({when:r}),this.pick=e,this.when=r,this.elementType="caseWhen",this.has({pick:e})}}G2.PickWhen=V0t;var Y2={},Y0t=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),K0t=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),J0t=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Y0t(e,t,r);return K0t(e,t),e};Object.defineProperty(Y2,"__esModule",{value:!0}),Y2.CaseWhen=Y2.Case=void 0;const X0t=zt,Z0t=pt,ect=Ze,K2=J0t(nn);function lce(t,e){return t===void 0||t.type==="null"||t.type==="error"?e:t}class tct extends Z0t.ExpressionDef{constructor(e,r,i){super({choices:r}),this.value=e,this.choices=r,this.elseValue=i,this.elementType="case",this.has({elseValue:i,value:e})}getExpression(e){const r={node:"case",kids:{caseWhen:[],caseThen:[]}},i=[];let s;if(this.value){const a=this.value.getExpression(e);i.push(a),r.kids.caseValue=a.value,s=a}const o=[];for(const a of this.choices){const l=a.when.getExpression(e),c=a.then.getExpression(e);o.push({when:l,then:c}),i.push(l,c)}let u;for(const a of o){if(s!==void 0){if(!K2.typeEq(a.when,s))return this.loggedErrorExpr("case-when-type-does-not-match",{whenType:a.when.type,valueType:s.type})}else if(!K2.typeEq(a.when,K2.boolT))return this.loggedErrorExpr("case-when-must-be-boolean",{whenType:a.when.type});if(u&&!K2.typeEq(u,a.then,!0))return this.loggedErrorExpr("case-then-type-does-not-match",{thenType:a.then.type,returnType:u.type});u=lce(u,a.then),r.kids.caseWhen.push(a.when.value),r.kids.caseThen.push(a.then.value)}if(this.elseValue){const a=this.elseValue.getExpression(e);if(u&&!K2.typeEq(u,a,!0))return this.loggedErrorExpr("case-else-type-does-not-match",{elseType:a.type,returnType:u.type});u=lce(u,a),i.push(a),r.kids.caseElse=a.value}return(0,X0t.computedExprValue)({value:r,dataType:u?K2.atomicDef(u):{type:"null"},from:i})}}Y2.Case=tct;class nct extends ect.MalloyElement{constructor(e,r){super({when:e,then:r}),this.when=e,this.then=r,this.elementType="caseWhen"}}Y2.CaseWhen=nct;var HT={},wd={},rct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),ict=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),sct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&rct(e,t,r);return ict(e,t),e};Object.defineProperty(wd,"__esModule",{value:!0}),wd.RecordLiteral=wd.RecordElement=void 0;const cce=Yi,oct=zt,uct=pt,act=Ze,lct=sct(nn);class cct extends act.MalloyElement{constructor(e){if(super(),this.elementType="record element","value"in e)this.value=e.value,this.has({value:e.value}),e.key&&(this.key=e.key);else{this.has({path:e.path}),this.value=e.path;const r=e.path.fieldReference.path;this.key=r[r.length-1]}}}wd.RecordElement=cct;class fct extends uct.ExpressionDef{constructor(e){super(),this.pairs=e,this.elementType="record literal",this.has({pairs:e})}getExpression(e){return this.getRecord(e,[])}getRecord(e,r){var i;const s={node:"recordLiteral",kids:{},typeDef:{type:"record",fields:[]}},o=[];let u=0;for(const a of this.pairs){const l=(i=a.key)!==null&&i!==void 0?i:r[u];if(u+=1,l===void 0){a.logError("record-literal-needs-keys","Anonymous record element not legal here");continue}const c=a.value.getExpression(e);cce.TD.isAtomic(c)?(o.push(c),s.kids[l]=c.value,s.typeDef.fields.push((0,cce.mkFieldDef)(lct.atomicDef(c),l))):a.value.logError("illegal-record-property-type",`Record property '${a.key} is type '${c.type}', which is not a legal property value type`)}return(0,oct.computedExprValue)({value:s,dataType:s.typeDef,from:o})}getNextElement(e,r){const i=r.value;return i.node==="recordLiteral"?this.getRecord(e,Object.keys(i.kids)):this.getRecord(e,[])}}wd.RecordLiteral=fct;var xct=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),dct=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),hct=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&xct(e,t,r);return dct(e,t),e};Object.defineProperty(HT,"__esModule",{value:!0}),HT.ArrayLiteral=void 0;const pct=zt,mct=pt,fce=hct(nn),gct=wd;class yct extends mct.ExpressionDef{constructor(e){super(),this.elements=e,this.elementType="array literal",this.has({elements:e})}getExpression(e){const r=[],i=[];let s;if(this.elements.length>0)for(const l of this.elements){const c=s&&l instanceof gct.RecordLiteral?l.getNextElement(e,s):l.getExpression(e);if(i.push(c),c.type!=="error"){if(s){if(c.type!=="null"&&!fce.typeEq(s,c)){l.logError("array-values-incompatible","All array elements must be same type");continue}}else c.type!=="null"&&(s=c);r.push(c.value)}}const o=fce.atomicDef(s||{type:"number"}),u=o.type==="record"?{type:"array",elementTypeDef:{type:"record_element"},fields:o.fields}:{type:"array",elementTypeDef:o},a={node:"arrayLiteral",kids:{values:r},typeDef:u};return(0,pct.computedExprValue)({dataType:u,value:a,from:i})}}HT.ArrayLiteral=yct;var QT={};Object.defineProperty(QT,"__esModule",{value:!0}),QT.Timeframe=void 0;const Ect=et,Act=Ze;class _ct extends Act.MalloyElement{constructor(e){super(),this.elementType="timeframe";let r=e.toLowerCase();r.endsWith("s")&&(r=r.slice(0,-1)),this.text=(0,Ect.isTimestampUnit)(r)?r:"second"}}QT.Timeframe=_ct;var lf={};Object.defineProperty(lf,"__esModule",{value:!0}),lf.ImportStatement=lf.ImportSelect=lf.ImportSourceName=void 0;const Rk=Ze;class vct extends Rk.MalloyElement{constructor(e){super(),this.text=e,this.elementType="importSourceName"}}lf.ImportSourceName=vct;class Cct extends Rk.MalloyElement{constructor(e,r){super(),this.text=e,this.from=r,this.elementType="importName",r&&this.has({from:r})}}lf.ImportSelect=Cct;class Sct extends Rk.ListOf{constructor(e,r){super([]),this.url=e,this.elementType="import statement";try{this.fullURL=decodeURI(new URL(e,r).toString())}catch{this.logError("invalid-import-url","Invalid URL in import statement")}}needs(){const e=this.translator();if(e&&this.fullURL&&e.root.importZone.getEntry(this.fullURL).status==="present"){const i=e.childRequest(this.fullURL);if(i)return i}}execute(e){const r=this.translator();if(!r)this.logError("no-translator-for-import","Cannot import without translation context");else if(this.fullURL){const i=r.root.pretranslatedModels.get(this.fullURL),s=r.root.importZone.getEntry(this.fullURL);if(i||s.status==="present"){const o=r.getChildExports(this.fullURL);if(this.notEmpty())for(const u of this.list){const a=u.from||u;if(e.getEntry(u.text))u.logError("name-conflict-on-selective-import",`Cannot redefine '${u.text}'`);else if(o[a.text]){const l={...o[a.text]};u.from&&(l.as=u.text),e.setEntry(u.text,{entry:l,exported:!1})}else a.logError("selective-import-not-found",`Cannot find '${a.text}', not imported`)}else for(const[u,a]of Object.entries(r.getChildExports(this.fullURL)))e.getEntry(u)?this.logError("name-conflict-on-indiscriminate-import",`Cannot redefine '${u}'`):e.setEntry(u,{entry:a,exported:!1})}else s.status==="error"?this.logError("failed-import",`import failed: '${s.message}'`):this.logError("failed-import",`import failed with status: '${s.status}'`)}}}lf.ImportStatement=Sct;var wE={};Object.defineProperty(wE,"__esModule",{value:!0}),wE.ExtendBlock=void 0;const bct=Ze,Tct=Wn;class Rct extends bct.ListOf{constructor(){super(...arguments),this.elementType="extendBlock",this.forceQueryClass=void 0,this.queryRefinementStage=Tct.LegalRefinementStage.Single}queryExecute(e){for(const r of this.list)for(const i of r.list)e.inputFS.extendSource(i)}}wE.ExtendBlock=Rct;var zT={};Object.defineProperty(zT,"__esModule",{value:!0}),zT.Argument=void 0;const Dct=Ze;class Oct extends Dct.MalloyElement{constructor(e){super({...e}),this.elementType="Argument",this.id=e.id,this.value=e.value}}zT.Argument=Oct;var WT={};Object.defineProperty(WT,"__esModule",{value:!0}),WT.HasParameter=void 0;const xce=et,wct=Ze;class Fct extends wct.MalloyElement{constructor(e){super(),this.elementType="hasParameter",this.name=e.name,e.type&&(0,xce.isCastType)(e.type)&&(this.type=e.type),e.default&&(this.default=e.default,this.has({default:this.default}))}parameter(){var e;if(this.default!==void 0){const r=this.default.constantValue();return this.type&&this.type!==r.type&&r.type!=="null"&&r.type!=="error"&&this.default.logError("parameter-default-does-not-match-declared-type",`Default value for parameter does not match declared type \`${this.type}\``),r.type==="null"?this.type?{type:this.type,value:r.value,name:this.name}:(this.default.logError("parameter-null-default-without-declared-type","Default value cannot have type `null` unless parameter type is also specified"),{value:r.value,name:this.name,type:"error"}):!(0,xce.isCastType)(r.type)&&r.type!=="error"?(this.default.logError("parameter-illegal-default-type",`Default value cannot have type \`${r.type}\``),{value:r.value,name:this.name,type:"error"}):{value:r.value,name:this.name,type:r.type}}return this.type===void 0&&this.logError("parameter-missing-default-or-type","Parameter must have default value or declared type"),{value:null,name:this.name,type:(e=this.type)!==null&&e!==void 0?e:"error"}}}WT.HasParameter=Fct;var GT={};Object.defineProperty(GT,"__esModule",{value:!0}),GT.AnonymousQuery=void 0;const Nct=Ze,Lct=zr;class Ict extends Nct.MalloyElement{constructor(e){super(),this.queryExpr=e,this.elementType="anonymousQuery",this.isNoteableObj=!0,this.extendNote=Lct.extendNoteMethod,this.has({queryExpr:e})}execute(e){const r=this.queryExpr.getQuery();if(!r){this.queryExpr.sqLog("non-query-used-as-query","Cannot run this object as a query");return}const i={...r.query()},s=this.note||{};i.annotation&&(s.inherits=i.annotation),(s.notes||s.blockNotes||s.inherits)&&(i.annotation=s),e.queryList.push(i)}}GT.AnonymousQuery=Ict;var cf={};Object.defineProperty(cf,"__esModule",{value:!0}),cf.View=void 0;const $ct=Ze;class Bct extends $ct.MalloyElement{pipeline(e,r){return this.pipelineComp(e,r).pipeline}}cf.View=Bct;var VT={};Object.defineProperty(VT,"__esModule",{value:!0}),VT.ViewArrow=void 0;const kct=Gr,Mct=cf;class Pct extends Mct.View{constructor(e,r){super({base:e,operation:r}),this.base=e,this.operation=r,this.elementType="viewArrow"}pipelineComp(e){const r=this.base.pipelineComp(e),i=new kct.StaticSourceSpace(r.outputStruct),s=this.operation.pipelineComp(i);return{pipeline:[...r.pipeline,...s.pipeline],outputStruct:s.outputStruct}}refine(e,r,i){return this.logError("refinement-with-multistage-view","A multi-segment view cannot be used as a refinement"),[]}getImplicitName(){return this.operation.getImplicitName()}}VT.ViewArrow=Pct;var YT={},FE={};Object.defineProperty(FE,"__esModule",{value:!0}),FE.refine=void 0;const Dk=Yi,Uct=dt,Ok=Kc;function jct(t,e,r){var i,s;if(e.length!==1)return t.logError("refinement-with-multistage-view","Named refinements of multi-stage views are not supported"),e;const o={...e[0]},u=r;if((0,Dk.isRawSegment)(o))t.logError("refinement-of-raw-query","Cannot refine raw query, must add an explicit query stage");else if(o.type==="partial"&&u.type!=="index"&&u.type!=="raw"?o.type=u.type:u.type!==o.type&&t.logError("mismatched-view-types-for-refinement",`cannot refine ${o.type} view with ${u.type} view`),u.type!=="index"&&o.type!=="index"&&u.type!=="raw"&&(u.orderBy!==void 0&&!u.defaultOrderBy&&(o.orderBy===void 0||o.defaultOrderBy?o.orderBy=u.orderBy:t.logError("ordering-overridden-in-refinement","refinement cannot override existing ordering")),u.limit!==void 0&&(o.limit===void 0?o.limit=u.limit:t.logError("limit-overridden-in-refinement","refinement cannot override existing limit"))),o.filterList=o.filterList!==void 0||u.filterList!==void 0?[...(i=o.filterList)!==null&&i!==void 0?i:[],...(s=u.filterList)!==null&&s!==void 0?s:[]]:void 0,(0,Dk.isQuerySegment)(u)&&(0,Dk.isQuerySegment)(o)){const a=[],l=[],c=new Map(o.queryFields.map(f=>[(0,Ok.nameFromDef)(f),f]));for(const f of u.queryFields)c.has((0,Ok.nameFromDef)(f))?a.push(f):l.push(f);o.queryFields=[...o.queryFields,...l],a.length>0&&t.logError("name-conflict-in-refinement",`overlapping fields in refinement: ${a.map(Ok.nameFromDef)}`),o.compositeFieldUsage=(0,Uct.mergeCompositeFieldUsage)(o.compositeFieldUsage,u.compositeFieldUsage)}else u.type==="index"&&o.type==="index"&&(o.indexFields=[...u.indexFields,...o.indexFields]);return[o]}FE.refine=jct,Object.defineProperty(YT,"__esModule",{value:!0}),YT.ViewRefine=void 0;const qct=yi,Hct=Gs,Qct=FE,zct=cf;class Wct extends zct.View{constructor(e,r){super({base:e,refinement:r}),this.base=e,this.refinement=r,this.elementType="refine"}pipelineComp(e,r){const i=this.base.pipelineComp(e),s=this.refinement.refine(e,i.pipeline,r);return{pipeline:s,annotation:i.annotation,outputStruct:s.length>0?(0,Hct.getFinalStruct)(this.refinement,e.structDef(),s):qct.ErrorFactory.structDef}}refine(e,r,i){const s=this.pipeline(e,i);return s.length!==1?(this.refinement.logError("refinement-with-multistage-view","refinement must have exactly one stage"),r):(0,Qct.refine)(this,r,s[0])}getImplicitName(){return this.base.getImplicitName()}}YT.ViewRefine=Wct;var KT={};Object.defineProperty(KT,"__esModule",{value:!0}),KT.ReferenceView=void 0;const wk=et,dce=yi,Gct=Gs,Vct=Wr,Yct=FE,Kct=cf;class Jct extends Kct.View{constructor(e){super({reference:e}),this.reference=e,this.elementType="reference-view"}pipelineComp(e,r){return this._pipelineComp(e)}_pipelineComp(e,{forRefinement:r}={forRefinement:!1}){const i=this.reference.getField(e),s=function(){return{inputStruct:dce.ErrorFactory.structDef,outputStruct:dce.ErrorFactory.structDef,pipeline:[],error:!0}};if(!i.found)return this.reference.logError(i.error.code,i.error.message),s();if(!(i.found instanceof Vct.SpaceField))throw new Error("Expected space field");const o=i.found.fieldDef();if(o===void 0)throw new Error("Expected field to have definition");if((0,wk.isAtomic)(o)){const u={type:"reduce",queryFields:[this.reference.refToField],compositeFieldUsage:o.compositeFieldUsage},a=this.reference.nameString,l={...(0,wk.sourceBase)(e.structDef()),type:"query_result",name:a,fields:[o]};return{pipeline:[u],name:a,outputStruct:l}}else return(0,wk.isTurtle)(o)?this.reference.list.length>1?(r?this.logError("refinement-with-joined-view","Cannot use view from join as refinement"):this.logError("nest-of-joined-view","Cannot use view from join"),s()):{pipeline:[...o.pipeline],name:o.name,annotation:o.annotation,outputStruct:(0,Gct.getFinalStruct)(this.reference,e.structDef(),o.pipeline)}:(r?this.reference.logError("refinement-with-source",`named refinement \`${this.reference.refString}\` must be a view, found a ${o.type}`):this.reference.logError("nest-of-source","This operation is not supported"),s())}getRefinementSegment(e){const{pipeline:r,error:i}=this._pipelineComp(e,{forRefinement:!0});if(!i){if(r.length!==1){this.reference.logError("refinement-with-multistage-view",`named refinement \`${this.reference.refString}\` must have exactly one stage`);return}return r[0]}}refine(e,r,i){const s=this.getRefinementSegment(e);return s?(0,Yct.refine)(this,r,s):r}getImplicitName(){return this.reference.nameString}}KT.ReferenceView=Jct;var JT={},NE={},XT={},LE={};Object.defineProperty(LE,"__esModule",{value:!0}),LE.Index=void 0;const Xct=Ze,Zct=Wn;class eft extends Xct.MalloyElement{constructor(e){super({fields:e}),this.fields=e,this.elementType="index",this.forceQueryClass=Zct.QueryClass.Index,this.queryRefinementStage=void 0}useWeight(e){this.has({weightBy:e}),this.weightBy=e}}LE.Index=eft;var IE={};Object.defineProperty(IE,"__esModule",{value:!0}),IE.SampleProperty=void 0;const tft=Ze,hce=Wn;class nft extends tft.MalloyElement{constructor(e){super(),this.sample=e,this.elementType="sampleProperty",this.queryRefinementStage=hce.LegalRefinementStage.Tail,this.forceQueryClass=hce.QueryClass.Index}sampling(){return this.sample}}IE.SampleProperty=nft;var ZT={};Object.defineProperty(ZT,"__esModule",{value:!0}),ZT.IndexFieldSpace=void 0;const pce=dt,mce=et,Fk=_t,rft=Wr,ift=Du,sft=xE,oft=Gr;class uft extends ift.QueryOperationSpace{constructor(){super(...arguments),this.segmentType="index"}pushFields(...e){for(const r of e)r instanceof Fk.FieldReference?super.pushFields(r):r instanceof Fk.WildcardFieldReference?this.addWild(r):r.logError("invalid-field-in-index-query","Internal error, not expected in index query")}getPipeSegment(e){if(e)return this.logError("refinement-of-index-segment","index query operations cannot be refined"),{type:"index",indexFields:[]};let r=(0,pce.emptyCompositeFieldUsage)(),i=(0,pce.emptyNarrowedCompositeFieldResolution)();const s=[],o=this.inputSpace().structDef();for(const[u,a]of this.entries())if(a instanceof rft.SpaceField){let l,c;const f=this.expandedWild[u];if(f)s.push({type:"fieldref",path:f.path}),l=f.entry.typeDesc().compositeFieldUsage;else if(a instanceof sft.ReferenceField){const h=a.fieldRef,p=h.getField(this.exprSpace);p.error?h.logError(p.error.code,p.error.message):(s.push(h.refToField),l=p.found.typeDesc().compositeFieldUsage,c=h)}const x=this.applyNextCompositeFieldUsage(o,r,i,l,c);r=x.compositeFieldUsage,i=x.narrowedCompositeFieldResolution}return this._compositeFieldUsage=r,{type:"index",indexFields:s}}addRefineFromFields(e){}addWild(e){var r;let i=this.exprSpace;const s=[];if(e.joinPath)for(const a of e.joinPath.list){const l=a.refString;s.push(l);const c=i.entry(l);if(c)if(c instanceof oft.StructSpaceField)i=c.fieldSpace;else{a.logError("invalid-wildcard-source",`Field '${l}' does not contain rows and cannot be expanded with '*'`);return}else{a.logError("wildcard-source-not-found",`No such field as '${l}'`);return}}const o=this.dialectObj(),u=[];for(const[a,l]of i.entries()){if(e.except.has(a)||l.refType==="parameter")continue;const c=Fk.IndexFieldReference.indexOutputName([...s,a]);if(this.entry(c)){const f=(r=this.expandedWild[c].path)===null||r===void 0?void 0:r.join(".");e.logError("name-conflict-in-wildcard-expansion",`Cannot expand '${a}' in '${e.refString}' because a field with that name already exists${f?` (conflicts with ${f})`:""}`)}else{const f=l.typeDesc();mce.TD.isLeafAtomic(f)&&(0,mce.expressionIsScalar)(f.expressionType)&&(o===void 0||!o.ignoreInProject(a))&&(u.push({name:c,entry:l}),this.expandedWild[c]={path:s.concat(a),entry:l})}}for(const a of u.sort((l,c)=>l.name.localeCompare(c.name)))this.setEntry(a.name,a.entry)}}ZT.IndexFieldSpace=uft,Object.defineProperty(XT,"__esModule",{value:!0}),XT.IndexBuilder=void 0;const Nk=et,aft=yi,lft=Ha,cft=LE,fft=sf,xft=IE,dft=ZT,Lk=dt;class hft{constructor(e,r,i,s){this.filters=[],this.alwaysJoins=[],this.type="index",this.resultFS=new dft.IndexFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e instanceof lft.Filter?e.queryExecute(this):e instanceof fft.Limit?(this.limit&&this.limit.logError("index-limit-already-specified","Ignored, too many limit: statements"),this.limit=e):e instanceof cft.Index?(this.resultFS.pushFields(...e.fields.list),e.weightBy&&(this.indexOn&&this.indexOn.logError("index-by-already-specified","Ignoring previous BY"),this.indexOn=e.weightBy)):e instanceof xft.SampleProperty?this.sample=e.sampling():e.logError("illegal-operation-for-index","Not legal in an index query operation")}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}finalize(e){var r;if(e&&!(0,Nk.isIndexSegment)(e)&&!(0,Nk.isPartialSegment)(e))return this.resultFS.logError("refinement-of-index-segment",`Can't refine index with ${e.type}`),aft.ErrorFactory.indexSegment;const i=this.resultFS.getPipeSegment(e),s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?i.filterList=this.filters:s&&(i.filterList=[...s,...this.filters]),e!=null&&e.limit&&(i.limit=e.limit),this.limit&&(i.limit=this.limit.limit),this.indexOn&&(i.weightMeasure=this.indexOn.refString),e&&(0,Nk.isIndexSegment)(e)&&(e!=null&&e.sample)&&(i.sample=e.sample),this.sample&&(i.sample=this.sample),this.alwaysJoins.length>0&&(i.alwaysJoins=[...this.alwaysJoins]);const o=e&&e.type==="index"&&(r=e.compositeFieldUsage)!==null&&r!==void 0?r:(0,Lk.emptyCompositeFieldUsage)();return i.compositeFieldUsage=(0,Lk.mergeCompositeFieldUsage)(o,this.compositeFieldUsage),i}}XT.IndexBuilder=hft;var eR={},$E={};Object.defineProperty($E,"__esModule",{value:!0}),$E.GroupBy=void 0;const pft=Ws,gce=Wn;class mft extends pft.DefinitionList{constructor(){super(...arguments),this.elementType="groupBy",this.queryRefinementStage=gce.LegalRefinementStage.Single,this.forceQueryClass=gce.QueryClass.Grouping}}$E.GroupBy=mft;var tR={};Object.defineProperty(tR,"__esModule",{value:!0}),tR.ProjectFieldSpace=void 0;const nR=et,gft=Du;class yft extends gft.QuerySpace{constructor(){super(...arguments),this.segmentType="project"}canContain(e){return e===void 0||!nR.TD.isAtomic(e)||(0,nR.expressionIsAggregate)(e.expressionType)?!1:(0,nR.expressionInvolvesAggregate)(e.expressionType)&&(0,nR.expressionIsAnalytic)(e.expressionType)?(this.logError("aggregate-analytic-in-select","Cannot add aggregate analyics to select"),!1):!0}}tR.ProjectFieldSpace=yft;var ff={},Fd={};Object.defineProperty(Fd,"__esModule",{value:!0}),Fd.Ordering=Fd.OrderBy=void 0;const Eft=et,yce=of,Ece=Ze,Aft=Wn;class _ft extends Ece.MalloyElement{constructor(e,r){super(),this.field=e,this.dir=r,this.elementType="orderBy",e instanceof yce.FieldName&&this.has({field:e})}get modelField(){return typeof this.field=="number"?this.field:this.field.refString}getOrderBy(e){var r;if(this.field instanceof yce.FieldName&&e.isQueryFieldSpace()){const s=e.outputSpace(),o=this.field.getField(s);o.error&&this.field.logError(o.error.code,o.error.message),(!o.found||!o.isOutputField)&&this.logError("order-by-not-found-in-output",`Unknown field ${this.field.refString} in output space`),(0,Eft.expressionIsAnalytic)((r=o.found)===null||r===void 0?void 0:r.typeDesc().expressionType)&&this.logError("order-by-analytic",`Illegal order by of analytic field ${this.field.refString}`)}const i={field:this.modelField};return this.dir&&(i.dir=this.dir),i}}Fd.OrderBy=_ft;class vft extends Ece.ListOf{constructor(e){super(e),this.elementType="ordering",this.queryRefinementStage=Aft.LegalRefinementStage.Tail,this.forceQueryClass=void 0}getOrderBy(e){return this.list.map(r=>r.getOrderBy(e))}}Fd.Ordering=vft,Object.defineProperty(ff,"__esModule",{value:!0}),ff.ReduceBuilder=ff.QuerySegmentBuilder=void 0;const Ou=et,Cft=yi,Sft=of,bft=sf,Tft=Fd,Rft=Du,Dft=Ws,Ik=dt;function Ace(t){return t.type==="fieldref"?t.path[t.path.length-1]:t.name}class _ce{constructor(){this.alwaysJoins=[],this.filters=[]}execute(e){if(e.queryExecute){e.queryExecute(this);return}e instanceof Dft.DefinitionList?this.resultFS.pushFields(...e.list):e instanceof bft.Limit?this.limit?e.logError("limit-already-specified","Query operation already limited"):this.limit=e.limit:e instanceof Tft.Ordering&&(this.order?e.logError("ordering-already-specified","Query operation already sorted"):this.order=e)}get compositeFieldUsage(){return this.resultFS.compositeFieldUsage}refineFrom(e,r){var i;e&&e.type!=="index"&&e.type!=="raw"&&(!this.limit&&e.orderBy&&!e.defaultOrderBy&&(r.orderBy=e.orderBy),!this.limit&&e.limit&&(r.limit=e.limit)),this.order&&(r.orderBy=this.order.getOrderBy(this.inputFS),delete r.defaultOrderBy),this.limit&&(r.limit=this.limit);const s=(e==null?void 0:e.filterList)||[];this.filters.length>0&&!s?r.filterList=this.filters:s&&(r.filterList=[...s,...this.filters]),this.alwaysJoins.length>0&&(r.alwaysJoins=[...this.alwaysJoins]);const o=e&&(0,Ou.isQuerySegment)(e)&&(i=e.compositeFieldUsage)!==null&&i!==void 0?i:(0,Ik.emptyCompositeFieldUsage)();r.compositeFieldUsage=(0,Ik.mergeCompositeFieldUsage)(o,this.compositeFieldUsage)}}ff.QuerySegmentBuilder=_ce;class Oft extends _ce{constructor(e,r,i,s){super(),this.type="grouping",this.resultFS=new Rft.ReduceFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}finalize(e){let r;if(e)if((0,Ou.isReduceSegment)(e)||(0,Ou.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-reduce-refinement",`Can't refine reduce with ${e.type}`),Cft.ErrorFactory.reduceSegment;const i=this.resultFS.getQuerySegment(r);if(this.refineFrom(r,i),i.orderBy){for(const s of i.orderBy)if(typeof s.field=="number"){const o=i.queryFields[s.field-1];s.field=Ace(o)}}if(i.orderBy===void 0||i.defaultOrderBy){let s;for(const o of i.queryFields){let u=!1,a=!1,l;const c=Ace(o);if(o.type==="fieldref"){const f=o.path.map(h=>new Sft.FieldName(h)),x=this.inputFS.lookup(f).found;if(x){const h=x.typeDesc();l=h.type,u=(0,Ou.expressionIsAggregate)(h.expressionType),a=(0,Ou.expressionIsAnalytic)(h.expressionType)}else continue}else l=o.type,u=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAggregate)(o.expressionType),a=(0,Ou.hasExpression)(o)&&(0,Ou.expressionIsAnalytic)(o.expressionType);if((0,Ou.isTemporalType)(l)||u){i.defaultOrderBy=!0,i.orderBy=[{field:c,dir:"desc"}],s=void 0;break}(0,Ou.canOrderBy)(l)&&!a&&!s&&(s=c)}s&&(i.defaultOrderBy=!0,i.orderBy=[{field:s,dir:"asc"}])}return i}}ff.ReduceBuilder=Oft,Object.defineProperty(eR,"__esModule",{value:!0}),eR.ProjectBuilder=void 0;const vce=et,wft=yi,Fft=$E,Nft=tR,Lft=ff;class Ift extends Lft.QuerySegmentBuilder{constructor(e,r,i,s){super(),this.type="project",this.resultFS=new Nft.ProjectFieldSpace(e,r,i,s),this.inputFS=this.resultFS.inputSpace()}execute(e){e.elementType==="having"||e instanceof Fft.GroupBy?e.logError("illegal-operation-in-select-segment","Illegal statement in a select query operation"):super.execute(e)}finalize(e){let r;if(e)if((0,vce.isProjectSegment)(e)||(0,vce.isPartialSegment)(e))r=e;else return this.resultFS.logError("incompatible-segment-for-select-refinement",`Can't refine select with ${e.type}`),wft.ErrorFactory.projectSegment;const i=this.resultFS.getQuerySegment(r);return this.refineFrom(r,i),i}}eR.ProjectBuilder=Ift;var rR={};Object.defineProperty(rR,"__esModule",{value:!0}),rR.PartialBuilder=void 0;const $ft=Yi,Bft=ff;class kft extends Bft.ReduceBuilder{finalize(e){const r=super.finalize(e);if((0,$ft.isQuerySegment)(r))return{...r,type:"partial"};throw new Error(`Partial Builder cannot finalize from ${r.type}`)}}rR.PartialBuilder=kft,Object.defineProperty(NE,"__esModule",{value:!0}),NE.QOpDesc=void 0;const Mft=XT,Pft=eR,Uft=ff,jft=Ze,qft=Gs,Hft=Gr,Nd=Wn,Qft=rR;class zft extends jft.ListOf{constructor(){super(...arguments),this.elementType="queryOperation"}computeType(){var e;let r,i=!1;this.refineThis&&(this.refineThis.type==="reduce"?r=Nd.QueryClass.Grouping:this.refineThis.type==="project"?r=Nd.QueryClass.Project:this.refineThis.type==="index"&&(r=Nd.QueryClass.Index));for(const s of this.list)s.forceQueryClass&&(r?r!==s.forceQueryClass&&s.logError(`illegal-${r}-operation`,`Not legal in ${r} query`):r=s.forceQueryClass),i||(i=(e=s.needsExplicitQueryClass)!==null&&e!==void 0?e:!1);return r===void 0&&i&&(this.logError("ambiguous-view-type",{}),r=Nd.QueryClass.Project),this.opClass=r,r}refineFrom(e){this.refineThis=e}getBuilder(e,r,i){switch(this.computeType()){case Nd.QueryClass.Grouping:return new Uft.ReduceBuilder(e,this.refineThis,r,i);case Nd.QueryClass.Project:return new Pft.ProjectBuilder(e,this.refineThis,r,i);case Nd.QueryClass.Index:return new Mft.IndexBuilder(e,this.refineThis,r,i);case void 0:return new Qft.PartialBuilder(e,this.refineThis,r,i)}}getOp(e,r){const i=this.getBuilder(e,r,this);for(const o of this.list)i.execute(o);const s=i.finalize(this.refineThis);return{segment:s,outputSpace:()=>new Hft.StaticSourceSpace((0,qft.opOutputStruct)(this,e.structDef(),s))}}}NE.QOpDesc=zft,Object.defineProperty(JT,"__esModule",{value:!0}),JT.QOpDescView=void 0;const Wft=et,Gft=Gr,Cce=NE,Vft=Gs,$k=Wn,Yft=cf;class Kft extends Yft.View{constructor(e){super({operation:e}),this.operation=e,this.elementType="qopdesc-view"}pipelineComp(e,r){const i=this.operation.getOp(e,r);return{pipeline:[i.segment],outputStruct:i.outputSpace().structDef()}}getOp(e,r,i,s){return(0,Wft.isRawSegment)(s)?(this.logError("refinement-of-raw-query","A raw query cannot be refined"),s):(i.refineFrom(s),i.getOp(e,r).segment)}refine(e,r,i){const s=[...r];if(s.length===0)return s;if(s.length===1)return this.operation.refineFrom(s[0]),[this.getOp(e,i,this.operation,s[0])];const o=new Cce.QOpDesc([]),u=new Cce.QOpDesc([]);for(const a of this.operation.list)switch(a.queryRefinementStage){case $k.LegalRefinementStage.Head:o.push(a);break;case $k.LegalRefinementStage.Single:a.logError("illegal-multistage-refinement-operation","Illegal in refinement of a query with more than one stage");break;case $k.LegalRefinementStage.Tail:u.push(a);break;default:a.logError("illegal-refinement-operation","Illegal query refinement")}if(o.notEmpty()&&(this.has({headRefinements:o}),s[0]=this.getOp(e,void 0,o,s[0])),u.notEmpty()){const a=s.length-1;this.has({tailRefinements:u});const l=(0,Vft.getFinalStruct)(this,e.structDef(),s.slice(-1));s[a]=this.getOp(new Gft.StaticSourceSpace(l),void 0,u,s[a])}return s}getImplicitName(){}}JT.QOpDescView=Kft;var Nn={},Jft=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Xft=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Zft=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Jft(e,t,r);return Xft(e,t),e};Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.FieldDefinitionValue=Nn.DefSpace=Nn.DimensionFieldDeclaration=Nn.MeasureFieldDeclaration=Nn.DeclareFieldDeclaration=Nn.ProjectFieldDeclaration=Nn.GroupByFieldDeclaration=Nn.AggregateFieldDeclaration=Nn.CalculateFieldDeclaration=Nn.AtomicFieldDeclaration=void 0;const Bk=et,Sce=Zft(nn),ext=U2,txt=Ze,Ld=lr,nxt=zr,rxt=Wr;class xf extends txt.MalloyElement{constructor(e,r,i){super({expr:e}),this.expr=e,this.defineName=r,this.exprSrc=i,this.isNoteableObj=!0,this.extendNote=nxt.extendNoteMethod}getName(){return this.defineName}fieldDef(e,r){return this.queryFieldDef(new kk(e,this),r)}executesInOutputSpace(){return!1}queryFieldDef(e,r){let i;function s(){if(e.isQueryFieldSpace())return e.outputSpace();throw new Error("must be in a query -- weird internal error")}try{const u=this.executesInOutputSpace()?s():e;i=this.expr.getExpression(u)}catch(u){return this.logError("failed-field-definition",`Cannot define '${r}', ${u.message}`),{name:r,type:"error"}}if(i.type==="null"&&(this.expr.logWarning("null-typed-field-definition",'null value defaults to type number, use "null::TYPE" to specify correct type'),i={type:"number",value:i.value,expressionType:i.expressionType,evalSpace:i.evalSpace,compositeFieldUsage:i.compositeFieldUsage}),(0,Bk.isAtomicFieldType)(i.type)&&i.type!=="error"){this.typecheckExprValue(i);const u=(0,Bk.mkFieldDef)(Sce.atomicDef(i),r);return(u.type==="date"||u.type==="timestamp")&&(0,ext.isGranularResult)(i)&&(u.timeframe=i.timeframe),u.location=this.location,u.e=i.value,u.compositeFieldUsage=i.compositeFieldUsage,i.expressionType&&(u.expressionType=i.expressionType),this.exprSrc&&(u.code=this.exprSrc),this.note&&(u.annotation=this.note),u}if(!(e instanceof kk&&e.foundCircle)&&i.type!=="error"){const u=Sce.inspect(i);this.logError("invalid-type-for-field-definition",`Cannot define '${r}', unexpected type: ${u}`)}return{name:r,type:"error"}}makeEntry(e){e.newEntry(this.defineName,this,new bce(e,this))}}Nn.AtomicFieldDeclaration=xf;class ixt extends xf{constructor(){super(...arguments),this.elementType="calculateFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckCalculate)(e,this)}executesInOutputSpace(){return!0}}Nn.CalculateFieldDeclaration=ixt;class sxt extends xf{constructor(){super(...arguments),this.elementType="aggregateFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckAggregate)(e,this)}}Nn.AggregateFieldDeclaration=sxt;class oxt extends xf{constructor(){super(...arguments),this.elementType="groupByFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckGroupBy)(e,this)}}Nn.GroupByFieldDeclaration=oxt;class uxt extends xf{constructor(){super(...arguments),this.elementType="projectFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckProject)(e,this)}}Nn.ProjectFieldDeclaration=uxt;class axt extends xf{constructor(){super(...arguments),this.elementType="declareFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckDeclare)(e,this)}}Nn.DeclareFieldDeclaration=axt;class lxt extends xf{constructor(){super(...arguments),this.elementType="measureFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckMeasure)(e,this)}}Nn.MeasureFieldDeclaration=lxt;class cxt extends xf{constructor(){super(...arguments),this.elementType="dimensionFieldDeclaration"}typecheckExprValue(e){(0,Ld.typecheckDimension)(e,this)}}Nn.DimensionFieldDeclaration=cxt;class kk{constructor(e,r){this.realFS=e,this.circular=r,this.type="fieldSpace",this.foundCircle=!1}structDef(){return this.realFS.structDef()}emptyStructDef(){return this.realFS.emptyStructDef()}entry(e){return this.realFS.entry(e)}lookup(e){return e[0]&&e[0].refString===this.circular.defineName?(this.foundCircle=!0,{error:{message:`Circular reference to '${this.circular.defineName}' in definition`,code:"circular-reference-in-field-definition"},found:void 0}):this.realFS.lookup(e)}entries(){return this.realFS.entries()}dialectName(){return this.realFS.dialectName()}dialectObj(){return this.realFS.dialectObj()}isQueryFieldSpace(){return this.realFS.isQueryFieldSpace()}outputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.outputSpace();throw new Error("Not a query field space")}inputSpace(){if(this.realFS.isQueryFieldSpace())return this.realFS.inputSpace();throw new Error("Not a query field space")}isProtectedAccessSpace(){return!0}}Nn.DefSpace=kk;class bce extends rxt.SpaceField{constructor(e,r){super(),this.space=e,this.exprDef=r,this.fieldName=r.defineName}get name(){return this.fieldName}fieldDef(){var e;const r=(e=this.defInSource)!==null&&e!==void 0?e:this.exprDef.fieldDef(this.space,this.name);return this.defInSource=r,r}getQueryFieldDef(e){if(!this.defInQuery){const r=this.exprDef.queryFieldDef(e,this.name);this.defInQuery=r}return this.defInQuery}typeDesc(){const e=this.defInQuery||this.fieldDef();if((0,Bk.isAtomic)(e))return this.fieldTypeFromFieldDef(e);throw new Error(`Can't get typeDesc for ${e.type}`)}entryType(){return(this.defInQuery||this.fieldDef()).type}}Nn.FieldDefinitionValue=bce;var iR={};Object.defineProperty(iR,"__esModule",{value:!0}),iR.Aggregate=void 0;const fxt=Ws,Tce=Wn;class xxt extends fxt.DefinitionList{constructor(){super(...arguments),this.elementType="aggregateList",this.queryRefinementStage=Tce.LegalRefinementStage.Single,this.forceQueryClass=Tce.QueryClass.Grouping}}iR.Aggregate=xxt;var sR={};Object.defineProperty(sR,"__esModule",{value:!0}),sR.Calculate=void 0;const dxt=Ws,hxt=Wn;class pxt extends dxt.DefinitionList{constructor(){super(...arguments),this.elementType="calculate",this.forceQueryClass=void 0,this.needsExplicitQueryClass=!0,this.queryRefinementStage=hxt.LegalRefinementStage.Single}}sR.Calculate=pxt;var BE={};Object.defineProperty(BE,"__esModule",{value:!0}),BE.Dimensions=void 0;const mxt=Jc;class gxt extends mxt.DeclareFields{constructor(){super(...arguments),this.elementType="dimensionList"}}BE.Dimensions=gxt;var kE={};Object.defineProperty(kE,"__esModule",{value:!0}),kE.Measures=void 0;const yxt=Jc;class Ext extends yxt.DeclareFields{constructor(){super(...arguments),this.elementType="measureList"}}kE.Measures=Ext;var oR={};Object.defineProperty(oR,"__esModule",{value:!0}),oR.Nests=void 0;const Axt=Ws,Rce=Wn;class _xt extends Axt.DefinitionList{constructor(e){super(e),this.elementType="nestedQueries",this.queryRefinementStage=Rce.LegalRefinementStage.Single,this.forceQueryClass=Rce.QueryClass.Grouping}}oR.Nests=_xt;var uR={};Object.defineProperty(uR,"__esModule",{value:!0}),uR.ProjectStatement=void 0;const vxt=Ws,Dce=Wn;class Cxt extends vxt.DefinitionList{constructor(){super(...arguments),this.elementType="projectStatement",this.forceQueryClass=Dce.QueryClass.Project,this.queryRefinementStage=Dce.LegalRefinementStage.Single}queryExecute(e){e.type==="project"&&e.resultFS.pushFields(...this.list)}}uR.ProjectStatement=Cxt;var df={},_0={},Un={};Object.defineProperty(Un,"__esModule",{value:!0}),Un.getPlainString=Un.unIndent=Un.getOptionalId=Un.idToStr=Un.getId=Un.getStringParts=Un.getStringIfShort=Un.getShortString=void 0;const Oce=$o;function wce(t){var e,r;const i=((e=t.DQ_STRING())===null||e===void 0?void 0:e.text)||((r=t.SQ_STRING())===null||r===void 0?void 0:r.text);return i?Oce.ParseUtil.parseString(i,i[0]):""}Un.getShortString=wce;function Fce(t){const e=t.string().shortString();if(e)return wce(e)}Un.getStringIfShort=Fce;function*Nce(t){var e;if(t){for(const i of t.sqlInterpolation()){const s=i.OPEN_CODE().text;s.length>2&&(yield s.slice(0,s.length-2)),i.sqExpr()&&(yield i.sqExpr())}const r=(e=t.SQL_END())===null||e===void 0?void 0:e.text.slice(0,-3);r&&r.length>0&&(yield r)}}Un.getStringParts=Nce;function Lce(t){return Ice(t.id())}Un.getId=Lce;function Ice(t){const e=t.BQ_STRING();return e?Oce.ParseUtil.parseString(e.text,"`"):t.text}Un.idToStr=Ice;function Sxt(t){function e(r){return"id"in r}if(e(t)&&t.id())return Lce(t)}Un.getOptionalId=Sxt;function*$ce(t){for(;t.length>0;){const e=t.match(/^.*?\r?\n/);let r=t;e&&(r=e[0]),yield r,t=t.slice(r.length)}}function bxt(t){let e;for(const r of $ce(t)){const i=r.match(/^( *).*[^\s]/);if(i){const s=i[1].length;(e===void 0||s<e)&&(e=s)}}return e}function Bce(t){let e;for(const r of t)if(typeof r=="string"){const i=bxt(r);i!==void 0&&(e===void 0||i<e)&&(e=i)}if(e)for(let r=0;r<=t.length;r+=1){const i=t[r];if(typeof i=="string"){let s="";for(let o of $ce(i))o[0]===" "&&(o=o.slice(e)),s+=o;t[r]=s}}}Un.unIndent=Bce;function Txt(t,e=!1){const r=[],i=Fce(t);if(i)return[i,r];const s=[],o=t.string().sqlString();if(o){for(const u of Nce(o))if(typeof u=="string")s.push(u);else if(r.push(u),e)return[void 0,r];return Bce(s),[s.join(""),r]}return["",r]}Un.getPlainString=Txt,Object.defineProperty(_0,"__esModule",{value:!0}),_0.findReferences=_0.deprecatedParseTableURI=_0.constructTableKey=void 0;const Rxt=R0,Mk=Un;function Pk(t){const e=(0,Mk.getStringIfShort)(t);if(e)return e;const r=[],i=t.string().sqlString();if(i){for(const s of(0,Mk.getStringParts)(i))typeof s=="string"&&r.push(s);return r.join("")}return""}class Dxt{constructor(e,r){this.trans=e,this.tokens=r,this.needTables={},this.needImports={}}registerTableReference(e,r,i){const s=kce(e,r);this.needTables[s]||(this.needTables[s]={connectionName:e,tablePath:r,firstReference:i})}enterTableMethod(e){const r=(0,Mk.getId)(e.connectionId()),i=Pk(e.tablePath()),s=this.trans.rangeFromContext(e);this.registerTableReference(r,i,s)}enterTableFunction(e){const r=Pk(e.tableURI()),{connectionName:i,tablePath:s}=Mce(r),o=this.trans.rangeFromContext(e);this.registerTableReference(i,s,o)}enterImportURL(e){const r=Pk(e);this.needImports[r]||(this.needImports[r]=this.trans.rangeFromContext(e))}}function kce(t,e){return t===void 0?e:`${t}:${e}`}_0.constructTableKey=kce;function Mce(t){const e=t.match(/^([^:]*):(.*)$/);if(e){const[,r,i]=e;return{connectionName:r,tablePath:i}}else return{tablePath:t}}_0.deprecatedParseTableURI=Mce;function Oxt(t,e,r){const i=new Dxt(t,e),s=i;return Rxt.ParseTreeWalker.DEFAULT.walk(s,r),{tables:i.needTables,urls:i.needImports}}_0.findReferences=Oxt,Object.defineProperty(df,"__esModule",{value:!0}),df.TableFunctionSource=df.TableMethodSource=df.TableSource=void 0;const Pce=_0,wxt=Ro,Uce=yi;class Uk extends wxt.Source{getSourceDef(){var e,r,i;const s=this.getTableInfo();if(s===void 0)return Uce.ErrorFactory.structDef;const{tablePath:o,connectionName:u}=s,a=(0,Pce.constructTableKey)(u,o),l=(e=this.translator())===null||e===void 0?void 0:e.root.schemaZone.getEntry(a);let c=`Schema read failure for table '${o}' for connection '${u}'`;if(l){if(l.status==="present"){(r=this.document())===null||r===void 0||r.checkExperimentalDialect(this,l.value.dialect),l.value.location=this.location,l.value.fields.forEach(x=>{x.location=this.location});const f={...l.value,fields:l.value.fields.map(x=>({...x,location:this.location})),location:this.location};return(i=this.document())===null||i===void 0||i.rememberToAddModelAnnotations(f),f}l.status==="error"&&(c=l.message)}return this.logError("failed-to-fetch-table-schema",c),Uce.ErrorFactory.structDef}}df.TableSource=Uk;class Fxt extends Uk{constructor(e,r){super(),this.connectionName=e,this.tablePath=r,this.elementType="tableMethodSource",this.has({connectionName:e})}getTableInfo(){var e;const r=this.modelEntry(this.connectionName),i=this.connectionName.refString;if(r===void 0)(e=this.namespace())===null||e===void 0||e.setEntry(i,{entry:{type:"connection",name:i},exported:!0},!0);else if(r.entry.type!=="connection"){this.connectionName.logError("invalid-connection-for-table-source",`${this.connectionName.refString} is not a connection`);return}return{tablePath:this.tablePath,connectionName:this.connectionName.refString}}}df.TableMethodSource=Fxt;class Nxt extends Uk{constructor(e){super(),this.tableURI=e,this.elementType="tableFunctionSource"}getTableInfo(){return(0,Pce.deprecatedParseTableURI)(this.tableURI)}}df.TableFunctionSource=Nxt;var aR={};Object.defineProperty(aR,"__esModule",{value:!0}),aR.SQLString=void 0;const Lxt=Ze,jce=Tu;class Ixt extends Lxt.MalloyElement{constructor(){super(...arguments),this.elementType="sqlString",this.elements=[],this.containsQueries=!1}complete(){this.has({queries:this.elements.filter($xt)})}push(e){typeof e=="string"?e.length>0&&this.elements.push(e):e instanceof jce.SourceQueryElement?(this.elements.push(e),this.containsQueries=!0,e.parent=this):e.logError("invalid-sql-source-interpolation","This element is not legal inside an SQL string")}sqlPhrases(){const e=[];for(const r of this.elements)if(typeof r=="string")e.push({sql:r});else{const i=r.getQuery();i?e.push(i.query()):r.sqLog("failed-to-expand-sql-source","Cannot expand into a query")}return e}}aR.SQLString=Ixt;function $xt(t){return t instanceof jce.SourceQueryElement}var lR={};Object.defineProperty(lR,"__esModule",{value:!0}),lR.SourceDesc=void 0;const Bxt=Ze;class kxt extends Bxt.ListOf{constructor(){super(...arguments),this.elementType="sourceDescription"}}lR.SourceDesc=kxt;var cR={};Object.defineProperty(cR,"__esModule",{value:!0}),cR.isSourceProperty=void 0;const Mxt=Ha,Pxt=Jc,Uxt=L2,jxt=Zc,qxt=I2,Hxt=$2,Qxt=B2,zxt=Xc,Wxt=As;function Gxt(t){return t instanceof Mxt.Filter||t instanceof Wxt.JoinStatement||t instanceof Pxt.DeclareFields||t instanceof Uxt.FieldListEdit||t instanceof jxt.Renames||t instanceof qxt.PrimaryKey||t instanceof zxt.ObjectAnnotation||t instanceof Hxt.Views||t instanceof Qxt.TimezoneStatement}cR.isSourceProperty=Gxt;var fR={};Object.defineProperty(fR,"__esModule",{value:!0}),fR.isFieldCollectionMember=void 0;const Vxt=Nn,qce=_t;function Yxt(t){return t instanceof qce.FieldReference||t instanceof qce.WildcardFieldReference||t instanceof Vxt.AtomicFieldDeclaration}fR.isFieldCollectionMember=Yxt;var xR={};Object.defineProperty(xR,"__esModule",{value:!0}),xR.isQueryElement=void 0;const Kxt=k2,Jxt=M2,Xxt=EE,Zxt=AE;function edt(t){return t instanceof Kxt.QueryArrow||t instanceof Jxt.QueryRefine||t instanceof Xxt.QueryReference||t instanceof Zxt.QueryRaw}xR.isQueryElement=edt;var Hce={};Object.defineProperty(Hce,"__esModule",{value:!0});var dR={};Object.defineProperty(dR,"__esModule",{value:!0}),dR.isQueryProperty=void 0;function tdt(t){return"queryRefinementStage"in t&&"forceQueryClass"in t}dR.isQueryProperty=tdt;var hR={};Object.defineProperty(hR,"__esModule",{value:!0}),hR.isQueryExtendProperty=void 0;const ndt=BE,rdt=As,idt=kE;function sdt(t){return t instanceof ndt.Dimensions||t instanceof idt.Measures||t instanceof rdt.JoinStatement}hR.isQueryExtendProperty=sdt;var pR={};Object.defineProperty(pR,"__esModule",{value:!0}),pR.isFieldPropStatement=void 0;const odt=rf,udt=Ha,adt=sf,ldt=z2;function cdt(t){return t instanceof udt.Filter||t instanceof adt.Limit||t instanceof ldt.PartitionBy||t instanceof odt.FunctionOrdering}pR.isFieldPropStatement=cdt,function(t){var e=T&&T.__createBinding||(Object.create?function(i,s,o,u){u===void 0&&(u=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,u,a)}:function(i,s,o,u){u===void 0&&(u=o),i[u]=s[o]}),r=T&&T.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(t,"__esModule",{value:!0}),r(iE,t),r(D2,t),r(O2,t),r(Ro,t),r(uE,t),r(Tu,t),r(Y4,t),r(K4,t),r(Z4,t),r(hE,t),r(eT,t),r(tT,t),r(bu,t),r(L2,t),r(I2,t),r(Zc,t),r($2,t),r(B2,t),r(rT,t),r(q2,t),r(sT,t),r(rf,t),r(oT,t),r(E0,t),r(uT,t),r(Q2,t),r(aT,t),r(lT,t),r(cT,t),r(y0,t),r(fT,t),r(xT,t),r(hT,t),r(TE,t),r(SE,t),r(Rd,t),r(mT,t),r(gT,t),r(ET,t),r(_T,t),r(vT,t),r(CT,t),r(ST,t),r(uf,t),r(TT,t),r(RT,t),r(DT,t),r(wT,t),r(FT,t),r(NT,t),r(LT,t),r($T,t),r(MT,t),r(wr,t),r(jT,t),r(z2,t),r(G2,t),r(Y2,t),r(HT,t),r(wd,t),r(nf,t),r(QT,t),r(RE,t),r(lf,t),r(wE,t),r(zT,t),r(WT,t),r(GT,t),r(M2,t),r(k2,t),r(cf,t),r(VT,t),r(YT,t),r(KT,t),r(JT,t),r(Nn,t),r(_t,t),r(iR,t),r(sR,t),r(Jc,t),r(BE,t),r(wE,t),r(Ha,t),r($E,t),r(LE,t),r(As,t),r(sE,t),r(sf,t),r(kE,t),r(iE,t),r(oR,t),r(Fd,t),r(uR,t),r(NE,t),r(IE,t),r(P2,t),r(Td,t),r(_E,t),r(df,t),r(aR,t),r(Xc,t),r(Ru,t),r(lR,t),r(cR,t),r(pt,t),r(fR,t),r(of,t),r(Ze,t),r(xR,t),r(Hce,t),r(dR,t),r(hR,t),r(pR,t)}(q4);var mR={},J2={};Object.defineProperty(J2,"__esModule",{value:!0}),J2.ConstantExpression=J2.ConstantFieldSpace=void 0;const fdt=pt;class Qce{constructor(){this.type="fieldSpace"}structDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}emptyStructDef(){throw new Error("ConstantFieldSpace cannot generate a structDef")}lookup(e){return{error:{message:"Only constants allowed in parameter default values",code:"illegal-reference-in-parameter-default"},found:void 0}}entries(){return[]}entry(){}dialectName(){return"~constant-space-unknown-dialect~"}dialectObj(){}isQueryFieldSpace(){return!1}isProtectedAccessSpace(){return!1}}J2.ConstantFieldSpace=Qce;class xdt extends fdt.ExpressionDef{constructor(e){super({expr:e}),this.expr=e,this.elementType="constantExpression"}getExpression(e){return this.constantValue()}get constantFs(){return this.cfs||(this.cfs=new Qce),this.cfs}constantValue(){return this.expr.getExpression(this.constantFs)}apply(e,r,i){return this.expr.apply(e,r,i)}requestExpression(e){return this.expr.requestExpression(e)}}J2.ConstantExpression=xdt;var ddt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),hdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),pdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&ddt(e,t,r);return hdt(e,t),e};Object.defineProperty(mR,"__esModule",{value:!0}),mR.MalloyToAST=void 0;const zce=tg,mdt=Hd,ue=pdt(q4),jk=b2,Wce=xr,gdt=q4,Xn=Un,qk=et,ydt=$o,Edt=J2,Gce=Jn;class Vce extends ue.SourceQueryElement{constructor(){super(...arguments),this.elementType="parseErrorSourceQuery"}}class Hk extends ue.MalloyElement{constructor(e){super(),this.elementType="ignoredByParser",this.malloySrc=e}}const Adt=["##! m4warnings=error"];class _dt extends mdt.AbstractParseTreeVisitor{constructor(e,r,i){super(),this.parseInfo=e,this.msgLog=r,this.compilerFlags=i;for(const s of Adt){const o=ydt.Tag.fromTagLine(s,0,this.compilerFlags);this.compilerFlags=o.tag}}internalError(e,r){return this.contextError(e,"internal-translator-error",{message:r}),new Error(`Internal Translator Error: ${r}`)}astError(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(r,i,{at:e.location,...s}))}rangeFromContext(e){return(0,Gce.rangeFromContext)(this.parseInfo.sourceInfo,e)}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.rangeFromContext(e)}}getSourceString(e){return this.parseInfo.sourceStream.getText(new Wce.Interval(e.start.startIndex,e.stop?e.stop.stopIndex:e.start.startIndex))}contextError(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(r,i,{at:this.getLocation(e),...s}))}warnWithReplacement(e,r,i,s){this.msgLog.log((0,jk.makeLogMessage)(e,r,{at:{url:this.parseInfo.sourceURL,range:i},severity:"warn",replacement:s}))}inExperiment(e,r){const i=this.compilerFlags.tag("experimental");return i&&(i.bare()||i.has(e))?!0:(this.contextError(r,"experiment-not-enabled",{experimentId:e}),!1)}m4Severity(){const e=this.compilerFlags.tag("m4warnings");return e?e.text()==="warn"?"warn":"error":!1}m4advisory(e,r,i){const s=this.m4Severity();s&&this.contextError(e,r,i,{severity:s})}only(e,r,i){const s=[];for(const o of e){const u=r(o);u?s.push(u):o instanceof Hk||this.astError(o,"unexpected-statement-in-translation",`Parser enountered unexpected statement type '${o.elementType}' when it needed '${i}'`)}return s}getNumber(e){return Number.parseInt(e.text)}getFieldName(e){return this.astAt(new ue.FieldName((0,Xn.getId)(e)),e.id())}getModelEntryName(e){return this.astAt(new ue.ModelEntryReference((0,Xn.getId)(e)),e.id())}defaultResult(){return new ue.Unimplemented}astAt(e,r){return e.location={url:this.parseInfo.sourceURL,range:this.rangeFromContext(r)},e}getSourceCode(e){const r=e.start.startIndex,i=e.stop||e.start,s=new Wce.Interval(r,i.stopIndex);return this.parseInfo.sourceStream.getText(s)}getFilterElement(e){const r=this.getFieldExpr(e),i=new ue.FilterElement(r,this.getSourceCode(e));return this.astAt(i,e)}getFieldDefs(e,r){return e.map(i=>this.getFieldDef(i,r))}getFieldExpr(e){const r=this.visit(e);if(r instanceof ue.ExpressionDef)return this.astAt(r,e);throw this.internalError(e,`expression node unknown type '${r.elementType}'`)}getPlainStringFrom(e){const[r,i]=(0,Xn.getPlainString)(e);for(const s of i)s instanceof zce.ParserRuleContext&&this.contextError(s,"illegal-query-interpolation-outside-sql-block","%{ query } illegal in this string");return r||""}makeSqlString(e,r){for(const i of e.sqlInterpolation())i.CLOSE_CODE()&&this.m4advisory(i,"percent-terminated-query-interpolation","Use %{ ... } instead of %{ ... }%");for(const i of(0,Xn.getStringParts)(e))i instanceof zce.ParserRuleContext?r.push(this.visit(i)):r.push(i);r.complete(),this.astAt(r,e)}parseTime(e,r){let i=r(e.text);return i||(this.contextError(e,"failed-to-parse-time-literal","Time data parse error"),i=new ue.LiteralTimestamp({text:e.text})),this.astAt(i,e)}getNotes(e){return e.ANNOTATION().map(r=>({text:r.text,at:this.getLocation(e)}))}getIsNotes(e){return this.getNotes(e._beforeIs).concat(this.getNotes(e._afterIs))}visitMalloyDocument(e){const r=this.only(e.malloyStatement().map(i=>this.visit(i)),i=>ue.isDocStatementOrDocStatementList(i)&&i,"statement");return new ue.Document(r)}visitDefineSourceStatement(e){const i=e.sourcePropertyList().sourceDefinition().map(u=>this.visitSourceDefinition(u)),s=this.getNotes(e.tags()),o=new ue.DefineSourceList(i);return o.extendNote({blockNotes:s}),o}getSourceParameter(e){const r=e.fieldExpr(),i=r?this.astAt(new Edt.ConstantExpression(this.getFieldExpr(r)),r):void 0,s=e.malloyType(),o=s?this.getMalloyType(s):void 0;return this.astAt(new ue.HasParameter({name:(0,Xn.getId)(e.parameterNameDef()),type:o,default:i}),e)}getSourceParameters(e){return e===void 0?[]:(this.inExperiment("parameters",e),e.sourceParameter().map(r=>this.getSourceParameter(r)))}visitSourceDefinition(e){const r=this.visit(e.sqExplore()),i=this.getSourceParameters(e.sourceParameters()),s=new ue.DefineSource((0,Xn.getId)(e.sourceNameDef()),r instanceof ue.SourceQueryElement?r:void 0,!0,i),o=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return s.extendNote({notes:o}),this.astAt(s,e)}getSourceExtensions(e){return this.astAt(this.visitExploreProperties(e),e)}visitExploreProperties(e){const r=this.only(e.exploreStatement().map(s=>this.visit(s)),s=>ue.isSourceProperty(s)&&s,"source property");return new ue.SourceDesc(r)}visitTableFunction(e){const r=this.getPlainStringFrom(e.tableURI()),i=this.astAt(new ue.TableFunctionSource(r),e);return this.m4advisory(e,"table-function","`table('connection_name:table_path')` is deprecated; use `connection_name.table('table_path')`"),i}visitTableMethod(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=this.getPlainStringFrom(e.tablePath());return this.astAt(new ue.TableMethodSource(i,s),e)}visitSqlSource(e){const r=e.connectionId(),i=this.astAt(this.getModelEntryName(r),r),s=new ue.SQLString,o=e.sqlString();o&&this.makeSqlString(o,s);const u=e.shortString();u&&s.push((0,Xn.getShortString)(u));const a=new ue.SQLSource(i,s);return this.astAt(a,e)}visitDefJoinMany(e){const r=this.getAccessLabel(e.accessLabel()),i=[];for(const o of e.joinList().joinDef()){const u=this.visit(o);u instanceof ue.Join&&(i.push(u),u instanceof ue.ExpressionJoin?(u.joinType="many",u.joinOn===void 0&&this.contextError(e,"missing-on-in-join-many","join_many: requires ON expression")):u instanceof ue.KeyJoin&&this.contextError(e,"foreign-key-in-join-many","Foreign key join not legal in join_many:"))}const s=new ue.JoinStatement(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),s}visitDefJoinOne(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ue.Join&&(s.push(u),u instanceof ue.ExpressionJoin&&(u.joinType="one"));const o=new ue.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}visitDefJoinCross(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getJoinList(e.joinList()),s=[];for(const u of i)u instanceof ue.Join&&(s.push(u),u instanceof ue.ExpressionJoin?u.joinType="cross":u.logError("foreign-key-in-join-cross","Foreign key join not legal in join_cross:"));const o=new ue.JoinStatement(s,r);return o.extendNote({blockNotes:this.getNotes(e.tags())}),o}getJoinList(e){return this.only(e.joinDef().map(r=>this.visit(r)),r=>r instanceof ue.Join&&r,"join")}getJoinFrom(e){const r=e.isExplore(),i=this.getModelEntryName(e.joinNameDef());if(r){const o=this.getSqExpr(r.sqExpr()),u=this.getNotes(r._before_is).concat(this.getNotes(r._after_is));return{joinFrom:o,notes:u,joinAs:i}}const s=e.sourceArguments();return s?{joinFrom:this.astAt(new ue.SQReference(i,this.getSQArguments(s)),e),notes:[],joinAs:i}:{joinAs:i,joinFrom:new ue.SQReference(i),notes:[]}}visitQueryJoinStatement(e){return this.astAt(this.visit(e.joinStatement()),e)}visitJoinOn(e){var r;const{joinAs:i,joinFrom:s,notes:o}=this.getJoinFrom(e.joinFrom()),u=new ue.ExpressionJoin(i,s),a=e.joinExpression(),l=((r=e.matrixOperation())===null||r===void 0?void 0:r.text.toLocaleLowerCase())||"left";return(0,qk.isMatrixOperation)(l)?u.matrixOperation=l:this.contextError(e,"unknown-matrix-operation","Internal Error: Unknown matrixOperation"),a&&(u.joinOn=this.getFieldExpr(a)),u.extendNote({notes:this.getNotes(e).concat(o)}),this.astAt(u,e)}visitJoinWith(e){const{joinAs:r,joinFrom:i,notes:s}=this.getJoinFrom(e.joinFrom()),o=this.getFieldExpr(e.fieldExpr()),u=new ue.KeyJoin(r,i,o);return u.extendNote({notes:this.getNotes(e).concat(s)}),this.astAt(u,e)}getFieldDef(e,r){const i=e.fieldExpr(),s=(0,Xn.getId)(e.fieldNameDef()),o=this.getFieldExpr(i),u=new r(o,s,this.getSourceCode(i)),a=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));return u.extendNote({notes:a}),this.astAt(u,e)}visitDefDimensions(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.DimensionFieldDeclaration),s=new ue.Dimensions(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}getAccessLabel(e){if(e!==void 0){if(e.INTERNAL_KW())return"internal";if(e.PRIVATE_KW())return"private";if(e.PUBLIC_KW())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}getAccessLabelProp(e){if(e!==void 0){if(e.INTERNAL())return"internal";if(e.PRIVATE())return"private";if(e.PUBLIC())return"public";throw this.internalError(e,`Unknown access modifier label ${e.text}`)}}visitDefMeasures(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.MeasureFieldDeclaration),s=new ue.Measures(i,r);return s.extendNote({blockNotes:this.getNotes(e.tags())}),this.astAt(s,e)}visitQueryExtend(e){const r=[],i=e.queryExtendStatementList().queryExtendStatement().map(o=>this.visit(o));for(const o of i)if(ue.isQueryExtendProperty(o))r.push(o);else throw this.internalError(e,`Query extend matched, but ${o.elementType} found`);const s=new ue.ExtendBlock(r);return this.astAt(s,e)}visitDeclareStatement(e){const r=this.getAccessLabel(e.accessLabel()),i=this.getFieldDefs(e.defList().fieldDef(),ue.DeclareFieldDeclaration),s=new ue.DeclareFields(i,r),o=this.astAt(s,e);return this.m4advisory(e,"declare","`declare:` is deprecated; use `dimension:` or `measure:` inside a source or `extend:` block"),o}visitExploreRenameDef(e){const r=e.fieldName(0),i=e.fieldName(1),s=new ue.RenameField((0,Xn.getId)(r),this.getFieldName(i));return this.astAt(s,e)}visitDefExploreRename(e){const r=this.getAccessLabel(e.accessLabel()),s=e.renameList().exploreRenameDef().map(u=>this.visitExploreRenameDef(u)),o=new ue.Renames(s,r);return this.astAt(o,e)}visitFilterClauseList(e){return new ue.Filter(e.fieldExpr().map(r=>this.getFilterElement(r)))}visitWhereStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!1,this.astAt(r,e)}visitHavingStatement(e){const r=this.visitFilterClauseList(e.filterClauseList());return r.having=!0,this.astAt(r,e)}visitDefExploreQuery(e){const r=this.getAccessLabel(e.accessLabel()),i=e.subQueryDefList().exploreQueryDef().map(u=>this.visitExploreQueryDef(u)),s=new ue.Views(i,r),o=this.getNotes(e.tags());return s.extendNote({blockNotes:o}),e.QUERY()&&this.m4advisory(e,"query-in-source","Use view: inside of a source instead of query:"),s}visitDefExplorePrimaryKey(e){const r=new ue.PrimaryKey(this.getFieldName(e.fieldName()));return this.astAt(r,e)}getFieldNameList(e,r){const i=e.fieldName().map(s=>this.astAt(new r([this.getFieldName(s)]),s));return new ue.FieldReferences(i)}visitDefExploreEditField(e){const r=e.ACCEPT()?"accept":"except";return new ue.FieldListEdit(r,this.getFieldNameList(e.fieldNameList(),ue.AcceptExceptFieldReference))}visitSQInclude(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ue.SQExtend(r,new ue.SourceDesc([]),s);return this.astAt(o,e)}visitDefExploreTimezone(e){return this.visitTimezoneStatement(e.timezoneStatement())}visitTimezoneStatement(e){const r=this.getPlainStringFrom(e),i=this.astAt(new ue.TimezoneStatement(r),e.string());return i.isValid||this.astError(i,"invalid-timezone",{timezone:i.tz}),this.astAt(i,e)}visitQueryProperties(e){const r=this.only(e.queryStatement().map(i=>this.astAt(this.visit(i),i)),i=>ue.isQueryProperty(i)&&i,"query statement");return new ue.QOpDesc(r)}getFieldPath(e,r){const i=e.fieldName().map(s=>this.getFieldName(s));return this.astAt(new r(i),e)}getQueryFieldDef(e,r){const i=this.getFieldDef(e,r);return this.astAt(i,e)}getQueryFieldEntry(e,r,i){const s=e.taggedRef();if(s)return this.getTaggedRef(s,r,i);const o=e.fieldDef();if(o)return this.getQueryFieldDef(o,r);throw new Error("Expected query field entry to be a field reference or definition")}getQueryItems(e,r,i){return this.only(e.queryFieldEntry().map(s=>this.getQueryFieldEntry(s,r,i)),s=>s instanceof ue.FieldReference||s instanceof ue.AtomicFieldDeclaration?s:!1,"view field")}visitAggregateStatement(e){const r=new ue.Aggregate(this.getQueryItems(e.queryFieldList(),ue.AggregateFieldDeclaration,ue.AggregateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitGroupByStatement(e){const r=new ue.GroupBy(this.getQueryItems(e.queryFieldList(),ue.GroupByFieldDeclaration,ue.GroupByFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCalculateStatement(e){const r=new ue.Calculate(this.getQueryItems(e.queryFieldList(),ue.CalculateFieldDeclaration,ue.CalculateFieldReference));return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}getTaggedRef(e,r,i){const s=e.refExpr();if(s){const u=this.getFieldPath(e.fieldPath(),ue.ExpressionFieldReference);let a;const l=s.timeframe();l&&(a=new ue.ExprGranularTime(new ue.ExprIdReference(u),this.visitTimeframe(l).text,!0));const c=s.aggregate();if(c){const x=c.text.toLowerCase();if(x==="sum")a=new ue.ExprSum(void 0,u);else return this.contextError(c,"invalid-reference-only-aggregation",`\`${x}\` is not legal in a reference-only aggregation`),u}const f=new r(a,u.outputName);return f.extendNote({notes:this.getNotes(e.tags())}),f}const o=this.getFieldPath(e.fieldPath(),i);return o.extendNote({notes:this.getNotes(e.tags())}),o}getFieldCollectionMember(e,r,i){const s=e.fieldDef();if(s)return this.getFieldDef(s,r);const o=e.taggedRef();if(o)return this.getTaggedRef(o,r,i);const u=e.collectionWildCard();if(u)return this.visitCollectionWildCard(u);throw this.internalError(e,"Unexpected element in fieldCollectionMember")}visitFieldCollection(e){const r=e.collectionMember().map(i=>this.getFieldCollectionMember(i,ue.ProjectFieldDeclaration,ue.ProjectFieldReference));return this.astAt(new ue.ProjectStatement(r),e)}visitProjectStatement(e){e.PROJECT()&&this.m4advisory(e,"project","project: keyword is deprecated, use select:");const r=this.visitFieldCollection(e.fieldCollection());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitCollectionWildCard(e){var r;const i=e.fieldPath(),s=i?this.getFieldPath(i,ue.ProjectFieldReference):void 0,o=this.astAt(new ue.WildcardFieldReference(s),e),u=((r=e.starQualified())===null||r===void 0?void 0:r.fieldNameList())||[];for(const a of u)for(const l of a.fieldName())o.except.add((0,Xn.getId)(l));return o}visitIndexFields(e){const r=e.indexElement().map(i=>{const s=i.fieldPath();if(!s)return this.astAt(new ue.WildcardFieldReference(void 0),e);const o=this.getFieldPath(s,ue.IndexFieldReference);return i.STAR()?this.astAt(new ue.WildcardFieldReference(o),e):this.astAt(o,e)});return new ue.FieldReferences(r)}visitIndexStatement(e){const r=this.visitIndexFields(e.indexFields()),i=new ue.Index(r),s=e.fieldName();return s&&i.useWeight(this.getFieldName(s)),this.astAt(i,e)}visitFieldPropertyLimitStatement(e){return this.inExperiment("aggregate_limit",e),this.visitLimitStatement(e.limitStatement())}visitLimitStatement(e){return new ue.Limit(this.getNumber(e.INTEGER_LITERAL()))}visitAggregateOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.fieldExpr(),s=i?this.getFieldExpr(i):void 0;return this.astAt(new ue.FunctionOrderBy(s,r),e)}visitAggregateOrderByStatement(e){return this.visitAggregateOrdering(e.aggregateOrdering())}visitAggregateOrdering(e){const r=e.aggregateOrderBySpec().map(i=>this.visitAggregateOrderBySpec(i));return this.astAt(new ue.FunctionOrdering(r),e)}visitOrderBySpec(e){const r=e.ASC()?"asc":e.DESC()?"desc":void 0,i=e.INTEGER_LITERAL();if(i)return new ue.OrderBy(this.getNumber(i),r);const s=e.fieldName();if(s)return new ue.OrderBy(this.getFieldName(s),r);throw this.internalError(e,"can't parse order_by specification")}visitOrdering(e){const r=e.orderBySpec().map(i=>this.visitOrderBySpec(i));return this.astAt(new ue.Ordering(r),e)}visitTopStatement(e){const r=this.getNumber(e.INTEGER_LITERAL());return this.astAt(new ue.Limit(r),e)}visitTopLevelQueryDefs(e){const r=e.topLevelQueryDef().map(o=>this.visitTopLevelQueryDef(o)),i=this.getNotes(e.tags()),s=new ue.DefineQueryList(r);return s.extendNote({blockNotes:i}),s}visitTopLevelQueryDef(e){const r=(0,Xn.getId)(e.queryName()),i=this.visit(e.sqExpr()),s=this.getNotes(e.tags()).concat(this.getIsNotes(e.isDefine()));if(i instanceof ue.SourceQueryElement){const o=new ue.DefineQuery(r,i);return o.extendNote({notes:s}),this.astAt(o,e)}throw this.internalError(e,`Expected query definition, got a '${i.elementType}'`)}visitAnonymousQuery(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ue.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.m4advisory(r,"anonymous-query","Anonymous `query:` statements are deprecated, use `run:` instead"),this.astAt(s,e)}visitRunStatement(e){const r=e.topLevelAnonQueryDef(),i=this.getSqExpr(r.sqExpr()),s=this.astAt(new ue.AnonymousQuery(i),r),o=this.getNotes(e.topLevelAnonQueryDef().tags()),u=this.getNotes(e.tags());return s.extendNote({notes:o,blockNotes:u}),this.astAt(s,e)}visitNestStatement(e){const r=this.visitNestedQueryList(e.nestedQueryList());return r.extendNote({blockNotes:this.getNotes(e.tags())}),r}visitNestedQueryList(e){return new ue.Nests(this.only(e.nestEntry().map(r=>this.visit(r)),r=>r instanceof ue.NestFieldDeclaration&&r,"query"))}visitNestDef(e){const r=e.queryName();let i;const s=this.getVExpr(e.vExpr());if(r)i=(0,Xn.getId)(r);else{const a=s.getImplicitName();a===void 0&&this.contextError(e,"anonymous-nest","`nest:` view requires a name (add `nest_name is ...`)"),i=a??"__unnamed__"}const o=new ue.NestFieldDeclaration(i,s),u=e.isDefine();return o.extendNote({notes:this.getNotes(e.tags()).concat(u?this.getIsNotes(u):[])}),this.astAt(o,e)}visitExploreQueryDef(e){const r=(0,Xn.getId)(e.exploreQueryNameDef()),i=new ue.ViewFieldDeclaration(r,this.getVExpr(e.vExpr())),s=this.getNotes(e).concat(this.getIsNotes(e.isDefine()));return i.extendNote({notes:s}),this.astAt(i,e)}visitExprNot(e){return new ue.ExprNot(this.getFieldExpr(e.fieldExpr()))}visitExprBool(e){return new ue.Boolean(e.TRUE()?"true":"false")}allFieldExpressions(e){return e.map(r=>this.getFieldExpr(r))}visitExprLogicalOr(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ue.ExprLogicalOp(r,"or",i)}visitExprLogicalAnd(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1));return new ue.ExprLogicalOp(r,"and",i)}visitExprOrTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ue.ExprAlternationTree(r,"|",i),e)}visitExprAndTree(e){const r=this.getFieldExpr(e.fieldExpr()),i=this.getFieldExpr(e.partialAllowedFieldExpr());return this.astAt(new ue.ExprAlternationTree(r,"&",i),e)}visitExprCoalesce(e){const r=this.getFieldExpr(e.fieldExpr()[0]),i=this.getFieldExpr(e.fieldExpr()[1]);return this.astAt(new ue.ExprCoalesce(r,i),e)}visitPartialCompare(e){const r=e.compareOp().text;if(ue.isComparison(r))return this.astAt(new ue.PartialCompare(r,this.getFieldExpr(e.fieldExpr())),e);throw this.internalError(e,`partial comparison '${r}' not recognized`)}visitPartialTest(e){const r=e.partialCompare();return r?this.visitPartialCompare(r):this.astAt(new ue.PartialIsNull(e.NOT()?"!=":"="),e)}visitPartialAllowedFieldExpr(e){const r=e.fieldExpr();if(r)return this.getFieldExpr(r);const i=e.partialTest();if(i)return this.visitPartialTest(i);throw this.internalError(e,"impossible partial")}visitExprString(e){const r=this.getPlainStringFrom(e);return new ue.ExprString(r)}visitRawString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1556
1556
  `){const o=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing ${o}${r[0]}${o} before end-of-line`)}const s=new ue.ExprString(r.slice(1,-1));return this.astAt(s,e)}visitExprRegex(e){const r=e.HACKY_REGEX().text;return new ue.ExprRegEx(r.slice(2,-1))}visitExprNow(e){return new ue.ExprNow}visitExprNumber(e){return new ue.ExprNumber(e.text)}visitExprFieldPath(e){const r=new ue.ExprIdReference(this.getFieldPath(e.fieldPath(),ue.ExpressionFieldReference));return this.astAt(r,e)}visitExprNULL(e){return new ue.ExprNULL}visitExprExpr(e){return new ue.ExprParens(this.getFieldExpr(e.fieldExpr()))}visitExprMinus(e){return new ue.ExprMinus(this.getFieldExpr(e.fieldExpr()))}visitExprAddSub(e){const r=this.getFieldExpr(e.fieldExpr(0)),i=this.getFieldExpr(e.fieldExpr(1)),s=e.PLUS()?"+":"-";return new ue.ExprAddSub(r,s,i)}visitExprMulDiv(e){const r=e.STAR()?"*":e.SLASH()?"/":"%";return new ue.ExprMulDiv(this.getFieldExpr(e.fieldExpr(0)),r,this.getFieldExpr(e.fieldExpr(1)))}visitExprCompare(e){const r=e.compareOp().text,i=this.getFieldExpr(e.fieldExpr(0)),s=this.getFieldExpr(e.fieldExpr(1));if(ue.isEquality(r)){const o=this.rangeFromContext(e);return s instanceof ue.ExprNULL&&(r==="="?this.warnWithReplacement("sql-is-null","Use 'is null' to check for NULL instead of '= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is null`):r==="!="&&this.warnWithReplacement("sql-is-not-null","Use 'is not null' to check for NULL instead of '!= null'",o,`${this.getSourceCode(e.fieldExpr(0))} is not null`)),this.astAt(new ue.ExprEquality(i,r,s),e)}else if(ue.isComparison(r))return this.astAt(new ue.ExprCompare(i,r,s),e);throw this.internalError(e,`untranslatable comparison operator '${r}'`)}visitExprUngroup(e){const r=e.fieldName().map(s=>this.getFieldName(s)),i=e.ungroup().text.toLowerCase();return this.astAt(new ue.ExprUngroup(i==="all"?i:"exclude",this.getFieldExpr(e.fieldExpr()),r),e)}symmetricAggregateUsageError(e){return`Symmetric aggregate function \`${e}\` must be written as \`${e}(expression)\` or \`path.to.field.${e}()\``}asymmetricAggregateUsageError(e){return`Asymmetric aggregate function \`${e}\` must be written as \`path.to.field.${e}()\`, \`path.to.join.${e}(expression)\`, or \`${e}(expression)\``}visitExprAggregate(e){const r=e.fieldPath(),i=this.getFieldPath(r,ue.ExpressionFieldReference),s=r&&i?this.astAt(i,r):void 0,o=e.aggregate().text.toLowerCase(),u=e.fieldExpr();if(e.aggregate().COUNT())return u&&this.contextError(u,"count-expression-with-locality","Expression illegal inside path.count()"),new ue.ExprCount(s);const a=u?this.getFieldExpr(u):void 0;if(o==="min"||o==="max")if(a)this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o));else{const l=this.astAt(new ue.ExprIdReference(i),r);return o==="min"?new ue.ExprMin(l):new ue.ExprMax(l)}else{if(o==="avg")return new ue.ExprAvg(a,s);if(o==="sum")return new ue.ExprSum(a,s);this.contextError(e,"aggregate-parse-error",`Cannot parse aggregate function ${o}`)}return new ue.ExprNULL}visitExprPathlessAggregate(e){const r=e.fieldExpr(),i=r?this.getFieldExpr(r):void 0,s=void 0,o=e.aggregate().text.toLowerCase();if(e.STAR()&&this.m4advisory(e,"wildcard-in-aggregate",`* illegal inside ${o}()`),o==="count")return this.astAt(i?new ue.ExprCountDistinct(i):new ue.ExprCount,e);if(o==="min"){if(i)return new ue.ExprMin(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else if(o==="max"){if(i)return new ue.ExprMax(i);this.contextError(e,"invalid-symmetric-aggregate",this.symmetricAggregateUsageError(o))}else{if(i===void 0)return this.contextError(e,"invalid-asymmetric-aggregate",this.asymmetricAggregateUsageError(o)),new ue.ExprNULL;const u=e.SOURCE_KW()!==void 0;if(o==="avg")return new ue.ExprAvg(i,s,u);if(o==="sum")return new ue.ExprSum(i,s,u)}return new ue.ExprNULL}visitExprApply(e){return new ue.Apply(this.getFieldExpr(e.fieldExpr()),this.getFieldExpr(e.partialAllowedFieldExpr()))}visitExprRange(e){return new ue.Range(this.getFieldExpr(e.fieldExpr(0)),this.getFieldExpr(e.fieldExpr(1)))}visitExprCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ue.ExprCast(this.getFieldExpr(e.fieldExpr()),r)}getMalloyType(e){const r=e.text;if((0,qk.isCastType)(r))return r;throw this.internalError(e,`unknown type '${r}'`)}getMalloyOrSQLType(e){const r=e.malloyType();if(r)return this.getMalloyType(r);const i=e.string();if(i)return{raw:this.getPlainStringFrom({string:()=>i})};throw this.internalError(e,"Expected Malloy or SQL type to either be a Malloy type or a string")}visitExprSafeCast(e){const r=this.getMalloyOrSQLType(e.malloyOrSQLType());return new ue.ExprCast(this.getFieldExpr(e.fieldExpr()),r,!0)}visitExprTimeTrunc(e){return new ue.ExprGranularTime(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text,!0)}visitTimeframe(e){return new ue.Timeframe(e.text)}visitExprForRange(e){const r=this.getFieldExpr(e._startAt),i=this.getFieldExpr(e._duration),s=this.visitTimeframe(e.timeframe());return new ue.ForRange(r,i,s)}visitExprAggFunc(e){const r=e.argumentList(),i=r?this.allFieldExpressions(r.fieldExpr()):[],s=(0,Xn.getId)(e),o=e.fieldPath(),u=o?this.getFieldPath(o,ue.ExpressionFieldReference):void 0,a=o&&u?this.astAt(u,o):void 0;return ue.ExprTimeExtract.extractor(s)?this.astAt(new ue.ExprTimeExtract(s,i),e):this.astAt(new ue.ExprFunc(s,i,!1,void 0,a),e)}visitExprFunc(e){var r,i;const s=e.argumentList(),o=s?this.allFieldExpressions(s.fieldExpr()):[],u=e.EXCLAM()!==void 0,a=(r=e.malloyType())===null||r===void 0?void 0:r.text;let l;a&&((0,qk.isCastType)(a)?l=a:(this.contextError(e,"unexpected-malloy-type",`'#' assertion for unknown type '${a}'`),l=void 0));let c=(0,Xn.getOptionalId)(e)||((i=e.timeframe())===null||i===void 0?void 0:i.text);return c===void 0&&(this.contextError(e,"failed-to-parse-function-name","Function name error"),c="FUNCTION_NAME_ERROR"),ue.ExprTimeExtract.extractor(c)?this.astAt(new ue.ExprTimeExtract(c,o),e):this.astAt(new ue.ExprFunc(c,o,u,l),e)}visitExprDuration(e){return new ue.ExprDuration(this.getFieldExpr(e.fieldExpr()),this.visitTimeframe(e.timeframe()).text)}visitCaseStatement(e){const r=e._valueExpr,i=r?this.getFieldExpr(r):void 0,s=e.caseWhen(),o=s.map(l=>new ue.CaseWhen(this.getFieldExpr(l._condition),this.getFieldExpr(l._result))),u=e._caseElse,a=u?this.getFieldExpr(u):void 0;return this.warnWithReplacement("sql-case","Use a `pick` statement instead of `case`",this.rangeFromContext(e),`${[...r?[`${this.getSourceCode(r)} ?`]:[],...s.map(l=>`pick ${this.getSourceCode(l._result)} when ${this.getSourceCode(l._condition)}`),u?`else ${u.text}`:"else null"].join(" ")}`),new ue.Case(i,o,a)}visitPickStatement(e){const r=e.pick().map(i=>{let s;return i._pickValue&&(s=this.getFieldExpr(i._pickValue)),new ue.PickWhen(s,this.getFieldExpr(i._pickWhen))});return e.ELSE()?new ue.Pick(r,this.getFieldExpr(e._pickElse)):new ue.Pick(r)}visitExprFieldProps(e){const r=this.only(e.fieldProperties().fieldPropertyStatement().map(i=>this.visit(i)),i=>ue.isFieldPropStatement(i)&&i,"field property statement");return new ue.ExprProps(this.getFieldExpr(e.fieldExpr()),r)}visitPartitionByStatement(e){return this.astAt(new ue.PartitionBy(e.id().map(r=>this.astAt(new ue.PartitionByFieldReference([this.astAt(new ue.FieldName((0,Xn.idToStr)(r)),r)]),r))),e)}visitLiteralTimestamp(e){return this.parseTime(e,ue.LiteralTimestamp.parse)}visitLiteralHour(e){return this.parseTime(e,ue.LiteralHour.parse)}visitLiteralDay(e){return this.parseTime(e,ue.LiteralDay.parse)}visitLiteralWeek(e){return this.parseTime(e,ue.LiteralWeek.parse)}visitLiteralMonth(e){return this.parseTime(e,ue.LiteralMonth.parse)}visitLiteralQuarter(e){return this.parseTime(e,ue.LiteralQuarter.parse)}visitLiteralYear(e){return this.parseTime(e,ue.LiteralYear.parse)}visitImportStatement(e){const r=this.getPlainStringFrom(e.importURL()),i=this.astAt(new ue.ImportStatement(r,this.parseInfo.importBaseURL),e),s=e.importSelect();if(s)for(const o of s.importItem()){const u=o.id(),a=u[1]?this.astAt(new ue.ImportSourceName((0,Xn.idToStr)(u[1])),u[1]):void 0;i.push(this.astAt(new ue.ImportSelect((0,Xn.idToStr)(u[0]),a),u[0]))}return i}visitDebugExpr(e){return this.getFieldExpr(e.fieldExpr())}visitSampleStatement(e){const r=e.sampleSpec().INTEGER_LITERAL();if(r)return new ue.SampleProperty({rows:this.getNumber(r)});const i=e.sampleSpec().PERCENT_LITERAL();if(i)return new ue.SampleProperty({percent:this.getNumber(i)});const s=e.sampleSpec().TRUE()!==void 0;return new ue.SampleProperty({enable:s})}visitDocAnnotations(e){const r=e.DOC_ANNOTATION().map(s=>({text:s.text,at:this.getLocation(e)})),i=new ue.ModelAnnotation(r);return this.compilerFlags=i.getCompilerFlags(this.compilerFlags,this.msgLog),i}visitIgnoredObjectAnnotations(e){return this.contextError(e,"orphaned-object-annotation","Object annotation not connected to any object"),new Hk(e.text)}visitIgnoredModelAnnotations(e){return this.contextError(e,"misplaced-model-annotation","Model annotations not allowed at this scope"),new Hk(e.text)}visitDefExploreAnnotation(e){const r=this.getNotes(e);return new ue.ObjectAnnotation(r)}getSQArgument(e){const r=e.argumentId(),i=r?this.astAt(new ue.PartitionByFieldReference([this.astAt(new ue.FieldName((0,Xn.idToStr)(r.id())),r)]),r):void 0;return this.astAt(new ue.Argument({id:i,value:this.getFieldExpr(e.fieldExpr())}),e)}getSQArguments(e){if(e!==void 0)return this.inExperiment("parameters",e),e.sourceArgument().map(r=>this.getSQArgument(r))}visitSQID(e){const r=this.getModelEntryName(e),i=this.getSQArguments(e.sourceArguments());return this.astAt(new ue.SQReference(r,i),e.id())}getSqExpr(e){const r=this.visit(e);return r instanceof ue.SourceQueryElement?r:(this.contextError(e,"unexpected-non-source-query-expression-node",`Expected a source/query expression, not '${r.elementType}'`),new Vce)}visitSQExtendedSource(e){const r=this.getSqExpr(e.sqExpr()),i=e.includeBlock(),s=i?this.getIncludeItems(i):void 0,o=new ue.SQExtend(r,this.getSourceExtensions(e.exploreProperties()),s);return this.astAt(o,e)}getIncludeItems(e){return this.inExperiment("access_modifiers",e),e.includeItem().map(r=>this.getIncludeItem(r)).filter(Gce.isNotUndefined)}getIncludeItem(e){var r;const i=e.tags(),s=i?this.getNotes(i):[],o=e.includeExceptList();if(o){i&&s.length>0&&this.contextError(i,"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const u=this.getExcludeList(o);return this.astAt(new ue.IncludeExceptItem(u),e)}else{const u=e.includeList();if(u===void 0){this.contextError((r=e.orphanedAnnotation())!==null&&r!==void 0?r:e,"orphaned-object-annotation","This tag is not attached to anything",{severity:"warn"});return}const a=this.getAccessLabelProp(e.accessLabelProp()),l=this.getIncludeList(u),c=this.astAt(new ue.IncludeAccessItem(a,l),e);return c.extendNote({blockNotes:s}),c}}getIncludeList(e){const r=e.includeField();if(r===void 0)throw this.internalError(e,"Expected a field name list");return r.map(i=>this.getIncludeListItem(i))}getExcludeList(e){return e.includeExceptListItem().map(r=>{r.tags().ANNOTATION().length>0&&this.contextError(r.tags(),"cannot-tag-include-except","Tags on `except:` are ignored",{severity:"warn"});const i=r.fieldName();if(i)return this.astAt(new ue.AccessModifierFieldReference([this.astAt(this.getFieldName(i),r)]),i);const s=r.collectionWildCard();if(s)return this.astAt(this.visitCollectionWildCard(s),s);throw this.internalError(r,"Expected a field name or wildcard")})}getIncludeListItem(e){const r=e.collectionWildCard(),i=r?this.visitCollectionWildCard(r):void 0,s=e._as?e._as.text:void 0,o=e.tags(),u=o?this.getNotes(o):[],a=e.isDefine(),l=a?this.getIsNotes(a):[],c=[...u,...l],f=e._name?this.astAt(new ue.AccessModifierFieldReference([this.astAt(this.getFieldName(e._name),e._name)]),e._name):void 0,x=f??i;if(x===void 0)throw this.internalError(e,"Expected a field name or wildcard");const h=this.astAt(new ue.IncludeListItem(x,s),e);return h.extendNote({notes:c}),h}visitSQParens(e){const r=this.getSqExpr(e.sqExpr());return this.astAt(r,e)}visitSQCompose(e){const r=e.sqExpr().map(i=>this.getSqExpr(i));return this.inExperiment("composite_sources",e),this.astAt(new ue.SQCompose(r),e)}visitSQArrow(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ue.SQArrow(r,this.getVExpr(i));return this.astAt(s,e)}getVExpr(e){const r=this.visit(e);if(r instanceof ue.View)return r;throw this.internalError(e,`Expected view, got a '${r.elementType}'`)}visitSegField(e){return new ue.ReferenceView(this.getFieldPath(e.fieldPath(),ue.ViewOrScalarFieldReference))}visitSegOps(e){return new ue.QOpDescView(this.visitQueryProperties(e.queryProperties()))}visitSegParen(e){return this.visit(e.vExpr())}visitVSeg(e){return this.visit(e.segExpr())}visitSegRefine(e){return new ue.ViewRefine(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitVArrow(e){return new ue.ViewArrow(this.getVExpr(e._lhs),this.getVExpr(e._rhs))}visitSQRefinedQuery(e){const r=this.getSqExpr(e.sqExpr()),i=e.segExpr(),s=new ue.SQRefine(r,this.getVExpr(i));return this.astAt(s,e)}visitSQTable(e){const r=this.visit(e.exploreTable());if(r instanceof gdt.TableSource){const i=new ue.SQSource(r);return this.astAt(i,e)}return new Vce}visitSQSQL(e){const r=new ue.SQSource(this.visitSqlSource(e.sqlSource()));return this.astAt(r,e)}visitExperimentalStatementForTesting(e){return this.inExperiment("compilerTestExperimentParse",e),this.astAt(new ue.ExperimentalExperiment("compilerTestExperimentTranslate"),e)}visitRecordRef(e){const r=new ue.ExprIdReference(this.getFieldPath(e.fieldPath(),ue.ExpressionFieldReference));return this.astAt(new ue.RecordElement({path:r}),e)}visitRecordExpr(e){const r=this.getFieldExpr(e.fieldExpr()),i=e.recordKey(),s=i?{key:(0,Xn.getId)(i),value:r}:{value:r};return this.astAt(new ue.RecordElement(s),e)}visitExprLiteralRecord(e){const r=this.only(e.recordElement().map(i=>this.astAt(this.visit(i),i)),i=>i instanceof ue.RecordElement&&i,"a legal record property description");return new ue.RecordLiteral(r)}visitExprArrayLiteral(e){const r=e.fieldExpr().map(s=>this.getFieldExpr(s)),i=new ue.ArrayLiteral(r);return this.astAt(i,e)}visitExprWarnLike(e){let r="~";const i=e.fieldExpr(0),s=e.fieldExpr(1),o=this.rangeFromContext(e);return e.NOT()?(r="!~",this.warnWithReplacement("sql-not-like","Use Malloy operator '!~' instead of 'NOT LIKE'",o,`${this.getSourceCode(i)} !~ ${this.getSourceCode(s)}`)):this.warnWithReplacement("sql-like","Use Malloy operator '~' instead of 'LIKE'",o,`${this.getSourceCode(i)} ~ ${this.getSourceCode(s)}`),this.astAt(new ue.ExprCompare(this.getFieldExpr(i),r,this.getFieldExpr(s)),e)}visitExprNullCheck(e){const r=e.fieldExpr();return this.astAt(new ue.ExprIsNull(this.getFieldExpr(r),e.NOT()?"!=":"="),e)}visitExprWarnIn(e){const r=this.getFieldExpr(e.fieldExpr()),i=!!e.NOT(),s=e.fieldExprList().fieldExpr(),o=this.astAt(new ue.ExprLegacyIn(r,i,s.map(u=>this.getFieldExpr(u))),e);return this.warnWithReplacement("sql-in",`Use = (a|b|c) instead of${i?" NOT":""} IN (a,b,c)`,this.rangeFromContext(e),`${this.getSourceCode(e.fieldExpr())} ${i?"!=":"="} (${s.map(u=>this.getSourceCode(u)).join(" | ")})`),o}visitTickFilterString(e){const r=e.text.slice(1).trimStart();if(r[r.length-1]===`
1557
1557
  `){const u=r[0]==="'"?'"':"'";this.contextError(e,"literal-string-newline",`Missing $${u}${r[0]}${u} before end-of-line`)}const s=r.slice(1,-1),o=new ue.ExprFilterExpression(s);return this.astAt(o,e)}visitTripFilterString(e){const i=e.text.slice(1).trimStart().slice(3,-3),s=new ue.ExprFilterExpression(i);return this.astAt(s,e)}}mR.MalloyToAST=_dt;var gR={};Object.defineProperty(gR,"__esModule",{value:!0}),gR.Zone=void 0;class vdt{constructor(){this.location={},this.zone=new Map}get(e){const r=this.zone.get(e);if((r==null?void 0:r.status)==="present")return r.value}getEntry(e){const r=this.zone.get(e);return r?r.firstReference||!this.location[e]?r:{...r,firstReference:this.location[e]}:{status:"error",message:"import reference failure"}}define(e,r){this.zone.set(e,{status:"present",value:r})}reference(e,r){const i=this.zone.get(e);(i==null?void 0:i.status)===void 0&&(this.zone.set(e,{status:"reference",firstReference:r}),this.location[e]=r)}getUndefined(){const e=[];for(const[r,i]of this.zone)i.status==="reference"&&e.push(r);return e.length>0?e:void 0}updateFrom(e,r){if(e)for(const[i,s]of Object.entries(e))s!==void 0&&this.define(i,s);if(r)for(const[i,s]of Object.entries(r))this.zone.set(i,{status:"error",message:s})}}gR.Zone=vdt;var yR={};Object.defineProperty(yR,"__esModule",{value:!0}),yR.walkForDocumentSymbols=void 0;const Cdt=R0,Sdt=Un;class bdt{constructor(e,r,i,s){this.translator=e,this.tokens=r,this.scopes=i,this.symbols=s}popScope(){return this.scopes.pop()}peekScope(){return this.scopes[this.scopes.length-1]}enterTopLevelQueryDefs(e){const r=this.translator.rangeFromContext(e);e.topLevelQueryDef().length===1&&(this.blockRange=r)}enterTopLevelQueryDef(e){this.symbols.push({range:this.translator.rangeFromContext(e),name:e.queryName().text,type:"query",children:[],lensRange:this.blockRange}),this.blockRange=void 0}enterRunStatement(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterAnonymousQuery(e){this.symbols.push({range:this.translator.rangeFromContext(e.topLevelAnonQueryDef().sqExpr()),name:"unnamed_query",type:"unnamed_query",children:[],lensRange:this.translator.rangeFromContext(e)})}enterDefineSourceStatement(e){const r=this.translator.rangeFromContext(e);e.sourcePropertyList().sourceDefinition().length===1&&(this.blockRange=r)}enterSourceDefinition(e){const r=this.translator.rangeFromContext(e);this.scopes.push({range:r,name:e.sourceNameDef().id().text,type:"explore",children:[],lensRange:this.blockRange}),this.blockRange=void 0}exitSourceDefinition(e){const r=this.popScope();r&&this.symbols.push(r)}enterDefExploreQuery(e){const r=this.translator.rangeFromContext(e);e.subQueryDefList().exploreQueryDef().length===1&&(this.blockRange=r)}enterExploreQueryDef(e){const r={range:this.translator.rangeFromContext(e),name:e.exploreQueryNameDef().id().text,type:"query",children:[],lensRange:this.blockRange},i=this.peekScope();i&&i.children.push(r),this.scopes.push(r),this.blockRange=void 0}exitExploreQueryDef(e){this.popScope()}getNestDefName(e){const r=e.queryName();if(r)return r.id().text;let i,s=!1;const o={enterVArrow(a){a.vExpr().enterRule(o)},enterVSeg(a){a.segExpr().enterRule(u)}},u={enterSegField(a){const l=a.fieldPath().fieldName();s||(i??(i=l[l.length-1].id().text))},enterSegParen(a){a.vExpr().enterRule(o)},enterSegRefine(a){a._lhs.enterRule(u)},enterSegOps(){i=void 0,s=!0}};return e.vExpr().enterRule(o),i}handleNestEntry(e){const r=this.getNestDefName(e);if(r===void 0)return;const i={range:this.translator.rangeFromContext(e),name:r,type:"query",children:[]},s=this.peekScope();return s&&s.children.push(i),i}enterNestDef(e){const r=this.handleNestEntry(e);r&&this.scopes.push(r)}exitNestDef(e){this.popScope()}enterFieldDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldNameDef().id().text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterQueryFieldEntry(e){var r;const i=(r=e.taggedRef())===null||r===void 0?void 0:r.fieldPath();if(i===void 0)return;const s={range:this.translator.rangeFromContext(e),name:i.text,type:"field",children:[]},o=this.peekScope();o&&o.children.push(s)}enterExploreRenameDef(e){const r={range:this.translator.rangeFromContext(e),name:e.fieldName()[0].text,type:"field",children:[]},i=this.peekScope();i&&i.children.push(r)}enterJoinWith(e){this.handleJoinDef(e)}enterJoinOn(e){this.handleJoinDef(e)}handleJoinDef(e){const r={range:this.translator.rangeFromContext(e),name:e.joinFrom().joinNameDef().id().text,type:"join",children:[]},i=this.peekScope();i&&i.children.push(r)}enterImportStatement(e){const r=(0,Sdt.getStringIfShort)(e.importURL());r&&this.scopes.push({range:this.translator.rangeFromContext(e),name:r,type:"import",children:[]})}exitImportStatement(){const e=this.popScope();e&&this.symbols.push(e)}enterImportSelect(e){const r=this.peekScope();if(r)for(const i of e.importItem()){const s={range:this.translator.rangeFromContext(e),name:i.text,type:"import_item",children:[]};r.children.push(s)}}}function Tdt(t,e,r){const i=new bdt(t,e,[],[]),s=i;return Cdt.ParseTreeWalker.DEFAULT.walk(s,r),i.symbols}yR.walkForDocumentSymbols=Tdt;var ER={};Object.defineProperty(ER,"__esModule",{value:!0}),ER.walkForDocumentCompletions=void 0;const Rdt=R0,Ddt=["dimension","measure","join_one","join_many","join_cross","where","primary_key","rename","accept","except","query","declare"],Odt=["group_by","project","index","aggregate","top","limit","order_by","where","having","nest","declare"],wdt=["source","explore","query","sql"];class Fdt{constructor(e,r,i){this.tokens=e,this.completions=r,this.position=i}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){const{start:r,end:i}=e,s=this.position.line>r.line||this.position.line===r.line&&this.position.character>=r.character,o=this.position.line<i.line||this.position.line===i.line&&this.position.character<=i.character;return s&&o}enterExploreProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.exploreStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Ddt)this.completions.push({type:"explore_property",text:`${i}: `})}}enterQueryProperties(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.queryStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of Odt)this.completions.push({type:"query_property",text:`${i}: `})}}enterMalloyDocument(e){if(this.inRange(this.rangeOf(e))){let r=!1;for(const i of e.malloyStatement())this.inRange(this.rangeOf(i))&&(r=!0);if(!r)for(const i of wdt)this.completions.push({type:"model_property",text:`${i}: `})}}}function Ndt(t,e,r){const i=new Fdt(t,[],r),s=i;return Rdt.ParseTreeWalker.DEFAULT.walk(s,e),i.completions}ER.walkForDocumentCompletions=Ndt;var AR={};Object.defineProperty(AR,"__esModule",{value:!0}),AR.walkForDocumentHelpContext=void 0;const Ldt=oO;class Idt extends Ldt.AbstractParseTreeVisitor{constructor(e){super(),this.position=e,this.type=""}rangeOf(e){const r=e.stop||e.start;return{start:{line:e.start.line-1,character:e.start.charPositionInLine},end:{line:r.line-1,character:r.stopIndex-(r.startIndex-r.charPositionInLine)+1}}}inRange(e){return e.start.line<=this.position.line&&e.end.line>=this.position.line&&(this.position.line!==e.start.line||this.position.character>=e.start.character)&&(this.position.line!==e.end.line||this.position.character<=e.end.character)}defaultResult(){}visitChildren(e){let r=this.defaultResult();if(this.inRange(this.rangeOf(e))){r={type:this.type,token:e.start.text};const i=e.childCount;for(let s=0;s<i;s++){const u=e.getChild(s).accept(this);u&&(r=this.aggregateResult(r,u))}}return r}visitMalloyDocument(e){return this.inRange(this.rangeOf(e))?(this.type="model_property",this.visitChildren(e)):this.defaultResult()}visitExploreProperties(e){return this.inRange(this.rangeOf(e))?(this.type="explore_property",this.visitChildren(e)):this.defaultResult()}visitQueryProperties(e){return this.inRange(this.rangeOf(e))?(this.type="query_property",this.visitChildren(e)):this.defaultResult()}aggregateResult(e,r){return r}}function $dt(t,e){return new Idt(e).visit(t)}AR.walkForDocumentHelpContext=$dt;var _R={};Object.defineProperty(_R,"__esModule",{value:!0}),_R.ReferenceList=void 0;const Bdt=Jn;class kdt{constructor(e){this.sourceURL=e,this.references=[]}findIndexBefore(e){let r=0,i=this.references.length;for(;r<i;){const s=Math.floor((r+i)/2),o=this.references[s].location.range.end;o.line<e.line||o.line===e.line&&o.character<e.character?r=s+1:i=s}return r}add(e){if(e.location.url!==this.sourceURL)return;const r=this.findIndexBefore(e.location.range.end);r<this.references.length&&this.isPositionEqual(e,this.references[r])||this.references.splice(r,0,e)}isPositionEqual(e,r){const i=e.location.range,s=r.location.range;return i.start.line===s.start.line&&i.start.character===s.start.character&&i.end.line===s.end.line&&i.end.character===s.end.character}find(e){const r=this.findIndexBefore(e);if(r===this.references.length)return;const i=this.references[r];if((0,Bdt.locationContainsPosition)(i.location,e))return i}}_R.ReferenceList=kdt;var vR={};Object.defineProperty(vR,"__esModule",{value:!0}),vR.isNeedResponse=void 0;function Mdt(t){return!!t&&(t.tables||t.urls||t.compileSQL)!==void 0}vR.isNeedResponse=Mdt;var CR={};Object.defineProperty(CR,"__esModule",{value:!0}),CR.walkForModelAnnotation=void 0;const Pdt=R0;class Udt{constructor(e,r,i){this.translator=e,this.tokens=r,this.parseInfo=i,this.notes=[]}getLocation(e){return{url:this.parseInfo.sourceURL,range:this.translator.rangeFromContext(e)}}enterDocAnnotations(e){const r=e.DOC_ANNOTATION().map(i=>({text:i.text,at:this.getLocation(e)}));this.notes.push(...r)}get annotation(){return{notes:this.notes}}}function jdt(t,e,r){const i=new Udt(t,e,r),s=i;return Pdt.ParseTreeWalker.DEFAULT.walk(s,r.root),i.annotation}CR.walkForModelAnnotation=jdt;var SR={};Object.defineProperty(SR,"__esModule",{value:!0}),SR.walkForTablePath=void 0;const Yce=Un,qdt=R0;class Hdt{constructor(e,r){this.translator=e,this.tokens=r,this.pathInfos=[]}enterTableMethod(e){const r=(0,Yce.getId)(e.connectionId()),[i,s]=(0,Yce.getPlainString)(e.tablePath(),!0);i!==void 0&&this.pathInfos.push({connectionId:r,tablePath:i,range:this.translator.rangeFromContext(e)})}}function Qdt(t,e,r){const i=new Hdt(t,e),s=i;return qdt.ParseTreeWalker.DEFAULT.walk(s,r.root),i.pathInfos}SR.walkForTablePath=Qdt;var ME={},bR={},zdt=T&&T.__createBinding||(Object.create?function(t,e,r,i){i===void 0&&(i=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,i,s)}:function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}),Wdt=T&&T.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Gdt=T&&T.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zdt(e,t,r);return Wdt(e,t),e};Object.defineProperty(bR,"__esModule",{value:!0}),bR.MalloyLexer=void 0;const Vdt=mh(),Ydt=xl(),Kdt=M1(),Jdt=Ds,Kce=Gdt(Sn);class le extends Ydt.Lexer{get vocabulary(){return le.VOCABULARY}constructor(e){super(e),this._interp=new Kdt.LexerATNSimulator(le._ATN,this)}get grammarFileName(){return"MalloyLexer.g4"}get ruleNames(){return le.ruleNames}get serializedATN(){return le._serializedATN}get channelNames(){return le.channelNames}get modeNames(){return le.modeNames}static get _ATN(){return le.__ATN||(le.__ATN=new Vdt.ATNDeserializer().deserialize(Kce.toCharArray(le._serializedATN))),le.__ATN}}bR.MalloyLexer=le,le.ACCEPT=1,le.AGGREGATE=2,le.CALCULATE=3,le.CALCULATION=4,le.CONNECTION=5,le.DECLARE=6,le.DIMENSION=7,le.EXCEPT=8,le.EXTENDQ=9,le.GROUP_BY=10,le.HAVING=11,le.INDEX=12,le.INTERNAL=13,le.JOIN_CROSS=14,le.JOIN_ONE=15,le.JOIN_MANY=16,le.LIMIT=17,le.MEASURE=18,le.NEST=19,le.ORDER_BY=20,le.PARTITION_BY=21,le.PRIMARY_KEY=22,le.PRIVATE=23,le.PROJECT=24,le.PUBLIC=25,le.QUERY=26,le.RENAME=27,le.RUN=28,le.SAMPLE=29,le.SELECT=30,le.SOURCE=31,le.TOP=32,le.WHERE=33,le.VIEW=34,le.TIMEZONE=35,le.ALL=36,le.AND=37,le.AS=38,le.ASC=39,le.AVG=40,le.BOOLEAN=41,le.BY=42,le.CASE=43,le.CAST=44,le.CONDITION=45,le.COUNT=46,le.COMPOSE=47,le.DATE=48,le.DAY=49,le.DESC=50,le.DISTINCT=51,le.ELSE=52,le.END=53,le.EXCLUDE=54,le.EXTEND=55,le.FALSE=56,le.FULL=57,le.FOR=58,le.FROM=59,le.HAS=60,le.HOUR=61,le.IMPORT=62,le.INCLUDE=63,le.INNER=64,le.IS=65,le.IN=66,le.INTERNAL_KW=67,le.JSON=68,le.LAST=69,le.LEFT=70,le.LIKE=71,le.MAX=72,le.MIN=73,le.MINUTE=74,le.MONTH=75,le.NOT=76,le.NOW=77,le.NULL=78,le.NUMBER=79,le.ON=80,le.OR=81,le.PICK=82,le.PRIVATE_KW=83,le.PUBLIC_KW=84,le.QUARTER=85,le.RIGHT=86,le.SECOND=87,le.STRING=88,le.SOURCE_KW=89,le.SUM=90,le.SQL=91,le.TABLE=92,le.THEN=93,le.THIS=94,le.TIMESTAMP=95,le.TO=96,le.TRUE=97,le.TURTLE=98,le.WEEK=99,le.WHEN=100,le.WITH=101,le.YEAR=102,le.UNGROUPED=103,le.HACKY_REGEX=104,le.RAW_SQ=105,le.RAW_DQ=106,le.SQ3_FILTER=107,le.SQ_FILTER=108,le.DQ3_FILTER=109,le.DQ_FILTER=110,le.BQ3_FILTER=111,le.BQ_FILTER=112,le.SQ_STRING=113,le.DQ_STRING=114,le.BQ_STRING=115,le.DOC_ANNOTATION=116,le.ANNOTATION=117,le.AMPER=118,le.ARROW=119,le.FAT_ARROW=120,le.OPAREN=121,le.CPAREN=122,le.OBRACK=123,le.CBRACK=124,le.OCURLY=125,le.CCURLY=126,le.DOUBLECOLON=127,le.TRIPLECOLON=128,le.EXCLAM=129,le.COLON=130,le.COMMA=131,le.DOT=132,le.LT=133,le.GT=134,le.EQ=135,le.NE=136,le.LTE=137,le.GTE=138,le.PLUS=139,le.MINUS=140,le.STAR=141,le.STARSTAR=142,le.SLASH=143,le.BAR=144,le.SEMI=145,le.NOT_MATCH=146,le.MATCH=147,le.PERCENT=148,le.DOUBLE_QMARK=149,le.QMARK=150,le.LITERAL_TIMESTAMP=151,le.LITERAL_HOUR=152,le.LITERAL_DAY=153,le.LITERAL_QUARTER=154,le.LITERAL_MONTH=155,le.LITERAL_WEEK=156,le.LITERAL_YEAR=157,le.IDENTIFIER=158,le.PERCENT_LITERAL=159,le.NUMERIC_LITERAL=160,le.INTEGER_LITERAL=161,le.BLOCK_COMMENT=162,le.COMMENT_TO_EOL=163,le.WHITE_SPACE=164,le.SQL_BEGIN=165,le.CLOSE_CODE=166,le.UNWATED_CHARS_TRAILING_NUMBERS=167,le.UNEXPECTED_CHAR=168,le.OPEN_CODE=169,le.SQL_END=170,le.SQL_MODE=1,le.channelNames=["DEFAULT_TOKEN_CHANNEL","HIDDEN"],le.modeNames=["DEFAULT_MODE","SQL_MODE"],le.ruleNames=["SPACE_CHAR","ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","SQ","BQ","DQ","SQ3","DQ3","BQ3","RAW_CHAR","RAW3_CHAR","FILTER","RAWSTR","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","HEX","UNICODE","SAFE_NON_QUOTE","ESCAPED","STR_CHAR","SQ_STRING","DQ_STRING","BQ_STRING","F_TO_EOL","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","F_YEAR","F_DD","F_TZ","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","EXPONENT","NUMERIC_LITERAL","INTEGER_LITERAL","ID_CHAR","DIGIT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","CLOSE_CODE","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","SQL_CHAR","OPEN_CODE","SQL_END"],le._LITERAL_NAMES=[void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,"'&'","'->'","'=>'","'('","')'","'['","']'","'{'","'}'","'::'","':::'","'!'","':'","','","'.'","'<'","'>'","'='","'!='","'<='","'>='","'+'","'-'","'*'","'**'","'/'","'|'","';'","'!~'","'~'","'%'","'??'","'?'",void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,`'"""'`,"'}%'"],le._SYMBOLIC_NAMES=[void 0,"ACCEPT","AGGREGATE","CALCULATE","CALCULATION","CONNECTION","DECLARE","DIMENSION","EXCEPT","EXTENDQ","GROUP_BY","HAVING","INDEX","INTERNAL","JOIN_CROSS","JOIN_ONE","JOIN_MANY","LIMIT","MEASURE","NEST","ORDER_BY","PARTITION_BY","PRIMARY_KEY","PRIVATE","PROJECT","PUBLIC","QUERY","RENAME","RUN","SAMPLE","SELECT","SOURCE","TOP","WHERE","VIEW","TIMEZONE","ALL","AND","AS","ASC","AVG","BOOLEAN","BY","CASE","CAST","CONDITION","COUNT","COMPOSE","DATE","DAY","DESC","DISTINCT","ELSE","END","EXCLUDE","EXTEND","FALSE","FULL","FOR","FROM","HAS","HOUR","IMPORT","INCLUDE","INNER","IS","IN","INTERNAL_KW","JSON","LAST","LEFT","LIKE","MAX","MIN","MINUTE","MONTH","NOT","NOW","NULL","NUMBER","ON","OR","PICK","PRIVATE_KW","PUBLIC_KW","QUARTER","RIGHT","SECOND","STRING","SOURCE_KW","SUM","SQL","TABLE","THEN","THIS","TIMESTAMP","TO","TRUE","TURTLE","WEEK","WHEN","WITH","YEAR","UNGROUPED","HACKY_REGEX","RAW_SQ","RAW_DQ","SQ3_FILTER","SQ_FILTER","DQ3_FILTER","DQ_FILTER","BQ3_FILTER","BQ_FILTER","SQ_STRING","DQ_STRING","BQ_STRING","DOC_ANNOTATION","ANNOTATION","AMPER","ARROW","FAT_ARROW","OPAREN","CPAREN","OBRACK","CBRACK","OCURLY","CCURLY","DOUBLECOLON","TRIPLECOLON","EXCLAM","COLON","COMMA","DOT","LT","GT","EQ","NE","LTE","GTE","PLUS","MINUS","STAR","STARSTAR","SLASH","BAR","SEMI","NOT_MATCH","MATCH","PERCENT","DOUBLE_QMARK","QMARK","LITERAL_TIMESTAMP","LITERAL_HOUR","LITERAL_DAY","LITERAL_QUARTER","LITERAL_MONTH","LITERAL_WEEK","LITERAL_YEAR","IDENTIFIER","PERCENT_LITERAL","NUMERIC_LITERAL","INTEGER_LITERAL","BLOCK_COMMENT","COMMENT_TO_EOL","WHITE_SPACE","SQL_BEGIN","CLOSE_CODE","UNWATED_CHARS_TRAILING_NUMBERS","UNEXPECTED_CHAR","OPEN_CODE","SQL_END"],le.VOCABULARY=new Jdt.VocabularyImpl(le._LITERAL_NAMES,le._SYMBOLIC_NAMES,[]),le._serializedATNSegments=4,le._serializedATNSegment0=`줝쪺֍꾺体؇쉁¬ވ\b\b     \x07 \x07\b \b 
1558
1558