"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[5558],{45558:function(e,t,r){r.d(t,{A$:function(){return function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){let n=Object.entries(t);return n.length===Object.keys(r).length&&n.every(t=>{let[n,i]=t;return n in r&&e(i,r[n])})}return!1}},Dw:function(){return p},Kn:function(){return c},Xc:function(){return n.Xc},f6:function(){return a},hj:function(){return d},nQ:function(){return h},nd:function(){return m},o6:function(){return s},rs:function(){return o},u2:function(){return l},xL:function(){return i},xb:function(){return u}});var n=r(20037);function i(e){if(""===e.trim())return{value:null,error:void 0};try{return{value:JSON.parse(e),error:void 0}}catch(t){return{value:e,error:t}}}function a(e,t){let r=e;for(let e of t){if(!r)return null;r=r[e]}return r}function o(e,t,r){if(0===t.length)return r;let n=e;for(let e=0;e<t.length-1;e++)n[t[e]]||(n[t[e]]={}),n=n[t[e]];return n[t[t.length-1]]=r,e}function s(e,t){return ArrayBuffer.isView(t)?Array.from(t):t}function l(e){return"string"==typeof e?e:JSON.stringify(e,s,2)}function c(e){return e instanceof Object&&!(e instanceof Array)}function u(e){return null==e}function p(e){if(!u(e))return e;throw Error("Unexpected empty value ".concat(e))}function d(e){return"number"==typeof e||"bigint"==typeof e}function h(e,t){return e.localeCompare(t)>0?e:t}function m(e){return Object.keys(e)}BigInt.prototype.toJSON=function(){let e=this.toString(),t=parseInt(e);return BigInt(t)===this?t:e}},73928:function(e,t,r){r.d(t,{GZ:function(){return e9},IY:function(){return tE},qG:function(){return tT},tU:function(){return e7}});var n,i=r(95370),a=r(34846),o=["year","month","day","hour","minute","second","millisecond","microsecond"],s=i.z.enum(["true","false","null","and","or","not","is","as","includes","contains","like","ilike","filter","pivot","unpivot","dimensions","measures","select","from","sort","asc","desc","limit","cursor","interval",...o]),l={doubleSlash:"//",doubleDash:"--",slashStar:"/*",starSlash:"*/",lcurly:"{",rcurly:"}",lsquare:"[",rsquare:"]",lparen:"(",rparen:")",comma:",",colon:":",period:".",equalOp:"=",notEqualOp:"!=",doubleAngle:"<>",lessThanOrEqual:"<=",lessThan:"<",greaterThanOrEqual:">=",greaterThan:">",plus:"+",minus:"-",star:"*",slash:"/",percent:"%",pipe:"|",question:"?",word:/[a-zA-Z_][a-zA-Z0-9_]*/,singleQuotedString:/'(?:[^\\']|\\(?:[bfnrtv'\\/]|u[0-9a-fA-F]{4}))*?'/,doubleQuotedString:/"(?:[^\\"]|\\(?:[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*?"/,number:/-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/,whiteSpace:/[ \t\n\r]+/},c=i.z.strictObject({line:i.z.number(),col:i.z.number()}),u=class{get eof(){return this.cursor>=this.text.length}snapshot(){return{cursor:this.cursor,line:this._line,col:this._col}}restore(e){this.cursor=e.cursor,this._line=e.line,this._col=e.col}peekToken(){if(this.eof)return null;for(let[e,t]of Object.entries(this.rules)){t.lastIndex=this.cursor;let r=t.exec(this.text);if(r&&r.index===this.cursor){if("whiteSpace"===e)return this.cursor+=r[0].length,this.updateLineCol(r[0]),this.peekToken();if("slashStar"===e){let e=this.text.indexOf("*/",this.cursor+2);if(-1===e)throw Error("Unterminated comment");return this.cursor=e+2,this.updateLineCol(this.text.slice(r.index,this.cursor)),this.peekToken()}if("doubleSlash"===e||"doubleDash"===e){let e=this.text.indexOf("\n",this.cursor+2);return -1===e?this.cursor=this.text.length:this.cursor=e+1,this.updateLineCol(this.text.slice(r.index,this.cursor)),this.peekToken()}let t=e,n=r[0];return"word"===e&&s.safeParse(n.toLowerCase()).success&&(t=n.toLowerCase()),{type:t,value:n,line:this._line,col:this._col}}}throw Error("Unexpected character at ".concat(this.cursor,": ").concat(this.text.substring(this.cursor,this.cursor+10)))}updateLineCol(e){let t=e.split("\n").length-1;this._line+=t,this._col=0===t?this._col+e.length:e.length-e.lastIndexOf("\n")}nextToken(){let e=this.peekToken();return e&&(this.cursor+=e.value.length,this.current=e,this.updateLineCol(e.value)),e}currentToken(){return this.current}get line(){return this._line}get col(){return this._col}substringCursor(e,t){return this.text.substring(Math.max(this.cursor-e,0),Math.min(this.cursor+t,this.text.length))}*tokens(){let e;for(;e=this.nextToken();)yield e}constructor(e){this.text=e,this.cursor=0,this._line=1,this._col=1,this.rules=Object.fromEntries(Object.entries(l).map(e=>{let[t,r]=e;return[t,RegExp("string"==typeof r?r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):r,"y"+("object"==typeof r?r.flags:""))]})),this.current=null}},p=i.z.strictObject({start:c,end:c}),d=p.nullish(),h=i.z.literal(null),m=i.z.boolean(),f=i.z.number().int(),z=i.z.number(),b=i.z.string(),y=i.z.string().datetime(),g=i.z.array(i.z.lazy(()=>v)),_=i.z.record(i.z.lazy(()=>v)),v=i.z.union([h,m,f,z,b,y,g,i.z.lazy(()=>_)]),j=i.z.object({op:i.z.literal("literal"),value:v,loc:d}),x=i.z.enum(["year","month","day","hour","minute","second","millisecond","microsecond"]),k=i.z.strictObject({op:i.z.literal("interval"),value:i.z.number().int(),unit:x,loc:d}),O=i.z.strictObject({op:i.z.literal("ident"),name:i.z.array(i.z.string()),loc:d}),w=i.z.strictObject({op:i.z.literal("star"),replace:i.z.record(i.z.lazy(()=>F)).optional(),loc:d}),T=i.z.strictObject({op:i.z.literal("function"),name:O,args:i.z.array(i.z.lazy(()=>F)),loc:d}),E=["eq","is","ne","lt","le","gt","ge","ilike","like"],I=i.z.strictObject({op:i.z.enum(E),left:i.z.lazy(()=>F),right:i.z.lazy(()=>F),loc:d}),A=i.z.strictObject({op:i.z.literal("includes"),haystack:i.z.lazy(()=>F),needle:i.z.lazy(()=>F),loc:d}),S=["and","or"],N=i.z.strictObject({op:i.z.enum(S),left:i.z.lazy(()=>F),right:i.z.lazy(()=>F),loc:d}),L=["add","sub","mul","div","mod"],R=i.z.strictObject({cond:i.z.lazy(()=>F),then:i.z.lazy(()=>F)}),U=i.z.strictObject({op:i.z.literal("if"),conds:i.z.array(R),else:i.z.lazy(()=>F),loc:d}),P=i.z.strictObject({op:i.z.enum(L),left:i.z.lazy(()=>F),right:i.z.lazy(()=>F),loc:d}),q=["neg"],M=i.z.strictObject({op:i.z.enum(q),expr:i.z.lazy(()=>F),loc:d}),C=i.z.strictObject({op:i.z.enum(["not","isnull","isnotnull"]),expr:i.z.lazy(()=>F),loc:d}),D=i.z.strictObject({btql:i.z.string(),op:i.z.literal("btql").nullish(),loc:p.nullish()}),F=i.z.union([j,k,O,w,T,I,A,N,U,M,C,P,D]),B=i.z.strictObject({expr:F,alias:i.z.string()}),V=i.z.strictObject({expr:F,alias:i.z.union([i.z.string(),i.z.tuple([i.z.string(),i.z.string()])])}),J=i.z.enum(["asc","desc"]),Q=i.z.strictObject({expr:F,dir:J,loc:p.nullish()});i.z.strictObject({dimensions:i.z.array(B).nullish(),pivot:i.z.array(B).nullish(),unpivot:i.z.array(V).nullish(),measures:i.z.array(B).nullish(),select:i.z.array(i.z.union([B,w])).nullish(),filter:F.nullish(),from:i.z.union([O,T]).nullish(),sort:i.z.array(Q).nullish(),limit:i.z.number().int().nullish(),cursor:i.z.string().nullish()});var G=i.z.string(),$=i.z.string(),Y=i.z.string(),W=i.z.string(),H=i.z.string(),Z=i.z.string(),X=i.z.any(),K=i.z.boolean(),ee=i.z.array(X),et=i.z.number(),er=i.z.number(),en=i.z.number(),ei=i.z.number(),ea=i.z.number(),eo=i.z.number().nonnegative(),es=i.z.number().nonnegative().default(0),el=i.z.string(),ec=i.z.array(i.z.lazy(()=>eT)),eu=i.z.union([i.z.lazy(()=>eT),ec]).default(!0),ep=i.z.boolean(),ed=i.z.string(),eh=i.z.array(ed).default([]),em=i.z.record(i.z.any()).default({}),ef=i.z.record(i.z.any()).default({}),ez=i.z.record(i.z.any()).default({});i.z.union([i.z.lazy(()=>eT),eh]);var eb=i.z.record(i.z.any()),ey=i.z.array(X),eg=i.z.enum(["array","boolean","integer","null","number","object","string"]),e_=i.z.array(eg),ev=i.z.union([eg,e_]),ej=i.z.string(),ex=i.z.string(),ek=i.z.string(),eO=i.z.object({$id:G.optional(),$schema:$.optional(),$ref:Y.optional(),$comment:W.optional(),title:H.optional(),description:Z.optional(),default:X.optional(),readOnly:K.optional(),examples:ee.optional(),multipleOf:et.optional(),maximum:er.optional(),exclusiveMaximum:en.optional(),minimum:ei.optional(),exclusiveMinimum:ea.optional(),maxLength:eo.optional(),minLength:es.optional(),pattern:el.optional(),additionalItems:i.z.lazy(()=>eT.optional()),items:eu.optional(),maxItems:eo.optional(),minItems:es.optional(),uniqueItems:ep.optional(),contains:i.z.lazy(()=>eT.optional()),maxProperties:eo.optional(),minProperties:es.optional(),required:eh.optional(),additionalProperties:i.z.lazy(()=>eT.optional()),definitions:em.optional(),properties:ef.optional(),patternProperties:ez.optional(),dependencies:eb.optional(),propertyNames:i.z.lazy(()=>eT.optional()),const:X.optional(),enum:ey.optional(),type:ev.optional(),format:ej.optional(),contentMediaType:ex.optional(),contentEncoding:ek.optional(),if:i.z.lazy(()=>eT.optional()),then:i.z.lazy(()=>eT.optional()),else:i.z.lazy(()=>eT.optional()),allOf:ec.optional(),anyOf:ec.optional(),oneOf:ec.optional(),not:i.z.lazy(()=>eT.optional())}).catchall(i.z.any()),ew=i.z.boolean(),eT=i.z.union([eO,ew]),eE=i.z.union([i.z.strictObject({type:i.z.enum(["bigint","bit","blob","boolean","date","double","hugeint","integer","interval","real","smallint","time","timestamp with time zone","timestamp","tinyint","ubigint","uhugeint","uinteger","usmallint","utinyint","uuid","varchar","json"])}),i.z.strictObject({type:i.z.literal("decimal"),prec:i.z.number().int().optional(),scale:i.z.number().int().optional()})]),eI=i.z.object({type:i.z.literal("array"),items:i.z.lazy(()=>eN)}),eA=i.z.object({type:i.z.literal("struct"),fields:i.z.lazy(()=>i.z.record(eN))}),eS=i.z.object({type:i.z.literal("map"),key:i.z.lazy(()=>eE),value:i.z.lazy(()=>eN)}),eN=i.z.union([eE,eI,eS,eA]),eL=i.z.strictObject({path:i.z.array(i.z.string()),type:eN}),eR=i.z.strictObject({columns:i.z.record(eL)}),eU=i.z.union([i.z.strictObject({type:i.z.enum(["bigint","bigserial","bit","bit varying","boolean","box","bytea","character","character varying","cidr","circle","date","double precision","inet","integer","interval","json","jsonb","line","lseg","macaddr","macaddr8","money","path","pg_lsn","pg_snapshot","point","polygon","real","smallint","smallserial","serial","text","time","time with time zone","timestamp","timestamptz","timestamp with time zone","tsquery","tsvector","txid_snapshot","uuid","xml"])}),i.z.strictObject({type:i.z.literal("numeric"),prec:i.z.number().int().optional(),scale:i.z.number().int().optional()})]),eP=i.z.strictObject({path:i.z.array(i.z.string()),type:eU}),eq=i.z.strictObject({columns:i.z.record(eP)}),eM=i.z.union([i.z.strictObject({type:i.z.enum(["UInt8","UInt16","UInt32","UInt64","UInt128","UInt256","Int8","Int16","Int32","Int64","Int128","Int256","Float32","Float64","Boolean","String","FixedString","Date","DateTime","DateTime64","JSON","UUID","IPv4","IPv6","Point","Ring","Polygon","MultiPolygon","Nothing","Interval"])}),i.z.strictObject({type:i.z.literal("Decimal"),precision:i.z.number(),scale:i.z.number()})]),eC=i.z.object({type:i.z.literal("Array"),items:i.z.lazy(()=>eJ)}),eD=i.z.object({type:i.z.literal("Nullable"),inner:i.z.lazy(()=>eJ)}),eF=i.z.object({type:i.z.literal("Enum"),values:i.z.record(i.z.number())}),eB=i.z.object({type:i.z.literal("LowCardinality"),inner:i.z.lazy(()=>eJ)}),eV=i.z.object({type:i.z.literal("Map"),key:i.z.lazy(()=>eJ),value:i.z.lazy(()=>eJ)}),eJ=i.z.union([eM,eC,eD,eF,eB,eV]),eQ=i.z.strictObject({path:i.z.array(i.z.string()),type:eJ}),eG=i.z.strictObject({columns:i.z.record(eQ)});function e$(e){return"object"==typeof e?e:!0===e?{}:{not:{}}}(e=>{function t(e){return{type:e}}e.scalar=t,e.nullable=function(e){return{type:"Nullable",inner:t(e)}},e.array=function(e){return{type:"Array",items:t(e)}},e.record=function(e){return{type:"Map",key:t("String"),value:e}}})(n||(n={}));var eY=new a({coerceTypes:!1});eY.addFormat("uuid",{type:"string",validate:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}),eY.addFormat("date-time",{type:"string",validate:e=>!isNaN(Date.parse(e))});var eW=["array","boolean","integer","null","number","object","string","date","datetime","interval"],eH=i.z.enum(eW);function eZ(e){switch(e){case"array":case"boolean":case"integer":case"object":case"null":case"number":case"string":return{type:e};case"date":return{type:"string",format:"date"};case"datetime":return{type:"string",format:"date-time"};case"interval":return{type:"string",format:"duration"}}}function eX(e){return"object"!=typeof e?e?[...eW]:["null"]:e.type&&!Array.isArray(e.type)?["string"===e.type&&"date-time"===e.format?"datetime":"string"===e.type&&"date"===e.format?"date":"string"===e.type&&"duration"===e.format?"interval":e.type]:Array.isArray(e)||Array.isArray(e.type)||e.anyOf||e.oneOf?[...new Set((Array.isArray(e)?e:e.type||e.anyOf||e.oneOf).flatMap(e=>"string"==typeof e?[e]:eX(e)))]:e.allOf?e.allOf.map(e=>eX(e)).reduce((e,t)=>e.filter(e=>t.includes(e)),[...eW]):[...eW]}i.z.union([eR,eq,eG]),i.z.union([i.z.strictObject({type:i.z.literal("duckdb"),tables:i.z.record(eR)}),i.z.strictObject({type:i.z.literal("postgres"),tables:i.z.record(eq)}),i.z.strictObject({type:i.z.literal("clickhouse"),tables:i.z.record(eG)})]);var eK=class extends Error{constructor(e,t,r,n,i){let a=Array.isArray(t)?t.join(", "):t;super("".concat(e).concat(a?" (expected '"+a+"')":""," at line ").concat(r,", col ").concat(n).concat(i?" ".concat(i):"")),this.prefix=e,this.expected=t,this.line=r,this.col=n,this.suffix=i}},e0=class{parseQuery(){let e={};for(;;){let t=this.tokenizer.nextToken();for(;t&&"pipe"===t.type;)t=this.tokenizer.nextToken();if(!t)break;switch(t.type){case"dimensions":case"measures":case"pivot":e[t.type]&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e[t.type]=this.parseList(this.parseAliasExpr.bind(this),"comma");break;case"unpivot":e.select&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e.unpivot=this.parseList(this.parseUnpivotAliasExpr.bind(this),"comma");break;case"select":e.select&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e.select=this.parseList(this.parseAliasOrStar.bind(this),"comma");break;case"filter":e.filter&&this.fail("filter already defined"),this.mustReadToken("filter","colon"),e.filter=this.parseExpr();break;case"from":e.from&&this.fail("from already defined"),this.mustReadToken("from","colon");let r=this.parseIdentOrFunction();e.from="literal"===r.op?e4(r):r;break;case"sort":e.sort&&this.fail("sort already defined"),this.mustReadToken("sort","colon"),e.sort=this.parseList(this.parseSortExpr.bind(this),"comma");break;case"limit":e.limit&&this.fail("limit already defined"),this.mustReadToken("limit","colon");let n=this.mustReadToken("limit","number");e1(n.value)||this.fail("limit must be an integer"),e.limit=parseInt(n.value);break;case"cursor":e.cursor&&this.fail("cursor already defined"),this.mustReadToken("cursor","colon");let i=this.mustReadToken("cursor");"singleQuotedString"!==i.type&&"doubleQuotedString"!==i.type&&this.fail("cursor must be a string"),e.cursor=e2(i.value,"singleQuotedString"===i.type?"'":'"');break;default:this.failOp("query",["dimensions","pivot","unpivot","measures","select","filter","from","sort","limit","cursor"].filter(t=>!e[t]))}}return e}finished(){return this.tokenizer.eof}parseAliasExpr(){let e=this.parseExpr();e.loc||this.fail("no location information for alias expression");let t="ident"===e.op?e.name[e.name.length-1]:this.query.substring(e.loc.start.col-1,e.loc.end.col-1),r=this.tokenizer.peekToken();return r&&"as"===r.type&&(t=this.parseAliasValue()),{expr:e,alias:t}}parseAliasValue(){this.tokenizer.nextToken();let e=this.tokenizer.nextToken();return e&&this.isIdentPart(e)||this.failOp("alias expression",["identifier"]),e.value}parseUnpivotAliasExpr(){let e;let t=this.parseExpr();t.loc||this.fail("no location information for alias expression"),this.mustReadToken("unpivot alias expression","as");let r=this.tokenizer.peekToken();switch(r||this.failOp("unpivot alias expression",["identifier"]),r.type){case"word":case"doubleQuotedString":e=this.parseAliasValue();break;case"lparen":this.mustReadToken("unpivot alias expression","lparen");let n=this.parseAliasValue();this.mustReadToken("unpivot alias expression","comma");let i=this.parseAliasValue();this.mustReadToken("unpivot alias expression","rparen"),e=[n,i];break;default:this.failOp("unpivot alias expression",["identifier"])}return{expr:t,alias:e}}parseAliasOrStar(){var e;return(null==(e=this.tokenizer.peekToken())?void 0:e.type)==="star"?(this.mustReadToken("select","star"),{op:"star"}):this.parseAliasExpr()}parseSortExpr(){var e,t,r;let n=this.parseExpr(),i=null==(e=n.loc)?void 0:e.start,a=null==(t=n.loc)?void 0:t.end,o="asc";switch(null==(r=this.tokenizer.peekToken())?void 0:r.type){case"asc":case"desc":let s=this.tokenizer.nextToken();o=null==s?void 0:s.type,a=e6(s).end}return{expr:n,dir:o,loc:i&&a?{start:i,end:a}:void 0}}parseList(e,t){let r=[];for(;;){let n=this.tokenizer.snapshot();try{r.push(e())}catch(e){console.error(e),this.tokenizer.restore(n);break}let i=this.tokenizer.peekToken();if(!i||i.type!==t)break;this.tokenizer.nextToken()}return r}parseExpr(){if(++this.exprGuard>this.maxExprDepth)throw Error("Maximum expression depth exceeded");let e=this.parseTernaryExpr();return--this.exprGuard,e}parseTernaryExpr(){var e,t;let r=this.parseOrExpr(),n=null==(e=r.loc)?void 0:e.start,i=this.tokenizer.peekToken();if((null==i?void 0:i.type)==="question"){this.tokenizer.nextToken();let e=this.parseOrExpr();this.mustReadToken("ternary expression","colon");let i=this.parseTernaryExpr(),a=null==(t=i.loc)?void 0:t.end,o=[{cond:r,then:e}],s=i;return"if"===i.op&&(o.push(...i.conds),s=i.else),{op:"if",conds:o,else:s,loc:n&&a?{start:n,end:a}:void 0}}return r}parseLeftAssocExpr(e,t,r){var n,i;let a=e(),o=null==(n=a.loc)?void 0:n.start,s=Array.isArray(t)?t:[t];for(;;){let t=this.tokenizer.peekToken();if(!t||!s.includes(t.type))break;this.tokenizer.nextToken();let n=e(),l=null==(i=n.loc)?void 0:i.end;a=r(a,n,t.type,o&&l?{start:o,end:l}:void 0)}return a}parseRightAssocExpr(e,t,r){var n,i;let a=e(),o=null==(n=a.loc)?void 0:n.start,s=Array.isArray(t)?t:[t],l=this.tokenizer.peekToken();if(l&&s.includes(l.type)){this.tokenizer.nextToken();let n=this.parseRightAssocExpr(e,t,r),s=null==(i=n.loc)?void 0:i.end;return r(a,n,l.type,o&&s?{start:o,end:s}:void 0)}return a}parseOrExpr(){return this.parseLeftAssocExpr(this.parseAndExpr.bind(this),"or",(e,t,r,n)=>({op:"or",left:e,right:t,loc:n}))}parseAndExpr(){return this.parseLeftAssocExpr(this.parseNotExpr.bind(this),"and",(e,t,r,n)=>({op:"and",left:e,right:t,loc:n}))}parseNotExpr(){var e,t;if((null==(e=this.tokenizer.peekToken())?void 0:e.type)==="not"){let e=this.tokenizer.nextToken(),r=this.parseNotExpr(),n=e6(e).start,i=null==(t=r.loc)?void 0:t.end;return{op:"not",expr:r,loc:i?{start:n,end:i}:void 0}}return this.parseEqualityExpr()}parseEqualityExpr(){return this.parseRightAssocExpr(this.parseInequalityExpr.bind(this),["equalOp","notEqualOp","doubleAngle","includes","contains","like","ilike"],(e,t,r,n)=>"equalOp"===r?{op:"eq",left:e,right:t,loc:n}:"notEqualOp"===r||"doubleAngle"===r?{op:"ne",left:e,right:t,loc:n}:"like"===r||"ilike"===r?{op:r,left:e,right:t,loc:n}:{op:"includes",haystack:e,needle:t,loc:n})}parseInequalityExpr(){return this.parseRightAssocExpr(this.parseIsExpr.bind(this),["lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual"],(e,t,r,n)=>({op:"lessThan"===r?"lt":"lessThanOrEqual"===r?"le":"greaterThan"===r?"gt":"ge",left:e,right:t,loc:n}))}parseIsExpr(){var e,t,r,n;let i=this.parseAddExpr(),a=null==(e=i.loc)?void 0:e.start,o=this.tokenizer.peekToken();if((null==o?void 0:o.type)==="is"){if(this.tokenizer.nextToken(),(null==(t=this.tokenizer.peekToken())?void 0:t.type)==="not"){this.tokenizer.nextToken();let e=this.mustReadToken("is not","null");return{op:"isnotnull",expr:i,loc:a?{start:a,end:e6(e).end}:void 0}}if((null==(r=this.tokenizer.peekToken())?void 0:r.type)==="null"){let e=this.mustReadToken("is","null");return{op:"isnull",expr:i,loc:a?{start:a,end:e6(e).end}:void 0}}{let e=this.parsePrimaryExpr(!0),t=null==(n=e.loc)?void 0:n.end;return{op:"is",left:i,right:e,loc:a&&t?{start:a,end:t}:void 0}}}return i}parseAddExpr(){return this.parseLeftAssocExpr(this.parseMulExpr.bind(this),["plus","minus"],(e,t,r,n)=>({op:"plus"===r?"add":"sub",left:e,right:t,loc:n}))}parseMulExpr(){return this.parseLeftAssocExpr(this.parseUnaryExpr.bind(this),["star","slash","percent"],(e,t,r,n)=>({op:"star"===r?"mul":"slash"===r?"div":"mod",left:e,right:t,loc:n}))}parseUnaryExpr(){var e,t;if((null==(e=this.tokenizer.peekToken())?void 0:e.type)==="minus"){let e=e6(this.tokenizer.nextToken()).start,t=this.parseUnaryExpr();return{op:"neg",expr:t,loc:t.loc?{start:e,end:t.loc.end}:void 0}}return(null==(t=this.tokenizer.peekToken())?void 0:t.type)==="plus"?(this.tokenizer.nextToken(),this.parseUnaryExpr()):this.parsePrimaryExpr(!0)}parsePrimaryExpr(e){let t=this.tokenizer.nextToken();switch(t||this.failOp("primary expression"),t.type){case"true":return{op:"literal",value:!0,loc:e6(t)};case"false":return{op:"literal",value:!1,loc:e6(t)};case"null":return{op:"literal",value:null,loc:e6(t)};case"star":return{op:"star",loc:e6(t)};case"number":return{op:"literal",value:e1(t.value)?parseInt(t.value):parseFloat(t.value),loc:e6(t)};case"singleQuotedString":return{op:"literal",value:e2(t.value,"'"),loc:e6(t)};case"lsquare":let r=this.tokenizer.peekToken();if((null==r?void 0:r.type)==="rsquare")return this.tokenizer.nextToken(),{op:"literal",value:[],loc:{start:e6(t).start,end:e6(r).end}};return{op:"literal",value:this.parseList(this.parseLiteral.bind(this),"comma"),loc:{start:e6(t).start,end:e6(this.mustReadToken("list","rsquare")).end}};case"lcurly":{let e=this.tokenizer.peekToken();if((null==e?void 0:e.type)==="rcurly")return this.tokenizer.nextToken(),{op:"literal",value:{},loc:{start:e6(t).start,end:e6(e).end}};return{op:"literal",value:Object.fromEntries(this.parseList(this.parseObjectPair.bind(this),"comma")),loc:{start:e6(t).start,end:e6(this.mustReadToken("object","rcurly")).end}}}case"interval":let n=this.mustReadToken("interval","number");e1(n.value)||this.fail("interval value must be an integer");let i=this.mustReadToken("interval"),a=x.safeParse(i.value.toLowerCase());return!0!==a.success&&this.fail("invalid interval unit"),{op:"interval",value:parseInt(n.value),unit:a.data,loc:{start:e6(t).start,end:e6(i).end}};case"lparen":e||this.fail("Cannot parse nested expressions in this context");let o=this.parseExpr();return this.mustReadToken("primary expression","rparen"),o}if(this.isIdentPart(t))return this.parseIdentOrFunction(t);this.failOp("primary expression",["number","singleQuotedString"])}parseLiteral(){let e=this.parsePrimaryExpr(!1);return"literal"!==e.op&&this.fail("literal"),e.value}parseObjectPair(){let e;let t=this.parsePrimaryExpr(!1);return"ident"===t.op?(1!==t.name.length&&this.fail("object key must be a single identifier"),e=t.name[0]):"literal"===t.op?("string"!=typeof t.value&&this.fail("object key must be a string"),e=t.value):this.fail("object key must be a string or identifier"),this.mustReadToken("object pair","colon"),[e,this.parseLiteral()]}isIdentPart(e){return["word","doubleQuotedString",...o].includes(e.type)}parseIdent(e){var t,r;e||(e=this.mustReadToken("identifier")),this.isIdentPart(e)||this.failOp("ident",["word"]);let n=e=>"doubleQuotedString"===e.type?e2(e.value,'"'):e.value,i=[n(e)],a=e6(e).start,o=e6(e).end;if((null==(t=this.tokenizer.peekToken())?void 0:t.type)==="period")for(;(null==(r=this.tokenizer.peekToken())?void 0:r.type)==="period";){this.tokenizer.nextToken();let e=this.tokenizer.nextToken();e&&this.isIdentPart(e)||this.failOp("primary expression",["identifier"]),i.push(n(e)),o=e6(e).end}else if("doubleQuotedString"===e.type)return{op:"literal",value:i[0],loc:e6(e)};return{op:"ident",name:i,loc:{start:a,end:o}}}parseIdentOrFunction(e){var t,r;let n=this.parseIdent(e);if((null==(t=this.tokenizer.peekToken())?void 0:t.type)!=="lparen")return n;{this.tokenizer.nextToken();let e=[];(null==(r=this.tokenizer.peekToken())?void 0:r.type)!=="rparen"&&(e=this.parseList(this.parseExpr.bind(this),"comma"));let t=this.mustReadToken("function call","rparen");return{op:"function",name:e4(n),args:e,loc:{start:n.loc.start,end:e6(t).end}}}}mustReadToken(e,t){let r=this.tokenizer.nextToken();return r?t&&r.type!==t&&this.failOp(e,t):this.failOp(e),r}fail(e,t){var r;if(this.tokenizer.eof)throw new eK(e,t,this.tokenizer.line,this.tokenizer.col,"unexpected end of input");let n=this.tokenizer.currentToken(),i=(null==(r=this.tokenizer.currentToken())?void 0:r.value)||"",a=this.tokenizer.substringCursor(10,10);throw new eK(e,t,(null==n?void 0:n.line)||this.tokenizer.line,(null==n?void 0:n.col)||this.tokenizer.col,"at".concat(i?" ".concat(i):"").concat(a?" near '".concat(a,"'"):""))}failOp(e,t){this.fail("Failed to parse "+e,t)}constructor(e,t={}){this.query=e,this.exprGuard=0,this.tokenizer=new u(e),this.maxExprDepth=t.maxExprDepth||100}};function e1(e){if(!(e=e.trim()))return!1;let t=Math.floor(Number(e=e.replace(/^0+/,"")||"0"));return t!==1/0&&String(t)===e&&t>=0}function e2(e,t){return e[0]!==t||e[e.length-1]!==t?e:e.slice(1,-1)}function e6(e){return{start:{line:e.line,col:e.col},end:{line:e.line,col:e.col+e.value.length}}}function e4(e){if("ident"===e.op)return e;if("string"==typeof e.value)return{op:"ident",name:[e.value],loc:e.loc};throw Error("Expected string literal")}function e3(e){switch(e.op){case"literal":case"cast":return eZ(e.type);case"interval":return eZ("interval");case"field":return e.type;case"function":let t=ta[e.name],r=Object.fromEntries(Object.keys(t.args.named).map((t,r)=>[t,e3(e.args[r])])),n=e.args.slice(Object.keys(t.args.named).length).map(e3);return ta[e.name].type(r,n);case"eq":case"is":case"ne":case"lt":case"le":case"gt":case"ge":case"like":case"ilike":case"includes":case"and":case"or":case"not":case"isnull":case"isnotnull":return{type:"boolean"};case"add":case"sub":case"mul":case"div":case"mod":let i=e5(e.left),a=e5(e.right);if("integer"===i&&"integer"===a)return{type:"integer"};if(e8("datetime",i,a))return eZ("datetime");if(e8("date",i,a))return eZ("date");return{type:"number"};case"if":return e3(e.else);case"neg":return e3(e.expr)}}function e8(e,t,r){return t===e&&"interval"===r||"interval"===t&&r===e}var e9=i.z.strictObject({type:i.z.literal("array"),items:i.z.strictObject({type:i.z.literal("object"),properties:i.z.record(eO)})});function e5(e){return e7(e3(e))}function e7(e){return eX(e).sort((e,t)=>tt(e)-tt(t))[0]}function te(e){let t=Math.min(...e.map(e=>tt(e)));return e.find(e=>tt(e)===t)}function tt(e){switch(e){case"null":return 9;case"interval":return 8;case"datetime":return 7;case"date":return 6;case"boolean":return 5;case"integer":return 4;case"number":return 3;case"string":return 2;case"array":return 1;case"object":return 0}}i.z.strictObject({isAgg:i.z.boolean(),args:i.z.strictObject({named:i.z.record(eT),variadic:i.z.array(eT).optional()}),type:i.z.function(i.z.tuple([i.z.record(eT),i.z.array(eT)]),eO)});var tr=i.z.enum(["second","minute","hour","day","week","month","year","current_timestamp","current_date","insert","coalesce","nullif","least","greatest","count","sum","avg","min","max","percentile"]),tn={isAgg:!1,args:{named:{expr:[{type:"string",format:"date-time"}]}},type:()=>({type:"string",format:"date-time"})},ti={isAgg:!1,args:{named:{},variadic:[{}]},type:(e,t)=>eZ(te(t.map(e$).map(e7)))},ta={second:tn,minute:tn,hour:tn,day:tn,week:tn,month:tn,year:tn,current_timestamp:{isAgg:!1,args:{named:{}},type:()=>({type:"string",format:"date-time"})},current_date:{isAgg:!1,args:{named:{}},type:()=>({type:"string",format:"date"})},insert:{isAgg:!1,args:{named:{expr:[{}]},variadic:[{type:"string"},{}]},type:e=>{let{expr:t}=e;return e$(t)}},coalesce:ti,least:ti,greatest:ti,nullif:{isAgg:!1,args:{named:{left:[{}],right:[{}]}},type:e=>{let{left:t,right:r}=e;return eZ(te([t,r].map(e$).map(e7)))}},count:{isAgg:!0,args:{named:{expr:{default:1}}},type:()=>({type:"integer"})},sum:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}]}},type:e=>{let{expr:t}=e;return"integer"===e7(e$(t))?{type:["integer","null"]}:{type:["number","null"]}}},avg:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}]}},type:e=>{let{expr:t}=e;return{type:["number","null"]}}},min:{isAgg:!0,args:{named:{expr:[{}]}},type:e=>{let{expr:t}=e;return e$(t)}},max:{isAgg:!0,args:{named:{expr:[{}]}},type:e=>{let{expr:t}=e;return e$(t)}},percentile:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}],p:[{type:"number"}]}},type:e=>{let{expr:t}=e;return{type:["number","null"]}}}},to={now:"current_timestamp"},ts=i.z.strictObject({op:i.z.literal("literal"),value:i.z.unknown(),type:eH}),tl=i.z.strictObject({op:i.z.literal("interval")}).merge(k.omit({loc:!0})),tc=i.z.strictObject({op:i.z.literal("field"),name:i.z.array(i.z.string()),type:eO,source:i.z.strictObject({unpivot:i.z.number().int(),type:i.z.enum(["key","value","element"])}).nullish()}),tu=i.z.strictObject({op:i.z.literal("function"),name:tr,args:i.z.array(i.z.lazy(()=>t_)),type:eO}),tp=i.z.strictObject({op:i.z.enum(E),left:i.z.lazy(()=>t_),right:i.z.lazy(()=>t_)}),td=i.z.strictObject({op:i.z.literal("includes"),haystack:i.z.lazy(()=>t_),needle:i.z.lazy(()=>t_)}),th=i.z.strictObject({op:i.z.enum(S),left:i.z.lazy(()=>t_),right:i.z.lazy(()=>t_)}),tm=i.z.strictObject({cond:i.z.lazy(()=>t_),then:i.z.lazy(()=>t_)}),tf=i.z.strictObject({op:i.z.literal("if"),conds:i.z.array(tm),else:i.z.lazy(()=>t_)}),tz=i.z.strictObject({op:i.z.enum(L),left:i.z.lazy(()=>t_),right:i.z.lazy(()=>t_)}),tb=i.z.strictObject({op:i.z.enum(q),expr:i.z.lazy(()=>t_)}),ty=i.z.strictObject({op:i.z.enum(["not","isnull","isnotnull"]),expr:i.z.lazy(()=>t_)}),tg=i.z.strictObject({op:i.z.literal("cast"),expr:i.z.lazy(()=>t_),type:eH}),t_=i.z.union([ts,tl,tc,tu,tp,td,th,tf,tz,tb,ty,tg]),tv=i.z.strictObject({expr:t_,alias:i.z.string()}),tj=i.z.strictObject({expr:t_,type:i.z.enum(["object","array"])}),tx=i.z.union([i.z.object({dimensions:i.z.array(tv),pivot:i.z.array(tv),measures:i.z.array(tv)}),i.z.object({select:i.z.array(tv)})]),tk=i.z.strictObject({name:i.z.string(),objects:i.z.array(i.z.string()).nullish()}),tO=i.z.object({dir:J}).and(i.z.union([i.z.object({alias:i.z.string()}),i.z.object({expr:t_})])),tw=i.z.array(tO);function tT(e,t){var r;let n="btql"in(r=t.expr)?new e0(r.btql).parseExpr():r;return"ident"===n.op&&1===n.name.length&&e.scope[n.name[0]]?{alias:n.name[0],dir:t.dir}:{expr:tE(e,n),dir:t.dir}}function tE(e,t){if("btql"in t)return tE(e,new e0(t.btql).parseExpr());switch(t.op){case"literal":return function(e,t){var r;if("literal"!==t.op)throw Error("Expected literal");let n=null===(r=t.value)?"null":!0===r||!1===r?"boolean":f.safeParse(r).success?"integer":z.safeParse(r).success?"number":m.safeParse(r).success?"boolean":y.safeParse(r).success?"datetime":b.safeParse(r).success?"string":g.safeParse(r).success?"array":_.safeParse(r).success?"object":null;return n||tI(e,"Invalid literal: ".concat(JSON.stringify(t.value)),t.loc),{op:"literal",value:t.value,type:n}}(e,t);case"interval":return{op:"interval",value:t.value,unit:t.unit};case"ident":return function e(t,r){var n,i,a;if(0===r.name.length&&tI(t,"Invalid empty field reference",r.loc),t.scope[r.name[0]]&&1===r.name.length)return{...t.scope[r.name[0]]};let o=t.schema;for(let s=0;s<r.name.length;s++){i=t,"object"==typeof(a=o)&&!Array.isArray(a)||tI(i,"Invalid field schema: ".concat(JSON.stringify(a)),null);let l=r.name[s];if("null"===o.type){o={};break}if(("object"!=typeof o||Array.isArray(o)||o.type&&"object"!==o.type)&&tI(t,'Trying to access field "'.concat(l,'" in a non-object').concat("type"in o?" ("+o.type+")":""," ").concat(JSON.stringify(o)),r.loc),"object"===o.type){let e=null==(n=o.properties)?void 0:n[l];if(!e&&o.additionalProperties&&(e=o.additionalProperties),!e){if(0===s)switch(l.toLowerCase()){case"current_timestamp":return{op:"function",name:"current_timestamp",args:[]};case"current_date":return{op:"function",name:"current_date",args:[]}}tI(t,"Field ".concat(l," not found"),r.loc)}(Array.isArray(e)||"object"!=typeof e)&&tI(t,"Invalid field schema: ".concat(JSON.stringify(e)),r.loc),o=e}else if(o.additionalProperties)"object"==typeof o.additionalProperties?o=o.additionalProperties:tI(t,"Invalid field schema: ".concat(JSON.stringify(o.additionalProperties)),r.loc);else if(o.anyOf||Array.isArray(o.type)){o={anyOf:(o.anyOf||o.type).map(n=>e({...t,schema:"object"==typeof n?n:n?{}:tI(t,"Invalid field schema: ".concat(JSON.stringify(n)),r.loc),scope:{}},{op:"ident",name:r.name.slice(s),loc:r.loc})).map(e=>e3(e))};break}else o.oneOf?tI(t,"oneOf not supported yet",r.loc):o.allOf?tI(t,"allOf not supported yet",r.loc):o.not?tI(t,"not not supported yet",r.loc):o.enum?tI(t,"enum not supported yet",r.loc):o.const?tI(t,"const not supported yet",r.loc):o.$ref?tI(t,"$ref not supported yet",r.loc):o.$defs?tI(t,"$defs not supported yet",r.loc):o.$id?tI(t,"$id not supported yet",r.loc):o.$schema?tI(t,"$schema not supported yet",r.loc):o.multipleOf?tI(t,"multipleOf not supported yet",r.loc):o.if?tI(t,"if not supported yet",r.loc):o.then?tI(t,"then not supported yet",r.loc):o.else?tI(t,"else not supported yet",r.loc):o.type?tI(t,'Trying to access field "'.concat(l,'" in a non-object (').concat(o.type,") ").concat(JSON.stringify(o)),r.loc):o={}}return{op:"field",name:r.name,type:function e(t){if("object"!=typeof t)return{};if(t.anyOf){let r=t.anyOf.map(e).filter(e=>null!==e&&Object.keys(e).length>0&&!(e.not&&0===Object.keys(e.not).length));return 0===r.length?{}:1===r.length?r[0]:{anyOf:r}}return"object"===t.type?{...t,properties:Object.fromEntries(Object.entries(t.properties||{}).map(t=>{let[r,n]=t;return[r,e(n)]})),additionalProperties:t.additionalProperties&&"object"==typeof t.additionalProperties?e(t.additionalProperties):void 0}:"array"===t.type?{...t,items:Array.isArray(t.items)?t.items.map(e):t.items}:t}(o)}}(e,t);case"star":return tI(e,"Unsupported star expression",t.loc);case"function":return function(e,t){var r,n;1!==t.name.name.length&&tI(e,"Invalid function name",t.loc);let i=t.name.name[0].toLowerCase();to[i]&&(i=to[i]);let a=tr.safeParse(i);a.success||tI(e,"Unknown function: ".concat(t.name.name[0]),t.loc);let o=a.data,s=ta[o];!e.bindingMeasures&&s.isAgg&&tI(e,"Cannot use aggregate function in non-measure context",t.loc);let l=null!=(n=null==(r=s.args.variadic)?void 0:r.length)?n:0;(l>0&&t.args.length<Object.keys(s.args.named).length||0===l&&t.args.length!==Object.keys(s.args.named).length)&&tI(e,"Expected ".concat(Object.keys(s.args).length," arguments (received ").concat(t.args.length,") for function: ").concat(o),t.loc);let c=Object.values(s.args.named).map((e,r)=>({type:e,expr:r<t.args.length?t.args[r]:{op:"literal",value:null}})),u=t.args.slice(c.length);u.length>0&&!s.args.variadic&&tI(e,"Function ".concat(o," does not accept variadic arguments"),t.loc);let p=u.map((e,t)=>({type:s.args.variadic[t%l],expr:e})),d=c.concat(p).map((t,r)=>{let{type:n,expr:i}=t,a=tE(e,i),o=function(e,t){let r=e7(e),n=[...t];for(let e of(n.sort((e,t)=>tt(t)-tt(e)),n)){if(tt(e)===tt(r))return null;if(tt(e)<tt(r))return e}return n[n.length-1]}(eX(e3(a)),eX(n));return o&&(a={op:"cast",expr:a,type:o}),a}),h=d.slice(0,c.length),m=d.slice(h.length),f=p.map(e=>[]);for(let e=0;e<m.length;e++)f[e%l].push(m[e]);let z=f.map(e=>te(e.map(e5)));for(let e=0;e<m.length;e++)m[e]=tS(m[e],z[e%l]);return{op:"function",name:o,args:h.concat(m)}}(e,t);case"eq":case"is":case"ne":case"lt":case"le":case"gt":case"ge":let r=tE(e,t.left),n=tE(e,t.right),[i,a]=function(e,t){if(JSON.stringify(e)===JSON.stringify(t))return[null,null];let r=e7(e),n=e7(t);if(r===n)return[null,null];let i=tt(r),a=tt(n),o=["number","integer","boolean"];return(o.includes(r)&&o.includes(n)&&(i*=-1,a*=-1),"interval"===r&&"interval"!==n)?[null,"datetime"===n?null:"datetime"]:"interval"===n&&"interval"!==r?["datetime"===r?null:"datetime",null]:i===a?[null,null]:i>a?[null,r]:[n,null]}(e3(r),e3(n));return{op:t.op,left:tS(r,i),right:tS(n,a)};case"like":case"ilike":{let r=tE(e,t.left),n=tE(e,t.right);return{op:t.op,left:tS(r,"string"),right:tS(n,"string")}}case"includes":{var o;let r=tE(e,t.haystack),n=tE(e,t.needle);return"object"===(o=e5(r))||"array"===o||(r=tS(r,"object")),{op:"includes",haystack:r,needle:tS(n,"object")}}case"and":case"or":return{op:t.op,left:tS(tE(e,t.left),"boolean"),right:tS(tE(e,t.right),"boolean")};case"if":let s=t.conds.map(t=>({cond:tS(tE(e,t.cond),"boolean"),then:tE(e,t.then)})),l=tE(e,t.else),c=te(s.map(e=>e.then).concat(l).map(e5));for(let e of s)e.then=tS(e.then,c);return l=tS(l,c),{op:t.op,conds:s,else:l};case"add":case"sub":case"mul":case"div":case"mod":return{op:t.op,left:tE(e,t.left),right:tE(e,t.right)};case"neg":case"not":case"isnull":case"isnotnull":return{op:t.op,expr:tE(e,t.expr)}}}function tI(e,t,r){throw new tA(t,r,e.queryText)}i.z.object({filter:t_.nullish(),from:tk.nullish(),unpivot:i.z.array(tj),sort:tw.nullish(),limit:i.z.number().int().nullish(),cursor:i.z.string().nullish()}).and(tx);var tA=class extends Error{constructor(e,t,r){let n=(r||"").split("\n"),i=t&&r?n.slice(t.start.line-1,t.end.line-t.start.line+1).map((e,r)=>{let i=0===r?t.start.col-1:0,a=r===n.length-1?t.end.col:e.length,o=" ".repeat(i)+"^".repeat(a-i-1),s="".concat(t.start.line+r,":").padEnd(4," ");return"".concat(s).concat(e,"\n    ").concat(o)}).join("\n"):"";super("".concat(e).concat(t&&i?" ... at line ".concat(t.start.line,", column ").concat(t.start.col,":\n")+i:"")),this.prefix=e,this.loc=t,this.query=r}};function tS(e,t){return null===t?e:e5(e)===t?e:function e(t){let r="cast"===t.expr.op?e(t.expr):t.expr;return"field"===r.op?{...r,type:eZ(t.type)}:t}({op:"cast",expr:e,type:t})}},28865:function(e,t,r){r.d(t,{_b:function(){return F}});var n=r(95370),i=["year","month","day","hour","minute","second","millisecond","microsecond"],a=n.z.enum(["true","false","null","and","or","not","is","as","includes","contains","like","ilike","filter","pivot","unpivot","dimensions","measures","select","from","sort","asc","desc","limit","cursor","interval",...i]),o={doubleSlash:"//",doubleDash:"--",slashStar:"/*",starSlash:"*/",lcurly:"{",rcurly:"}",lsquare:"[",rsquare:"]",lparen:"(",rparen:")",comma:",",colon:":",period:".",equalOp:"=",notEqualOp:"!=",doubleAngle:"<>",lessThanOrEqual:"<=",lessThan:"<",greaterThanOrEqual:">=",greaterThan:">",plus:"+",minus:"-",star:"*",slash:"/",percent:"%",pipe:"|",question:"?",word:/[a-zA-Z_][a-zA-Z0-9_]*/,singleQuotedString:/'(?:[^\\']|\\(?:[bfnrtv'\\/]|u[0-9a-fA-F]{4}))*?'/,doubleQuotedString:/"(?:[^\\"]|\\(?:[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*?"/,number:/-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/,whiteSpace:/[ \t\n\r]+/},s=n.z.strictObject({line:n.z.number(),col:n.z.number()}),l=class{get eof(){return this.cursor>=this.text.length}snapshot(){return{cursor:this.cursor,line:this._line,col:this._col}}restore(e){this.cursor=e.cursor,this._line=e.line,this._col=e.col}peekToken(){if(this.eof)return null;for(let[e,t]of Object.entries(this.rules)){t.lastIndex=this.cursor;let r=t.exec(this.text);if(r&&r.index===this.cursor){if("whiteSpace"===e)return this.cursor+=r[0].length,this.updateLineCol(r[0]),this.peekToken();if("slashStar"===e){let e=this.text.indexOf("*/",this.cursor+2);if(-1===e)throw Error("Unterminated comment");return this.cursor=e+2,this.updateLineCol(this.text.slice(r.index,this.cursor)),this.peekToken()}if("doubleSlash"===e||"doubleDash"===e){let e=this.text.indexOf("\n",this.cursor+2);return -1===e?this.cursor=this.text.length:this.cursor=e+1,this.updateLineCol(this.text.slice(r.index,this.cursor)),this.peekToken()}let t=e,n=r[0];return"word"===e&&a.safeParse(n.toLowerCase()).success&&(t=n.toLowerCase()),{type:t,value:n,line:this._line,col:this._col}}}throw Error("Unexpected character at ".concat(this.cursor,": ").concat(this.text.substring(this.cursor,this.cursor+10)))}updateLineCol(e){let t=e.split("\n").length-1;this._line+=t,this._col=0===t?this._col+e.length:e.length-e.lastIndexOf("\n")}nextToken(){let e=this.peekToken();return e&&(this.cursor+=e.value.length,this.current=e,this.updateLineCol(e.value)),e}currentToken(){return this.current}get line(){return this._line}get col(){return this._col}substringCursor(e,t){return this.text.substring(Math.max(this.cursor-e,0),Math.min(this.cursor+t,this.text.length))}*tokens(){let e;for(;e=this.nextToken();)yield e}constructor(e){this.text=e,this.cursor=0,this._line=1,this._col=1,this.rules=Object.fromEntries(Object.entries(o).map(e=>{let[t,r]=e;return[t,RegExp("string"==typeof r?r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):r,"y"+("object"==typeof r?r.flags:""))]})),this.current=null}},c=n.z.strictObject({start:s,end:s}),u=c.nullish(),p=n.z.literal(null),d=n.z.boolean(),h=n.z.number().int(),m=n.z.number(),f=n.z.string(),z=n.z.string().datetime(),b=n.z.array(n.z.lazy(()=>g)),y=n.z.record(n.z.lazy(()=>g)),g=n.z.union([p,d,h,m,f,z,b,n.z.lazy(()=>y)]),_=n.z.object({op:n.z.literal("literal"),value:g,loc:u}),v=n.z.enum(["year","month","day","hour","minute","second","millisecond","microsecond"]),j=n.z.strictObject({op:n.z.literal("interval"),value:n.z.number().int(),unit:v,loc:u}),x=n.z.strictObject({op:n.z.literal("ident"),name:n.z.array(n.z.string()),loc:u}),k=n.z.strictObject({op:n.z.literal("star"),replace:n.z.record(n.z.lazy(()=>U)).optional(),loc:u}),O=n.z.strictObject({op:n.z.literal("function"),name:x,args:n.z.array(n.z.lazy(()=>U)),loc:u}),w=n.z.strictObject({op:n.z.enum(["eq","is","ne","lt","le","gt","ge","ilike","like"]),left:n.z.lazy(()=>U),right:n.z.lazy(()=>U),loc:u}),T=n.z.strictObject({op:n.z.literal("includes"),haystack:n.z.lazy(()=>U),needle:n.z.lazy(()=>U),loc:u}),E=n.z.strictObject({op:n.z.enum(["and","or"]),left:n.z.lazy(()=>U),right:n.z.lazy(()=>U),loc:u}),I=n.z.strictObject({cond:n.z.lazy(()=>U),then:n.z.lazy(()=>U)}),A=n.z.strictObject({op:n.z.literal("if"),conds:n.z.array(I),else:n.z.lazy(()=>U),loc:u}),S=n.z.strictObject({op:n.z.enum(["add","sub","mul","div","mod"]),left:n.z.lazy(()=>U),right:n.z.lazy(()=>U),loc:u}),N=n.z.strictObject({op:n.z.enum(["neg"]),expr:n.z.lazy(()=>U),loc:u}),L=n.z.strictObject({op:n.z.enum(["not","isnull","isnotnull"]),expr:n.z.lazy(()=>U),loc:u}),R=n.z.strictObject({btql:n.z.string(),op:n.z.literal("btql").nullish(),loc:c.nullish()}),U=n.z.union([_,j,x,k,O,w,T,E,A,N,L,S,R]),P=n.z.strictObject({expr:U,alias:n.z.string()}),q=n.z.strictObject({expr:U,alias:n.z.union([n.z.string(),n.z.tuple([n.z.string(),n.z.string()])])}),M=n.z.enum(["asc","desc"]),C=n.z.strictObject({expr:U,dir:M,loc:c.nullish()});n.z.strictObject({dimensions:n.z.array(P).nullish(),pivot:n.z.array(P).nullish(),unpivot:n.z.array(q).nullish(),measures:n.z.array(P).nullish(),select:n.z.array(n.z.union([P,k])).nullish(),filter:U.nullish(),from:n.z.union([x,O]).nullish(),sort:n.z.array(C).nullish(),limit:n.z.number().int().nullish(),cursor:n.z.string().nullish()});var D=class extends Error{constructor(e,t,r,n,i){let a=Array.isArray(t)?t.join(", "):t;super("".concat(e).concat(a?" (expected '"+a+"')":""," at line ").concat(r,", col ").concat(n).concat(i?" ".concat(i):"")),this.prefix=e,this.expected=t,this.line=r,this.col=n,this.suffix=i}},F=class{parseQuery(){let e={};for(;;){let t=this.tokenizer.nextToken();for(;t&&"pipe"===t.type;)t=this.tokenizer.nextToken();if(!t)break;switch(t.type){case"dimensions":case"measures":case"pivot":e[t.type]&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e[t.type]=this.parseList(this.parseAliasExpr.bind(this),"comma");break;case"unpivot":e.select&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e.unpivot=this.parseList(this.parseUnpivotAliasExpr.bind(this),"comma");break;case"select":e.select&&this.fail("".concat(t.type," already defined")),this.mustReadToken(t.type,"colon"),e.select=this.parseList(this.parseAliasOrStar.bind(this),"comma");break;case"filter":e.filter&&this.fail("filter already defined"),this.mustReadToken("filter","colon"),e.filter=this.parseExpr();break;case"from":e.from&&this.fail("from already defined"),this.mustReadToken("from","colon");let r=this.parseIdentOrFunction();e.from="literal"===r.op?Q(r):r;break;case"sort":e.sort&&this.fail("sort already defined"),this.mustReadToken("sort","colon"),e.sort=this.parseList(this.parseSortExpr.bind(this),"comma");break;case"limit":e.limit&&this.fail("limit already defined"),this.mustReadToken("limit","colon");let n=this.mustReadToken("limit","number");B(n.value)||this.fail("limit must be an integer"),e.limit=parseInt(n.value);break;case"cursor":e.cursor&&this.fail("cursor already defined"),this.mustReadToken("cursor","colon");let i=this.mustReadToken("cursor");"singleQuotedString"!==i.type&&"doubleQuotedString"!==i.type&&this.fail("cursor must be a string"),e.cursor=V(i.value,"singleQuotedString"===i.type?"'":'"');break;default:this.failOp("query",["dimensions","pivot","unpivot","measures","select","filter","from","sort","limit","cursor"].filter(t=>!e[t]))}}return e}finished(){return this.tokenizer.eof}parseAliasExpr(){let e=this.parseExpr();e.loc||this.fail("no location information for alias expression");let t="ident"===e.op?e.name[e.name.length-1]:this.query.substring(e.loc.start.col-1,e.loc.end.col-1),r=this.tokenizer.peekToken();return r&&"as"===r.type&&(t=this.parseAliasValue()),{expr:e,alias:t}}parseAliasValue(){this.tokenizer.nextToken();let e=this.tokenizer.nextToken();return e&&this.isIdentPart(e)||this.failOp("alias expression",["identifier"]),e.value}parseUnpivotAliasExpr(){let e;let t=this.parseExpr();t.loc||this.fail("no location information for alias expression"),this.mustReadToken("unpivot alias expression","as");let r=this.tokenizer.peekToken();switch(r||this.failOp("unpivot alias expression",["identifier"]),r.type){case"word":case"doubleQuotedString":e=this.parseAliasValue();break;case"lparen":this.mustReadToken("unpivot alias expression","lparen");let n=this.parseAliasValue();this.mustReadToken("unpivot alias expression","comma");let i=this.parseAliasValue();this.mustReadToken("unpivot alias expression","rparen"),e=[n,i];break;default:this.failOp("unpivot alias expression",["identifier"])}return{expr:t,alias:e}}parseAliasOrStar(){var e;return(null==(e=this.tokenizer.peekToken())?void 0:e.type)==="star"?(this.mustReadToken("select","star"),{op:"star"}):this.parseAliasExpr()}parseSortExpr(){var e,t,r;let n=this.parseExpr(),i=null==(e=n.loc)?void 0:e.start,a=null==(t=n.loc)?void 0:t.end,o="asc";switch(null==(r=this.tokenizer.peekToken())?void 0:r.type){case"asc":case"desc":let s=this.tokenizer.nextToken();o=null==s?void 0:s.type,a=J(s).end}return{expr:n,dir:o,loc:i&&a?{start:i,end:a}:void 0}}parseList(e,t){let r=[];for(;;){let n=this.tokenizer.snapshot();try{r.push(e())}catch(e){console.error(e),this.tokenizer.restore(n);break}let i=this.tokenizer.peekToken();if(!i||i.type!==t)break;this.tokenizer.nextToken()}return r}parseExpr(){if(++this.exprGuard>this.maxExprDepth)throw Error("Maximum expression depth exceeded");let e=this.parseTernaryExpr();return--this.exprGuard,e}parseTernaryExpr(){var e,t;let r=this.parseOrExpr(),n=null==(e=r.loc)?void 0:e.start,i=this.tokenizer.peekToken();if((null==i?void 0:i.type)==="question"){this.tokenizer.nextToken();let e=this.parseOrExpr();this.mustReadToken("ternary expression","colon");let i=this.parseTernaryExpr(),a=null==(t=i.loc)?void 0:t.end,o=[{cond:r,then:e}],s=i;return"if"===i.op&&(o.push(...i.conds),s=i.else),{op:"if",conds:o,else:s,loc:n&&a?{start:n,end:a}:void 0}}return r}parseLeftAssocExpr(e,t,r){var n,i;let a=e(),o=null==(n=a.loc)?void 0:n.start,s=Array.isArray(t)?t:[t];for(;;){let t=this.tokenizer.peekToken();if(!t||!s.includes(t.type))break;this.tokenizer.nextToken();let n=e(),l=null==(i=n.loc)?void 0:i.end;a=r(a,n,t.type,o&&l?{start:o,end:l}:void 0)}return a}parseRightAssocExpr(e,t,r){var n,i;let a=e(),o=null==(n=a.loc)?void 0:n.start,s=Array.isArray(t)?t:[t],l=this.tokenizer.peekToken();if(l&&s.includes(l.type)){this.tokenizer.nextToken();let n=this.parseRightAssocExpr(e,t,r),s=null==(i=n.loc)?void 0:i.end;return r(a,n,l.type,o&&s?{start:o,end:s}:void 0)}return a}parseOrExpr(){return this.parseLeftAssocExpr(this.parseAndExpr.bind(this),"or",(e,t,r,n)=>({op:"or",left:e,right:t,loc:n}))}parseAndExpr(){return this.parseLeftAssocExpr(this.parseNotExpr.bind(this),"and",(e,t,r,n)=>({op:"and",left:e,right:t,loc:n}))}parseNotExpr(){var e,t;if((null==(e=this.tokenizer.peekToken())?void 0:e.type)==="not"){let e=this.tokenizer.nextToken(),r=this.parseNotExpr(),n=J(e).start,i=null==(t=r.loc)?void 0:t.end;return{op:"not",expr:r,loc:i?{start:n,end:i}:void 0}}return this.parseEqualityExpr()}parseEqualityExpr(){return this.parseRightAssocExpr(this.parseInequalityExpr.bind(this),["equalOp","notEqualOp","doubleAngle","includes","contains","like","ilike"],(e,t,r,n)=>"equalOp"===r?{op:"eq",left:e,right:t,loc:n}:"notEqualOp"===r||"doubleAngle"===r?{op:"ne",left:e,right:t,loc:n}:"like"===r||"ilike"===r?{op:r,left:e,right:t,loc:n}:{op:"includes",haystack:e,needle:t,loc:n})}parseInequalityExpr(){return this.parseRightAssocExpr(this.parseIsExpr.bind(this),["lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual"],(e,t,r,n)=>({op:"lessThan"===r?"lt":"lessThanOrEqual"===r?"le":"greaterThan"===r?"gt":"ge",left:e,right:t,loc:n}))}parseIsExpr(){var e,t,r,n;let i=this.parseAddExpr(),a=null==(e=i.loc)?void 0:e.start,o=this.tokenizer.peekToken();if((null==o?void 0:o.type)==="is"){if(this.tokenizer.nextToken(),(null==(t=this.tokenizer.peekToken())?void 0:t.type)==="not"){this.tokenizer.nextToken();let e=this.mustReadToken("is not","null");return{op:"isnotnull",expr:i,loc:a?{start:a,end:J(e).end}:void 0}}if((null==(r=this.tokenizer.peekToken())?void 0:r.type)==="null"){let e=this.mustReadToken("is","null");return{op:"isnull",expr:i,loc:a?{start:a,end:J(e).end}:void 0}}{let e=this.parsePrimaryExpr(!0),t=null==(n=e.loc)?void 0:n.end;return{op:"is",left:i,right:e,loc:a&&t?{start:a,end:t}:void 0}}}return i}parseAddExpr(){return this.parseLeftAssocExpr(this.parseMulExpr.bind(this),["plus","minus"],(e,t,r,n)=>({op:"plus"===r?"add":"sub",left:e,right:t,loc:n}))}parseMulExpr(){return this.parseLeftAssocExpr(this.parseUnaryExpr.bind(this),["star","slash","percent"],(e,t,r,n)=>({op:"star"===r?"mul":"slash"===r?"div":"mod",left:e,right:t,loc:n}))}parseUnaryExpr(){var e,t;if((null==(e=this.tokenizer.peekToken())?void 0:e.type)==="minus"){let e=J(this.tokenizer.nextToken()).start,t=this.parseUnaryExpr();return{op:"neg",expr:t,loc:t.loc?{start:e,end:t.loc.end}:void 0}}return(null==(t=this.tokenizer.peekToken())?void 0:t.type)==="plus"?(this.tokenizer.nextToken(),this.parseUnaryExpr()):this.parsePrimaryExpr(!0)}parsePrimaryExpr(e){let t=this.tokenizer.nextToken();switch(t||this.failOp("primary expression"),t.type){case"true":return{op:"literal",value:!0,loc:J(t)};case"false":return{op:"literal",value:!1,loc:J(t)};case"null":return{op:"literal",value:null,loc:J(t)};case"star":return{op:"star",loc:J(t)};case"number":return{op:"literal",value:B(t.value)?parseInt(t.value):parseFloat(t.value),loc:J(t)};case"singleQuotedString":return{op:"literal",value:V(t.value,"'"),loc:J(t)};case"lsquare":let r=this.tokenizer.peekToken();if((null==r?void 0:r.type)==="rsquare")return this.tokenizer.nextToken(),{op:"literal",value:[],loc:{start:J(t).start,end:J(r).end}};return{op:"literal",value:this.parseList(this.parseLiteral.bind(this),"comma"),loc:{start:J(t).start,end:J(this.mustReadToken("list","rsquare")).end}};case"lcurly":{let e=this.tokenizer.peekToken();if((null==e?void 0:e.type)==="rcurly")return this.tokenizer.nextToken(),{op:"literal",value:{},loc:{start:J(t).start,end:J(e).end}};return{op:"literal",value:Object.fromEntries(this.parseList(this.parseObjectPair.bind(this),"comma")),loc:{start:J(t).start,end:J(this.mustReadToken("object","rcurly")).end}}}case"interval":let n=this.mustReadToken("interval","number");B(n.value)||this.fail("interval value must be an integer");let i=this.mustReadToken("interval"),a=v.safeParse(i.value.toLowerCase());return!0!==a.success&&this.fail("invalid interval unit"),{op:"interval",value:parseInt(n.value),unit:a.data,loc:{start:J(t).start,end:J(i).end}};case"lparen":e||this.fail("Cannot parse nested expressions in this context");let o=this.parseExpr();return this.mustReadToken("primary expression","rparen"),o}if(this.isIdentPart(t))return this.parseIdentOrFunction(t);this.failOp("primary expression",["number","singleQuotedString"])}parseLiteral(){let e=this.parsePrimaryExpr(!1);return"literal"!==e.op&&this.fail("literal"),e.value}parseObjectPair(){let e;let t=this.parsePrimaryExpr(!1);return"ident"===t.op?(1!==t.name.length&&this.fail("object key must be a single identifier"),e=t.name[0]):"literal"===t.op?("string"!=typeof t.value&&this.fail("object key must be a string"),e=t.value):this.fail("object key must be a string or identifier"),this.mustReadToken("object pair","colon"),[e,this.parseLiteral()]}isIdentPart(e){return["word","doubleQuotedString",...i].includes(e.type)}parseIdent(e){var t,r;e||(e=this.mustReadToken("identifier")),this.isIdentPart(e)||this.failOp("ident",["word"]);let n=e=>"doubleQuotedString"===e.type?V(e.value,'"'):e.value,i=[n(e)],a=J(e).start,o=J(e).end;if((null==(t=this.tokenizer.peekToken())?void 0:t.type)==="period")for(;(null==(r=this.tokenizer.peekToken())?void 0:r.type)==="period";){this.tokenizer.nextToken();let e=this.tokenizer.nextToken();e&&this.isIdentPart(e)||this.failOp("primary expression",["identifier"]),i.push(n(e)),o=J(e).end}else if("doubleQuotedString"===e.type)return{op:"literal",value:i[0],loc:J(e)};return{op:"ident",name:i,loc:{start:a,end:o}}}parseIdentOrFunction(e){var t,r;let n=this.parseIdent(e);if((null==(t=this.tokenizer.peekToken())?void 0:t.type)!=="lparen")return n;{this.tokenizer.nextToken();let e=[];(null==(r=this.tokenizer.peekToken())?void 0:r.type)!=="rparen"&&(e=this.parseList(this.parseExpr.bind(this),"comma"));let t=this.mustReadToken("function call","rparen");return{op:"function",name:Q(n),args:e,loc:{start:n.loc.start,end:J(t).end}}}}mustReadToken(e,t){let r=this.tokenizer.nextToken();return r?t&&r.type!==t&&this.failOp(e,t):this.failOp(e),r}fail(e,t){var r;if(this.tokenizer.eof)throw new D(e,t,this.tokenizer.line,this.tokenizer.col,"unexpected end of input");let n=this.tokenizer.currentToken(),i=(null==(r=this.tokenizer.currentToken())?void 0:r.value)||"",a=this.tokenizer.substringCursor(10,10);throw new D(e,t,(null==n?void 0:n.line)||this.tokenizer.line,(null==n?void 0:n.col)||this.tokenizer.col,"at".concat(i?" ".concat(i):"").concat(a?" near '".concat(a,"'"):""))}failOp(e,t){this.fail("Failed to parse "+e,t)}constructor(e,t={}){this.query=e,this.exprGuard=0,this.tokenizer=new l(e),this.maxExprDepth=t.maxExprDepth||100}};function B(e){if(!(e=e.trim()))return!1;let t=Math.floor(Number(e=e.replace(/^0+/,"")||"0"));return t!==1/0&&String(t)===e&&t>=0}function V(e,t){return e[0]!==t||e[e.length-1]!==t?e:e.slice(1,-1)}function J(e){return{start:{line:e.line,col:e.col},end:{line:e.line,col:e.col+e.value.length}}}function Q(e){if("ident"===e.op)return e;if("string"==typeof e.value)return{op:"ident",name:[e.value],loc:e.loc};throw Error("Expected string literal")}},38869:function(e,t,r){r.d(t,{Qw:function(){return nl},m6:function(){return nc}});var n,i=r(86274),a=r(95370),o=r(34846);function s(){let e=(0,i._)(["",""]);return s=function(){return e},e}function l(){let e=(0,i._)(["INTERVAL '"," ","'"]);return l=function(){return e},e}function c(){let e=(0,i._)(["("," "," ",")"]);return c=function(){return e},e}function u(){let e=(0,i._)(["(-(","))"]);return u=function(){return e},e}function p(){let e=(0,i._)(["(NOT (","))"]);return p=function(){return e},e}function d(){let e=(0,i._)(["("," IS NULL)"]);return d=function(){return e},e}function h(){let e=(0,i._)(["("," IS NOT NULL)"]);return h=function(){return e},e}function m(){let e=(0,i._)(["WHEN "," THEN ",""]);return m=function(){return e},e}function f(){let e=(0,i._)(["CASE "," ELSE "," END"]);return f=function(){return e},e}function z(){let e=(0,i._)(["",""]);return z=function(){return e},e}function b(){let e=(0,i._)(["true"]);return b=function(){return e},e}function y(){let e=(0,i._)(["false"]);return y=function(){return e},e}function g(){let e=(0,i._)(["",""]);return g=function(){return e},e}function _(){let e=(0,i._)(["","[","]"]);return _=function(){return e},e}function v(){let e=(0,i._)(["",""]);return v=function(){return e},e}function j(){let e=(0,i._)(["NULLIF(JSONExtractRaw(",", ","), '')"]);return j=function(){return e},e}function x(){let e=(0,i._)(["JSONExtract(",", ",", ",")"]);return x=function(){return e},e}function k(){let e=(0,i._)(["hasAny(",", ",")"]);return k=function(){return e},e}function O(){let e=(0,i._)(["JSONExtractArrayRaw(COALESCE(",", 'null'))"]);return O=function(){return e},e}function w(){let e=(0,i._)(["hasAny(",", ",")"]);return w=function(){return e},e}function T(){let e=(0,i._)([""," ILIKE CONCAT('%', ",", '%')"]);return T=function(){return e},e}function E(){let e=(0,i._)(["[","]"]);return E=function(){return e},e}function I(){let e=(0,i._)(["",""]);return I=function(){return e},e}function A(){let e=(0,i._)(["[","]"]);return A=function(){return e},e}function S(){let e=(0,i._)(["","(",")"]);return S=function(){return e},e}function N(){let e=(0,i._)(["quantileExact("," / 100)(",")"]);return N=function(){return e},e}function L(){let e=(0,i._)(["",""]);return L=function(){return e},e}function R(){let e=(0,i._)(["addMinutes(",", ",")"]);return R=function(){return e},e}function U(){let e=(0,i._)(["CAST(date_trunc(",", ","), 'Nullable(DateTime64)')"]);return U=function(){return e},e}function P(){let e=(0,i._)(["current_timestamp()"]);return P=function(){return e},e}function q(){let e=(0,i._)(["current_date()"]);return q=function(){return e},e}function M(){let e=(0,i._)(["mapConcat(",", map(","))"]);return M=function(){return e},e}function C(){let e=(0,i._)(["coalesce(",")"]);return C=function(){return e},e}function D(){let e=(0,i._)(["arraySort(arrayFilter(x -> x IS NOT NULL, [","]))[","]"]);return D=function(){return e},e}function F(){let e=(0,i._)(["nullIf(",", ",")"]);return F=function(){return e},e}function B(){let e=(0,i._)(["parseDateTimeBestEffort(",")"]);return B=function(){return e},e}function V(){let e=(0,i._)(["CAST(",", ",")"]);return V=function(){return e},e}function J(){let e=(0,i._)(["",""]);return J=function(){return e},e}function Q(){let e=(0,i._)(["","::",""]);return Q=function(){return e},e}function G(){let e=(0,i._)(["to_json(",")"]);return G=function(){return e},e}function $(){let e=(0,i._)(["json_extract_string(",", '$')::",""]);return $=function(){return e},e}function Y(){let e=(0,i._)(["","(",", ",")"]);return Y=function(){return e},e}function W(){let e=(0,i._)(["","::",""]);return W=function(){return e},e}function H(){let e=(0,i._)(["json_contains(",", ",")"]);return H=function(){return e},e}function Z(){let e=(0,i._)(["","(",")"]);return Z=function(){return e},e}function X(){let e=(0,i._)(["percentile_cont(",") WITHIN GROUP (ORDER BY ",")"]);return X=function(){return e},e}function K(){let e=(0,i._)(["",""]);return K=function(){return e},e}function ee(){let e=(0,i._)(["-"]);return ee=function(){return e},e}function et(){let e=(0,i._)(["+"]);return et=function(){return e},e}function er(){let e=(0,i._)(["((",") "," INTERVAL "," MINUTE)"]);return er=function(){return e},e}function en(){let e=(0,i._)(["date_trunc(",", ",")::text"]);return en=function(){return e},e}function ei(){let e=(0,i._)(["get_current_timestamp()"]);return ei=function(){return e},e}function ea(){let e=(0,i._)(["current_date()"]);return ea=function(){return e},e}function eo(){let e=(0,i._)(["json_merge_patch(",", json_object(","))"]);return eo=function(){return e},e}function es(){let e=(0,i._)(["","(",")"]);return es=function(){return e},e}function el(){let e=(0,i._)(["nullif(",", ",")"]);return el=function(){return e},e}function ec(){let e=(0,i._)(["varchar"]);return ec=function(){return e},e}function eu(){let e=(0,i._)(["timestamp"]);return eu=function(){return e},e}function ep(){let e=(0,i._)(["date"]);return ep=function(){return e},e}function ed(){let e=(0,i._)(["numeric"]);return ed=function(){return e},e}function eh(){let e=(0,i._)(["bigint"]);return eh=function(){return e},e}function em(){let e=(0,i._)(["boolean"]);return em=function(){return e},e}function ef(){let e=(0,i._)(["json"]);return ef=function(){return e},e}function ez(){let e=(0,i._)(["varchar"]);return ez=function(){return e},e}function eb(){let e=(0,i._)(["interval"]);return eb=function(){return e},e}function ey(){let e=(0,i._)(["json_extract_path_text(",", '$')::",""]);return ey=function(){return e},e}function eg(){let e=(0,i._)(["to_json((",")::",")"]);return eg=function(){return e},e}function e_(){let e=(0,i._)(["","::",""]);return e_=function(){return e},e}function ev(){let e=(0,i._)(["",""]);return ev=function(){return e},e}function ej(){let e=(0,i._)(["","::",""]);return ej=function(){return e},e}function ex(){let e=(0,i._)(["to_jsonb(",")"]);return ex=function(){return e},e}function ek(){let e=(0,i._)(["",""]);return ek=function(){return e},e}function eO(){let e=(0,i._)(["","(",", ",")"]);return eO=function(){return e},e}function ew(){let e=(0,i._)(["","::",""]);return ew=function(){return e},e}function eT(){let e=(0,i._)([""," @> ",""]);return eT=function(){return e},e}function eE(){let e=(0,i._)([""," = ",""]);return eE=function(){return e},e}function eI(){let e=(0,i._)([""," @> ",""]);return eI=function(){return e},e}function eA(){let e=(0,i._)(["","(",")"]);return eA=function(){return e},e}function eS(){let e=(0,i._)(["percentile_cont(",") WITHIN GROUP (ORDER BY ",")"]);return eS=function(){return e},e}function eN(){let e=(0,i._)(["(","::timestamptz AT TIME ZONE ",")"]);return eN=function(){return e},e}function eL(){let e=(0,i._)(["date_trunc(",", ",")::timestamptz"]);return eL=function(){return e},e}function eR(){let e=(0,i._)(["current_date"]);return eR=function(){return e},e}function eU(){let e=(0,i._)(["current_timestamp"]);return eU=function(){return e},e}function eP(){let e=(0,i._)([""," || jsonb_build_object(",")"]);return eP=function(){return e},e}function eq(){let e=(0,i._)(["","(",")"]);return eq=function(){return e},e}function eM(){let e=(0,i._)(["nullif(",", ",")"]);return eM=function(){return e},e}function eC(){let e=(0,i._)(["(CASE WHEN "," THEN 1 ELSE 0 END)"]);return eC=function(){return e},e}function eD(){let e=(0,i._)(["("," #>> '{}')::",""]);return eD=function(){return e},e}function eF(){let e=(0,i._)(["to_jsonb((",")::",")"]);return eF=function(){return e},e}function eB(){let e=(0,i._)(["","::",""]);return eB=function(){return e},e}function eV(){let e=(0,i._)([""," ",""]);return eV=function(){return e},e}a.z.enum(["true","false","null","and","or","not","is","as","includes","contains","like","ilike","filter","pivot","unpivot","dimensions","measures","select","from","sort","asc","desc","limit","cursor","interval","year","month","day","hour","minute","second","millisecond","microsecond"]);var eJ=a.z.strictObject({line:a.z.number(),col:a.z.number()}),eQ=a.z.strictObject({start:eJ,end:eJ}),eG=eQ.nullish(),e$=a.z.literal(null),eY=a.z.boolean(),eW=a.z.number().int(),eH=a.z.number(),eZ=a.z.string(),eX=a.z.string().datetime(),eK=a.z.array(a.z.lazy(()=>e1)),e0=a.z.record(a.z.lazy(()=>e1)),e1=a.z.union([e$,eY,eW,eH,eZ,eX,eK,a.z.lazy(()=>e0)]),e2=a.z.object({op:a.z.literal("literal"),value:e1,loc:eG}),e6=a.z.enum(["year","month","day","hour","minute","second","millisecond","microsecond"]),e4=a.z.strictObject({op:a.z.literal("interval"),value:a.z.number().int(),unit:e6,loc:eG}),e3=a.z.strictObject({op:a.z.literal("ident"),name:a.z.array(a.z.string()),loc:eG}),e8=a.z.strictObject({op:a.z.literal("star"),replace:a.z.record(a.z.lazy(()=>tp)).optional(),loc:eG}),e9=a.z.strictObject({op:a.z.literal("function"),name:e3,args:a.z.array(a.z.lazy(()=>tp)),loc:eG}),e5=["eq","is","ne","lt","le","gt","ge","ilike","like"],e7=a.z.strictObject({op:a.z.enum(e5),left:a.z.lazy(()=>tp),right:a.z.lazy(()=>tp),loc:eG}),te=a.z.strictObject({op:a.z.literal("includes"),haystack:a.z.lazy(()=>tp),needle:a.z.lazy(()=>tp),loc:eG}),tt=["and","or"],tr=a.z.strictObject({op:a.z.enum(tt),left:a.z.lazy(()=>tp),right:a.z.lazy(()=>tp),loc:eG}),tn=["add","sub","mul","div","mod"],ti=a.z.strictObject({cond:a.z.lazy(()=>tp),then:a.z.lazy(()=>tp)}),ta=a.z.strictObject({op:a.z.literal("if"),conds:a.z.array(ti),else:a.z.lazy(()=>tp),loc:eG}),to=a.z.strictObject({op:a.z.enum(tn),left:a.z.lazy(()=>tp),right:a.z.lazy(()=>tp),loc:eG}),ts=["neg"],tl=a.z.strictObject({op:a.z.enum(ts),expr:a.z.lazy(()=>tp),loc:eG}),tc=a.z.strictObject({op:a.z.enum(["not","isnull","isnotnull"]),expr:a.z.lazy(()=>tp),loc:eG}),tu=a.z.strictObject({btql:a.z.string(),op:a.z.literal("btql").nullish(),loc:eQ.nullish()}),tp=a.z.union([e2,e4,e3,e8,e9,e7,te,tr,ta,tl,tc,to,tu]),td=a.z.strictObject({expr:tp,alias:a.z.string()}),th=a.z.strictObject({expr:tp,alias:a.z.union([a.z.string(),a.z.tuple([a.z.string(),a.z.string()])])}),tm=a.z.enum(["asc","desc"]),tf=a.z.strictObject({expr:tp,dir:tm,loc:eQ.nullish()});a.z.strictObject({dimensions:a.z.array(td).nullish(),pivot:a.z.array(td).nullish(),unpivot:a.z.array(th).nullish(),measures:a.z.array(td).nullish(),select:a.z.array(a.z.union([td,e8])).nullish(),filter:tp.nullish(),from:a.z.union([e3,e9]).nullish(),sort:a.z.array(tf).nullish(),limit:a.z.number().int().nullish(),cursor:a.z.string().nullish()});var tz=a.z.string(),tb=a.z.string(),ty=a.z.string(),tg=a.z.string(),t_=a.z.string(),tv=a.z.string(),tj=a.z.any(),tx=a.z.boolean(),tk=a.z.array(tj),tO=a.z.number(),tw=a.z.number(),tT=a.z.number(),tE=a.z.number(),tI=a.z.number(),tA=a.z.number().nonnegative(),tS=a.z.number().nonnegative().default(0),tN=a.z.string(),tL=a.z.array(a.z.lazy(()=>tZ)),tR=a.z.union([a.z.lazy(()=>tZ),tL]).default(!0),tU=a.z.boolean(),tP=a.z.string(),tq=a.z.array(tP).default([]),tM=a.z.record(a.z.any()).default({}),tC=a.z.record(a.z.any()).default({}),tD=a.z.record(a.z.any()).default({});a.z.union([a.z.lazy(()=>tZ),tq]);var tF=a.z.record(a.z.any()),tB=a.z.array(tj),tV=a.z.enum(["array","boolean","integer","null","number","object","string"]),tJ=a.z.array(tV),tQ=a.z.union([tV,tJ]),tG=a.z.string(),t$=a.z.string(),tY=a.z.string(),tW=a.z.object({$id:tz.optional(),$schema:tb.optional(),$ref:ty.optional(),$comment:tg.optional(),title:t_.optional(),description:tv.optional(),default:tj.optional(),readOnly:tx.optional(),examples:tk.optional(),multipleOf:tO.optional(),maximum:tw.optional(),exclusiveMaximum:tT.optional(),minimum:tE.optional(),exclusiveMinimum:tI.optional(),maxLength:tA.optional(),minLength:tS.optional(),pattern:tN.optional(),additionalItems:a.z.lazy(()=>tZ.optional()),items:tR.optional(),maxItems:tA.optional(),minItems:tS.optional(),uniqueItems:tU.optional(),contains:a.z.lazy(()=>tZ.optional()),maxProperties:tA.optional(),minProperties:tS.optional(),required:tq.optional(),additionalProperties:a.z.lazy(()=>tZ.optional()),definitions:tM.optional(),properties:tC.optional(),patternProperties:tD.optional(),dependencies:tF.optional(),propertyNames:a.z.lazy(()=>tZ.optional()),const:tj.optional(),enum:tB.optional(),type:tQ.optional(),format:tG.optional(),contentMediaType:t$.optional(),contentEncoding:tY.optional(),if:a.z.lazy(()=>tZ.optional()),then:a.z.lazy(()=>tZ.optional()),else:a.z.lazy(()=>tZ.optional()),allOf:tL.optional(),anyOf:tL.optional(),oneOf:tL.optional(),not:a.z.lazy(()=>tZ.optional())}).catchall(a.z.any()),tH=a.z.boolean(),tZ=a.z.union([tW,tH]),tX=a.z.union([a.z.strictObject({type:a.z.enum(["bigint","bit","blob","boolean","date","double","hugeint","integer","interval","real","smallint","time","timestamp with time zone","timestamp","tinyint","ubigint","uhugeint","uinteger","usmallint","utinyint","uuid","varchar","json"])}),a.z.strictObject({type:a.z.literal("decimal"),prec:a.z.number().int().optional(),scale:a.z.number().int().optional()})]),tK=a.z.object({type:a.z.literal("array"),items:a.z.lazy(()=>t2)}),t0=a.z.object({type:a.z.literal("struct"),fields:a.z.lazy(()=>a.z.record(t2))}),t1=a.z.object({type:a.z.literal("map"),key:a.z.lazy(()=>tX),value:a.z.lazy(()=>t2)}),t2=a.z.union([tX,tK,t1,t0]),t6=a.z.strictObject({path:a.z.array(a.z.string()),type:t2}),t4=a.z.strictObject({columns:a.z.record(t6)}),t3=a.z.union([a.z.strictObject({type:a.z.enum(["bigint","bigserial","bit","bit varying","boolean","box","bytea","character","character varying","cidr","circle","date","double precision","inet","integer","interval","json","jsonb","line","lseg","macaddr","macaddr8","money","path","pg_lsn","pg_snapshot","point","polygon","real","smallint","smallserial","serial","text","time","time with time zone","timestamp","timestamptz","timestamp with time zone","tsquery","tsvector","txid_snapshot","uuid","xml"])}),a.z.strictObject({type:a.z.literal("numeric"),prec:a.z.number().int().optional(),scale:a.z.number().int().optional()})]),t8=a.z.strictObject({path:a.z.array(a.z.string()),type:t3}),t9=a.z.strictObject({columns:a.z.record(t8)}),t5=a.z.union([a.z.strictObject({type:a.z.enum(["UInt8","UInt16","UInt32","UInt64","UInt128","UInt256","Int8","Int16","Int32","Int64","Int128","Int256","Float32","Float64","Boolean","String","FixedString","Date","DateTime","DateTime64","JSON","UUID","IPv4","IPv6","Point","Ring","Polygon","MultiPolygon","Nothing","Interval"])}),a.z.strictObject({type:a.z.literal("Decimal"),precision:a.z.number(),scale:a.z.number()})]),t7=a.z.object({type:a.z.literal("Array"),items:a.z.lazy(()=>ri)}),re=a.z.object({type:a.z.literal("Nullable"),inner:a.z.lazy(()=>ri)}),rt=a.z.object({type:a.z.literal("Enum"),values:a.z.record(a.z.number())}),rr=a.z.object({type:a.z.literal("LowCardinality"),inner:a.z.lazy(()=>ri)}),rn=a.z.object({type:a.z.literal("Map"),key:a.z.lazy(()=>ri),value:a.z.lazy(()=>ri)}),ri=a.z.union([t5,t7,re,rt,rr,rn]),ra=a.z.strictObject({path:a.z.array(a.z.string()),type:ri}),ro=a.z.strictObject({columns:a.z.record(ra)});function rs(e){return"object"==typeof e?e:!0===e?{}:{not:{}}}(e=>{function t(e){return{type:e}}e.scalar=t,e.nullable=function(e){return{type:"Nullable",inner:t(e)}},e.array=function(e){return{type:"Array",items:t(e)}},e.record=function(e){return{type:"Map",key:t("String"),value:e}}})(n||(n={}));var rl=new o({coerceTypes:!1});rl.addFormat("uuid",{type:"string",validate:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}),rl.addFormat("date-time",{type:"string",validate:e=>!isNaN(Date.parse(e))});var rc=["array","boolean","integer","null","number","object","string","date","datetime","interval"],ru=a.z.enum(rc);function rp(e){switch(e){case"array":case"boolean":case"integer":case"object":case"null":case"number":case"string":return{type:e};case"date":return{type:"string",format:"date"};case"datetime":return{type:"string",format:"date-time"};case"interval":return{type:"string",format:"duration"}}}function rd(e){return"object"!=typeof e?e?[...rc]:["null"]:e.type&&!Array.isArray(e.type)?["string"===e.type&&"date-time"===e.format?"datetime":"string"===e.type&&"date"===e.format?"date":"string"===e.type&&"duration"===e.format?"interval":e.type]:Array.isArray(e)||Array.isArray(e.type)||e.anyOf||e.oneOf?[...new Set((Array.isArray(e)?e:e.type||e.anyOf||e.oneOf).flatMap(e=>"string"==typeof e?[e]:rd(e)))]:e.allOf?e.allOf.map(e=>rd(e)).reduce((e,t)=>e.filter(e=>t.includes(e)),[...rc]):[...rc]}function rh(e){let t=rd(e);return!t.includes("array")&&!t.includes("object")}function rm(e){switch(e.op){case"literal":case"cast":return rp(e.type);case"interval":return rp("interval");case"field":return e.type;case"function":let t=rO[e.name],r=Object.fromEntries(Object.keys(t.args.named).map((t,r)=>[t,rm(e.args[r])])),n=e.args.slice(Object.keys(t.args.named).length).map(rm);return rO[e.name].type(r,n);case"eq":case"is":case"ne":case"lt":case"le":case"gt":case"ge":case"like":case"ilike":case"includes":case"and":case"or":case"not":case"isnull":case"isnotnull":return{type:"boolean"};case"add":case"sub":case"mul":case"div":case"mod":let i=rz(e.left),a=rz(e.right);if("integer"===i&&"integer"===a)return{type:"integer"};if(rf("datetime",i,a))return rp("datetime");if(rf("date",i,a))return rp("date");return{type:"number"};case"if":return rm(e.else);case"neg":return rm(e.expr)}}function rf(e,t,r){return t===e&&"interval"===r||"interval"===t&&r===e}function rz(e){return rb(rm(e))}function rb(e){return rd(e).sort((e,t)=>rv(e)-rv(t))[0]}function ry(e){return"object"===e||"array"===e}function rg(e,t){if(JSON.stringify(e)===JSON.stringify(t))return[null,null];let r=rb(e),n=rb(t);if(r===n)return[null,null];let i=rv(r),a=rv(n),o=["number","integer","boolean"];return(o.includes(r)&&o.includes(n)&&(i*=-1,a*=-1),"interval"===r&&"interval"!==n)?[null,"datetime"===n?null:"datetime"]:"interval"===n&&"interval"!==r?["datetime"===r?null:"datetime",null]:i===a?[null,null]:i>a?[null,r]:[n,null]}function r_(e){let t=Math.min(...e.map(e=>rv(e)));return e.find(e=>rv(e)===t)}function rv(e){switch(e){case"null":return 9;case"interval":return 8;case"datetime":return 7;case"date":return 6;case"boolean":return 5;case"integer":return 4;case"number":return 3;case"string":return 2;case"array":return 1;case"object":return 0}}a.z.union([t4,t9,ro]),a.z.union([a.z.strictObject({type:a.z.literal("duckdb"),tables:a.z.record(t4)}),a.z.strictObject({type:a.z.literal("postgres"),tables:a.z.record(t9)}),a.z.strictObject({type:a.z.literal("clickhouse"),tables:a.z.record(ro)})]),a.z.strictObject({type:a.z.literal("array"),items:a.z.strictObject({type:a.z.literal("object"),properties:a.z.record(tW)})}),a.z.strictObject({isAgg:a.z.boolean(),args:a.z.strictObject({named:a.z.record(tZ),variadic:a.z.array(tZ).optional()}),type:a.z.function(a.z.tuple([a.z.record(tZ),a.z.array(tZ)]),tW)});var rj=a.z.enum(["second","minute","hour","day","week","month","year","current_timestamp","current_date","insert","coalesce","nullif","least","greatest","count","sum","avg","min","max","percentile"]),rx={isAgg:!1,args:{named:{expr:[{type:"string",format:"date-time"}]}},type:()=>({type:"string",format:"date-time"})},rk={isAgg:!1,args:{named:{},variadic:[{}]},type:(e,t)=>rp(r_(t.map(rs).map(rb)))},rO={second:rx,minute:rx,hour:rx,day:rx,week:rx,month:rx,year:rx,current_timestamp:{isAgg:!1,args:{named:{}},type:()=>({type:"string",format:"date-time"})},current_date:{isAgg:!1,args:{named:{}},type:()=>({type:"string",format:"date"})},insert:{isAgg:!1,args:{named:{expr:[{}]},variadic:[{type:"string"},{}]},type:e=>{let{expr:t}=e;return rs(t)}},coalesce:rk,least:rk,greatest:rk,nullif:{isAgg:!1,args:{named:{left:[{}],right:[{}]}},type:e=>{let{left:t,right:r}=e;return rp(r_([t,r].map(rs).map(rb)))}},count:{isAgg:!0,args:{named:{expr:{default:1}}},type:()=>({type:"integer"})},sum:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}]}},type:e=>{let{expr:t}=e;return"integer"===rb(rs(t))?{type:["integer","null"]}:{type:["number","null"]}}},avg:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}]}},type:e=>{let{expr:t}=e;return{type:["number","null"]}}},min:{isAgg:!0,args:{named:{expr:[{}]}},type:e=>{let{expr:t}=e;return rs(t)}},max:{isAgg:!0,args:{named:{expr:[{}]}},type:e=>{let{expr:t}=e;return rs(t)}},percentile:{isAgg:!0,args:{named:{expr:[{type:"number"},{type:"integer"}],p:[{type:"number"}]}},type:e=>{let{expr:t}=e;return{type:["number","null"]}}}},rw=a.z.strictObject({op:a.z.literal("literal"),value:a.z.unknown(),type:ru}),rT=a.z.strictObject({op:a.z.literal("interval")}).merge(e4.omit({loc:!0})),rE=a.z.strictObject({op:a.z.literal("field"),name:a.z.array(a.z.string()),type:tW,source:a.z.strictObject({unpivot:a.z.number().int(),type:a.z.enum(["key","value","element"])}).nullish()}),rI=a.z.strictObject({op:a.z.literal("function"),name:rj,args:a.z.array(a.z.lazy(()=>rC)),type:tW}),rA=a.z.strictObject({op:a.z.enum(e5),left:a.z.lazy(()=>rC),right:a.z.lazy(()=>rC)}),rS=a.z.strictObject({op:a.z.literal("includes"),haystack:a.z.lazy(()=>rC),needle:a.z.lazy(()=>rC)}),rN=a.z.strictObject({op:a.z.enum(tt),left:a.z.lazy(()=>rC),right:a.z.lazy(()=>rC)}),rL=a.z.strictObject({cond:a.z.lazy(()=>rC),then:a.z.lazy(()=>rC)}),rR=a.z.strictObject({op:a.z.literal("if"),conds:a.z.array(rL),else:a.z.lazy(()=>rC)}),rU=a.z.strictObject({op:a.z.enum(tn),left:a.z.lazy(()=>rC),right:a.z.lazy(()=>rC)}),rP=a.z.strictObject({op:a.z.enum(ts),expr:a.z.lazy(()=>rC)}),rq=a.z.strictObject({op:a.z.enum(["not","isnull","isnotnull"]),expr:a.z.lazy(()=>rC)}),rM=a.z.strictObject({op:a.z.literal("cast"),expr:a.z.lazy(()=>rC),type:ru}),rC=a.z.union([rw,rT,rE,rI,rA,rS,rN,rR,rU,rP,rq,rM]),rD=a.z.strictObject({expr:rC,alias:a.z.string()}),rF=a.z.strictObject({expr:rC,type:a.z.enum(["object","array"])}),rB=a.z.union([a.z.object({dimensions:a.z.array(rD),pivot:a.z.array(rD),measures:a.z.array(rD)}),a.z.object({select:a.z.array(rD)})]),rV=a.z.strictObject({name:a.z.string(),objects:a.z.array(a.z.string()).nullish()}),rJ=a.z.object({dir:tm}).and(a.z.union([a.z.object({alias:a.z.string()}),a.z.object({expr:rC})])),rQ=a.z.array(rJ);function rG(e){return"cast"===e.op?rG(e.expr):e}function r$(e,t,r){throw new rY(t,e.schema,r)}a.z.object({filter:rC.nullish(),from:rV.nullish(),unpivot:a.z.array(rF),sort:rQ.nullish(),limit:a.z.number().int().nullish(),cursor:a.z.string().nullish()}).and(rB);var rY=class extends Error{constructor(e,t,r){super("".concat(e)),this.prefix=e,this.schema=t,this.expr=r}};function rW(e){return"'".concat(e.replace(/'/g,"''"),"'")}function rH(e){return'"'.concat(e.replace(/"/g,'""'),'"')}var rZ=class{},rX=class extends rZ{toNumericParamQuery(){return{query:this.text,params:[]}}toPlainStringQuery(){return this.text}constructor(e){super(),this.text=e}},rK=class extends rZ{toNumericParamQuery(e,t){let r=null!=e?e:0,n=null!=t?t:new Map,i=[],a="";for(let e=0;e<this.fragments.length;e++){let t=this.fragments[e],o=n.get(t);if(void 0!==o)a+="$".concat(o);else if(t instanceof rZ){let{query:e,params:o}=t.toNumericParamQuery(r+i.length,n);a+=e,i.push(...o)}else{i.push(Array.isArray(this.fragments[e])||this.fragments[e]&&"object"==typeof this.fragments[e]?JSON.stringify(this.fragments[e]):this.fragments[e]);let t=r+i.length;a+="$".concat(t),n.set(this.fragments[e],t)}}return{query:a,params:i}}toPlainStringQuery(){return this.fragments.map(e=>e instanceof rZ?e.toPlainStringQuery():"string"==typeof e?rW(e):"number"==typeof e?e.toString():null===e?"null":rW(JSON.stringify(e))).join("")}constructor(e){super(),this.fragments=e}},r0=class extends rZ{toNumericParamQuery(){return{query:this.query,params:[]}}toPlainStringQuery(){return this.query}constructor(e){super(),this.query=e}},r1=class extends rZ{toNumericParamQuery(){return{query:this.name.map(rH).join("."),params:[]}}toPlainStringQuery(){return this.name.map(rH).join(".")}constructor(e){super(),this.name=e}};function r2(e){return new r1(Array.isArray(e)?e:[e])}function r6(e){return new rX(e)}function r4(e,t){let r=t instanceof rZ?t:new r0(t);return new rK(e.flatMap((e,t)=>0===t?[e]:[r,e]))}function r3(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];let i=[];for(let t=0;t<e.length;t++)if(i.push(r6(e[t])),t<r.length){let e=r[t];i.push(e)}return new rK(i)}function r8(e,t,r){switch(t.op){case"literal":return r3(s(),t.value);case"interval":return r3(l(),r6("".concat(t.value)),r6(t.unit.toLocaleUpperCase()));case"eq":case"is":case"ne":case"lt":case"le":case"gt":case"ge":case"and":case"or":case"add":case"sub":case"mul":case"div":case"mod":case"like":case"ilike":var n;return r3(c(),r(e,t.left),(n=t.op,new r0((()=>{switch(n){case"eq":return"=";case"ne":return"!=";case"lt":return"<";case"le":return"<=";case"gt":return">";case"ge":return">=";case"like":return"LIKE";case"ilike":return"ILIKE";case"is":return"IS";case"and":return"AND";case"or":return"OR";case"add":return"+";case"sub":case"neg":return"-";case"mul":return"*";case"div":return"/";case"mod":return"%";case"not":return"NOT";case"field":case"function":case"literal":case"interval":case"cast":case"isnull":case"isnotnull":case"if":case"includes":throw Error("Unexpected op: ".concat(n))}})())),r(e,t.right));case"neg":return r3(u(),r(e,t.expr));case"not":return r3(p(),r(e,t.expr));case"isnull":return r3(d(),r(e,t.expr));case"isnotnull":return r3(h(),r(e,t.expr));case"if":let i=t.conds.map(t=>r3(m(),r(e,t.cond),r(e,t.then)));return r3(f(),r4(i," "),r(e,t.else));default:return r$(e,"Unexpected op: ".concat(t.op),t)}}function r9(e){return"__unpivot_".concat(e)}function r5(e,t){switch(t.op){case"literal":let r=rz(t),n=r3(z(),t.value);return"datetime"===r?n=nr(n,"string","datetime"):"boolean"===r&&(n=n?r3(b()):r3(y())),n;case"field":let i;e.table||r$(e,"Field reference outside of table",t),0==t.name.length&&r$(e,"Table reference",t);let a=t.name[0],o=[];t.source?(o.push(r9(t.source.unpivot)),"key"===t.source.type?o.push(1):"value"===t.source.type&&o.push(2),i={type:"String"}):e.table.schema.columns[a]?(null!==e.table.alias&&o.push(e.table.alias),o.push(...e.table.schema.columns[a].path),o.push(...t.name.slice(1)),i=e.table.schema.columns[a].type):r$(e,"Unknown field: ".concat(a),t);let s=e=>r4(e.map(e=>"string"==typeof e?r2(e):r3(g(),r6("".concat(e)))),".");if(o.length<=2){let e=s(o),r=rb(nt(i)),n=rb(t.type),a=r===n?null:n;return null!==a&&"string"!==a&&(e=nr(e,"string",a)),e}let l=s(o.slice(0,2));if("Map"===i.type){o.length>3&&r$(e,"Unsupported nested map access",t);let r=r3(_(),l,o[2]),n=rb(nt(i.value)),a=rb(t.type),s=n===a?null:a;if(null!==s)return nr(r,n,s);return r}{let e=rb(t.type),r=r4(o.slice(2).map(e=>r3(v(),e)),", ");if(ry(e))return r3(j(),l,r);return r3(x(),l,r,ne(e))}case"function":return function(e,t){let r=t.args.map(t=>r5(e,t));switch(t.name){case"count":case"sum":case"avg":case"min":case"max":return r3(S(),r2(t.name),r4(r,", "));case"percentile":return r3(N(),r[1],r[0]);case"second":case"minute":case"hour":case"day":case"week":case"month":case"year":let n=r3(L(),r[0]);return e.tzOffset&&(n=r3(R(),n,-e.tzOffset)),r3(U(),t.name,n);case"current_timestamp":return r3(P());case"current_date":return r3(q());case"insert":return r3(M(),r[0],r4(r.slice(1),", "));case"coalesce":return r3(C(),r4(r,", "));case"least":case"greatest":return r3(D(),r4(r,", "),"least"===t.name?1:-1);case"nullif":return r3(F(),r[0],r[1]);default:let i=t.name;throw Error("Unsupported function: ".concat(i))}}(e,t);case"cast":return nr(r5(e,t.expr),rz(t.expr),t.type);case"includes":if(!ry(rb(rm(t.haystack))))return r3(T(),r5(e,t.haystack),r5(e,t.needle));{let r=r7(e,t.haystack,!1),n=r7(e,t.needle,!0);if(null!==r&&null!==n)return r3(k(),r,n);{let r=t=>r3(O(),r5(e,t));return r3(w(),r(t.haystack),r(t.needle))}}default:return r8(e,t,r5)}}function r7(e,t,r){var n;let i=rG(t),a=rz(t);if("field"===t.op&&(r||"array"===a)&&1===t.name.length&&(null==(n=e.table)?void 0:n.schema.columns[t.name[0]])!==void 0){let r=r5(e,t);return"array"===a?r:r3(E(),r)}if("literal"!==i.op)return null;{let e;let t=i.value;if(Array.isArray(t))e=t;else{if(!r)return null;e=[t]}return r3(A(),r4(e.map(e=>r3(I(),e)),","))}}function ne(e){switch(e){case"string":case"object":case"array":case"null":return"Nullable(String)";case"datetime":return"Nullable(DateTime64)";case"date":return"Nullable(Date)";case"number":return"Nullable(Float64)";case"integer":return"Nullable(Int64)";case"boolean":return"Nullable(Boolean)";case"interval":throw Error("Clickhouse has a separate type for each interval")}}function nt(e){switch(e.type){case"Nullable":case"LowCardinality":return nt(e.inner);case"UInt64":case"UInt32":case"UInt16":case"UInt8":case"Int64":case"Int32":case"Int16":case"Int8":return{type:"integer"};case"Boolean":return{type:"boolean"};case"Float64":case"Float32":return{type:"number"};case"DateTime":case"DateTime64":return{type:"string",format:"date-time"};case"Date":return{type:"string",format:"date"};case"String":case"FixedString":return{type:"string"};case"Map":if("string"!==nt(e.key).type)throw Error("Clickhouse Map key must be a string");return{additionalItems:nt(e.value)};case"Array":return{type:"array",items:nt(e.items)};default:throw Error("Unsupported Clickhouse type: ".concat(e.type))}}function nr(e,t,r){return t===r?e:"string"===t&&"datetime"===r?r3(B(),e):r3(V(),e,ne(r))}function nn(e){switch(e){case"string":return r3(ec());case"datetime":return r3(eu());case"date":return r3(ep());case"number":return r3(ed());case"integer":return r3(eh());case"boolean":return r3(em());case"object":case"array":return r3(ef());case"null":return r3(ez());case"interval":return r3(eb())}}function ni(e,t){switch(t.op){case"literal":var r;let n=null===(r=t.value)?"null":!0===r||!1===r?"boolean":eW.safeParse(r).success?"integer":eH.safeParse(r).success?"number":eY.safeParse(r).success?"boolean":eX.safeParse(r).success?"datetime":eZ.safeParse(r).success?"string":eK.safeParse(r).success?"array":e0.safeParse(r).success?"object":null;return null===n&&r$(e,"Unknown literal type: ".concat(t.value),t),ns(r3(ev(),t.value),n,rz(t));case"field":let i;e.table||r$(e,"Field reference outside of table",t),0==t.name.length&&r$(e,"Table reference",t);let a=t.name[0],o=[];if(t.source?(o.push(r9(t.source.unpivot)),o.push("key"===t.source.type?"key":"value"),i="key"===t.source.type?{type:"text"}:{type:"jsonb"}):e.table.schema.columns[a]?(null!==e.table.alias&&o.push(e.table.alias),o.push(...e.table.schema.columns[a].path),o.push(...t.name.slice(1)),i=e.table.schema.columns[a].type):r$(e,"Unknown field: ".concat(a),t),o.length<=2){let e=r2(o),[r,n]=rg(t.type,function(e){switch(e.type){case"json":case"jsonb":return{type:"object"};case"text":return{type:"string"};case"integer":case"bigint":case"bigserial":return{type:"integer"};case"numeric":return{type:"number"};case"boolean":return{type:"boolean"};case"timestamp":case"timestamp with time zone":return{type:"string",format:"date-time"};case"date":return{type:"string",format:"date"};default:throw Error("Unsupported Postgres type: ".concat(e.type))}}(i));return null!==n&&"string"!==n?e=r3(ej(),e,no(n)):rh(t.type)||"jsonb"===i.type||"json"===i.type||(e=r3(ex(),e)),e}let s=r6("jsonb_extract_path".concat(rh(t.type)?"_text":"")),l=r2(o.slice(0,2)),c=o.slice(2).map(e=>r3(ek(),e)),u=r3(eO(),s,l,r4(c,", ")),p=rb(t.type);return"string"!==p&&(u=r3(ew(),u,no(p))),u;case"function":return function(e,t){let r=t.args.map(t=>ni(e,t));switch(t.name){case"count":case"sum":case"avg":case"min":case"max":return r3(eA(),r2(t.name),r4(r,", "));case"percentile":return r3(eS(),r[1],r[0]);case"second":case"minute":case"hour":case"day":case"week":case"month":case"year":let n="UTC";if(e.tzOffset){let t=Math.abs(e.tzOffset),r=e.tzOffset>=0?"+":"-";n="".concat(r).concat(Math.floor(t/60).toString().padStart(2,"0"),":").concat((t%60).toString().padStart(2,"0"))}let i=r3(eN(),r[0],n);return r3(eL(),t.name,i);case"current_date":return r3(eR());case"current_timestamp":return r3(eU());case"insert":let a=r[0],o=r.slice(1).map((e,r)=>r%2==0?e:ns(e,rz(t.args[r+1]),"object"));return r3(eP(),a,r4(o,", "));case"coalesce":case"greatest":case"least":return r3(eq(),r6(t.name),r4(r,", "));case"nullif":return r3(eM(),r[0],r[1]);default:let s=t.name;throw Error("Unsupported function: ".concat(s))}}(e,t);case"cast":let d=ni(e,t.expr),h=rz(t.expr),m=t.type;if(h!==m)return ns(d,h,m);return d;case"includes":let f=rG(t.haystack),z=rG(t.needle);if("field"===f.op&&"literal"===z.op)return na(e,f,z);return r3(eT(),ni(e,t.haystack),ns(ni(e,t.needle),rz(t.needle),"object"));case"eq":let b,y;if("field"===t.left.op&&t.left.name.length>1&&"literal"===t.right.op&&!ry(t.right.type))b=t.left,y=t.right;else{if("field"!==t.right.op||!(t.right.name.length>1)||"literal"!==t.left.op||ry(t.left.type))return r8(e,t,ni);b=t.right,y=t.left}return na(e,b,y);default:return r8(e,t,ni)}}function na(e,t,r){var n;e.table||r$(e,"Field reference outside of table",t);let i=null!==e.table.alias?[e.table.alias]:[],a=t.name[0];if((null==(n=e.table)?void 0:n.schema.columns[a])||r$(e,"Unknown field: ".concat(a),t),i.push(...e.table.schema.columns[a].path),i.push(...t.name.slice(1)),i.length<=2)return r3(eE(),r2(i),r.value);"array"!==rz(t)||Array.isArray(r.value)||(r={op:"literal",value:[r.value],type:"array"});let o=i.slice(0,2),s={op:"literal",value:function(e,t){let r=t;for(let t=e.length-1;t>=0;t--)r={[e[t]]:r};return r}(i.slice(2),r.value),type:"object"};return r3(eI(),r2(o),ni(e,s))}function no(e){return r6(function(e){switch(e){case"string":case"null":return"text";case"datetime":return"timestamptz";case"date":return"date";case"number":return"numeric";case"integer":return"bigint";case"boolean":return"boolean";case"object":case"array":return"jsonb";case"interval":return"interval"}}(e))}function ns(e,t,r){return"boolean"===t&&["number","integer"].includes(r)?r3(eC(),e):ry(t)&&!ry(r)?r3(eD(),e,no(r)):ry(r)&&!ry(t)?r3(eF(),e,no(t)):r3(eB(),e,no(r))}function nl(e,t){let r="alias"in t?r2(t.alias):nc(e,t.expr);return r3(eV(),r,r6(t.dir))}function nc(e,t){switch(e.schema.type){case"duckdb":return function e(t,r){switch(r.op){case"literal":return r3(J(),r.value);case"field":let n;t.table||r$(t,"Field reference outside of table",r),0==r.name.length&&r$(t,"Table reference",r);let i=r.name[0],a=[];if(r.source?(a.push(r9(r.source.unpivot)),"key"===r.source.type?a.push("key"):"value"===r.source.type&&a.push("value"),n="key"===r.source.type?{type:"varchar"}:{type:"json"}):t.table.schema.columns[i]?(null!==t.table.alias&&a.push(t.table.alias),a.push(...t.table.schema.columns[i].path),a.push(...r.name.slice(1)),n=t.table.schema.columns[i].type):r$(t,"Unknown field: ".concat(i),r),a.length<=2||"struct"===n.type){let e=r2(a),[t,i]=rg(r.type,function e(t){switch(t.type){case"varchar":return{type:"string"};case"json":return{type:"object"};case"double":return{type:"number"};case"integer":case"bigint":case"hugeint":return{type:"integer"};case"boolean":return{type:"boolean"};case"timestamp":return{type:"string",format:"date-time"};case"date":return{type:"string",format:"date"};case"struct":return{type:"object",properties:Object.fromEntries(Object.entries(t.fields).map(t=>{let[r,n]=t;return[r,e(n)]}))};default:throw Error("Unsupported DuckDB type: ".concat(t.type))}}(n));return null!==i&&"string"!==i?e=r3(Q(),e,nn(i)):rh(r.type)||"json"===n.type?1===r.name.length&&"json"===n.type&&null!==i&&(e=r3($(),e,nn(i))):e=r3(G(),e),e}"json"!==n.type&&r$(t,'Unsupported field reference "'.concat(r.name.join("."),'" on type ').concat(n.type),r);let o=r6("json_extract".concat(rh(r.type)?"_string":"")),s=r2(a.slice(0,2)),l="$."+a.slice(2).map(rH).join("."),c=r3(Y(),o,s,l),u=rb(r.type);return"string"!==u&&(c=r3(W(),c,nn(u))),c;case"function":return function(t,r){let n=r.args.map(r=>e(t,r));switch(r.name){case"count":case"sum":case"avg":case"min":case"max":return r3(Z(),r2(r.name),r4(n,", "));case"percentile":return r3(X(),n[1],n[0]);case"second":case"minute":case"hour":case"day":case"week":case"month":case"year":let i=r3(K(),n[0]);return t.tzOffset&&(i=r3(er(),i,t.tzOffset>0?r3(ee()):r3(et()),Math.abs(t.tzOffset))),r3(en(),r.name,i);case"current_timestamp":return r3(ei());case"current_date":return r3(ea());case"insert":return r3(eo(),n[0],r4(n.slice(1),", "));case"coalesce":case"greatest":case"least":return r3(es(),r6(r.name),r4(n,", "));case"nullif":return r3(el(),n[0],n[1]);default:let a=r.name;throw Error("Unsupported function: ".concat(a))}}(t,r);case"cast":var p,d,h;return p=e(t,r.expr),(d=rz(r.expr))===(h=r.type)?p:d&&ry(d)&&!ry(h)?r3(ey(),p,nn(h)):ry(h)&&!ry(d)?r3(eg(),p,nn(d)):r3(e_(),p,nn(h));case"includes":return r3(H(),e(t,r.haystack),e(t,r.needle));default:return r8(t,r,e)}}(e,t);case"postgres":return ni(e,t);case"clickhouse":return r5(e,t)}}},83673:function(e,t,r){r.d(t,{Dc:function(){return C},VE:function(){return es}});var n,i=r(95370),a=r(34846),o=i.z.string(),s=i.z.string(),l=i.z.string(),c=i.z.string(),u=i.z.string(),p=i.z.string(),d=i.z.any(),h=i.z.boolean(),m=i.z.array(d),f=i.z.number(),z=i.z.number(),b=i.z.number(),y=i.z.number(),g=i.z.number(),_=i.z.number().nonnegative(),v=i.z.number().nonnegative().default(0),j=i.z.string(),x=i.z.array(i.z.lazy(()=>F)),k=i.z.union([i.z.lazy(()=>F),x]).default(!0),O=i.z.boolean(),w=i.z.string(),T=i.z.array(w).default([]),E=i.z.record(i.z.any()).default({}),I=i.z.record(i.z.any()).default({}),A=i.z.record(i.z.any()).default({});i.z.union([i.z.lazy(()=>F),T]);var S=i.z.record(i.z.any()),N=i.z.array(d),L=i.z.enum(["array","boolean","integer","null","number","object","string"]),R=i.z.array(L),U=i.z.union([L,R]),P=i.z.string(),q=i.z.string(),M=i.z.string(),C=i.z.object({$id:o.optional(),$schema:s.optional(),$ref:l.optional(),$comment:c.optional(),title:u.optional(),description:p.optional(),default:d.optional(),readOnly:h.optional(),examples:m.optional(),multipleOf:f.optional(),maximum:z.optional(),exclusiveMaximum:b.optional(),minimum:y.optional(),exclusiveMinimum:g.optional(),maxLength:_.optional(),minLength:v.optional(),pattern:j.optional(),additionalItems:i.z.lazy(()=>F.optional()),items:k.optional(),maxItems:_.optional(),minItems:v.optional(),uniqueItems:O.optional(),contains:i.z.lazy(()=>F.optional()),maxProperties:_.optional(),minProperties:v.optional(),required:T.optional(),additionalProperties:i.z.lazy(()=>F.optional()),definitions:E.optional(),properties:I.optional(),patternProperties:A.optional(),dependencies:S.optional(),propertyNames:i.z.lazy(()=>F.optional()),const:d.optional(),enum:N.optional(),type:U.optional(),format:P.optional(),contentMediaType:q.optional(),contentEncoding:M.optional(),if:i.z.lazy(()=>F.optional()),then:i.z.lazy(()=>F.optional()),else:i.z.lazy(()=>F.optional()),allOf:x.optional(),anyOf:x.optional(),oneOf:x.optional(),not:i.z.lazy(()=>F.optional())}).catchall(i.z.any()),D=i.z.boolean(),F=i.z.union([C,D]),B=i.z.union([i.z.strictObject({type:i.z.enum(["bigint","bit","blob","boolean","date","double","hugeint","integer","interval","real","smallint","time","timestamp with time zone","timestamp","tinyint","ubigint","uhugeint","uinteger","usmallint","utinyint","uuid","varchar","json"])}),i.z.strictObject({type:i.z.literal("decimal"),prec:i.z.number().int().optional(),scale:i.z.number().int().optional()})]),V=i.z.object({type:i.z.literal("array"),items:i.z.lazy(()=>G)}),J=i.z.object({type:i.z.literal("struct"),fields:i.z.lazy(()=>i.z.record(G))}),Q=i.z.object({type:i.z.literal("map"),key:i.z.lazy(()=>B),value:i.z.lazy(()=>G)}),G=i.z.union([B,V,Q,J]),$=i.z.strictObject({path:i.z.array(i.z.string()),type:G}),Y=i.z.strictObject({columns:i.z.record($)}),W=i.z.union([i.z.strictObject({type:i.z.enum(["bigint","bigserial","bit","bit varying","boolean","box","bytea","character","character varying","cidr","circle","date","double precision","inet","integer","interval","json","jsonb","line","lseg","macaddr","macaddr8","money","path","pg_lsn","pg_snapshot","point","polygon","real","smallint","smallserial","serial","text","time","time with time zone","timestamp","timestamptz","timestamp with time zone","tsquery","tsvector","txid_snapshot","uuid","xml"])}),i.z.strictObject({type:i.z.literal("numeric"),prec:i.z.number().int().optional(),scale:i.z.number().int().optional()})]),H=i.z.strictObject({path:i.z.array(i.z.string()),type:W}),Z=i.z.strictObject({columns:i.z.record(H)}),X=i.z.union([i.z.strictObject({type:i.z.enum(["UInt8","UInt16","UInt32","UInt64","UInt128","UInt256","Int8","Int16","Int32","Int64","Int128","Int256","Float32","Float64","Boolean","String","FixedString","Date","DateTime","DateTime64","JSON","UUID","IPv4","IPv6","Point","Ring","Polygon","MultiPolygon","Nothing","Interval"])}),i.z.strictObject({type:i.z.literal("Decimal"),precision:i.z.number(),scale:i.z.number()})]),K=i.z.object({type:i.z.literal("Array"),items:i.z.lazy(()=>ei)}),ee=i.z.object({type:i.z.literal("Nullable"),inner:i.z.lazy(()=>ei)}),et=i.z.object({type:i.z.literal("Enum"),values:i.z.record(i.z.number())}),er=i.z.object({type:i.z.literal("LowCardinality"),inner:i.z.lazy(()=>ei)}),en=i.z.object({type:i.z.literal("Map"),key:i.z.lazy(()=>ei),value:i.z.lazy(()=>ei)}),ei=i.z.union([X,K,ee,et,er,en]),ea=i.z.strictObject({path:i.z.array(i.z.string()),type:ei}),eo=i.z.strictObject({columns:i.z.record(ea)});function es(e){return"object"==typeof e?e:!0===e?{}:{not:{}}}(e=>{function t(e){return{type:e}}e.scalar=t,e.nullable=function(e){return{type:"Nullable",inner:t(e)}},e.array=function(e){return{type:"Array",items:t(e)}},e.record=function(e){return{type:"Map",key:t("String"),value:e}}})(n||(n={}));var el=new a({coerceTypes:!1});el.addFormat("uuid",{type:"string",validate:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}),el.addFormat("date-time",{type:"string",validate:e=>!isNaN(Date.parse(e))}),i.z.enum(["array","boolean","integer","null","number","object","string","date","datetime","interval"]),i.z.union([Y,Z,eo]),i.z.union([i.z.strictObject({type:i.z.literal("duckdb"),tables:i.z.record(Y)}),i.z.strictObject({type:i.z.literal("postgres"),tables:i.z.record(Z)}),i.z.strictObject({type:i.z.literal("clickhouse"),tables:i.z.record(eo)})])},20037:function(e,t,r){r.d(t,{Aq:function(){return v},CD:function(){return eg},CO:function(){return b},Ci:function(){return k},EQ:function(){return C},FL:function(){return eT},HF:function(){return T},I:function(){return A},JN:function(){return eE},JQ:function(){return S},Ke:function(){return P},Lu:function(){return D},MJ:function(){return ej},MT:function(){return I},OM:function(){return O},PM:function(){return _},Ro:function(){return L},Rq:function(){return ef},XH:function(){return y},Xc:function(){return eh},Xv:function(){return ex},YS:function(){return m},_S:function(){return ez},bL:function(){return U},bx:function(){return d},cz:function(){return eb},dO:function(){return ey},eH:function(){return eO},eM:function(){return N},ez:function(){return R},fB:function(){return j},hI:function(){return eI},iU:function(){return ev},jh:function(){return x},jo:function(){return J},ne:function(){return eA},ox:function(){return p},qR:function(){return q},r0:function(){return E},s0:function(){return em},s3:function(){return Q},s4:function(){return g},sR:function(){return z},sT:function(){return w},tt:function(){return B},wI:function(){return M},yR:function(){return h}});var n=r(75570),i=r(49091),a=r(95370),o=r(28865),s=r(73928),l=r(38869),c=r(83673),u=r(6298);function p(e){return"'".concat(e.replace(/'/g,"''"),"'")}function d(e){return'"'.concat(e.replace(/"/g,'""'),'"')}function h(e){return"string"==typeof e?d(e):e.map(d).join(".")}function m(e){return p(["$"].concat(e.map(d)).join("."))}function f(e,t,r){return"json_extract(".concat(e,", ").concat(m(t),")")+(r?"::".concat(r):"")}function z(e){let{path:t,desc:r}=e;return"".concat(h(t)," ").concat(r?"DESC":"ASC")}function b(e,t){return t&&t instanceof Object&&!Array.isArray(t)?Object.entries(t).flatMap(t=>{let[r,n]=t;return b(e.concat(r),n)}):[e]}function y(e){return e.map(e=>{if(e.length>1)throw Error("Expected nested field to be empty: ".concat(e));return e[0]})}var g="id",_="span_id",v="root_span_id",j="_xact_id",x="_update_nonce",k="_object_delete",O="created",w="user_id",T="org_id",E="log_id",I="project_id",A="experiment_id",S="dataset_id",N="prompt_session_id",L="scores",R="metrics",U="metadata",P="_audit_source",q="_audit_metadata",M="output",C="expected",D="tags",F="__tag_filter",B="estimated_cost",V=["+","-"];function J(e){var t;return null!=(t=null==e?void 0:e.map(e=>({type:e[0],text:e.slice(1)})).filter(e=>V.includes(e.type)))?t:[]}function Q(e){let{type:t,text:r}=e,n="json_contains(tags, ".concat(p(JSON.stringify(r)),")");return"+"===t?n:"COALESCE(".concat(n,", false) = false")}function G(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}function $(e,t){return(0,u.ZP)(e,{$refStrategy:"none",override:(e,t)=>{var r,n,i;return e instanceof Object&&(null==e?void 0:e.typeName)==="ZodEffects"&&(null==(n=null==(r=null==e?void 0:e.openapi)?void 0:r.metadata)?void 0:n.format)==="date-time"?{type:"string",format:"date-time",description:null!=(i=null==e?void 0:e.description)?i:"Creation date"}:u.kQ},...t})}var Y=a.z.strictObject({experiment:a.z.array(i.X9),dataset:a.z.array(i.f_),prompt_session:a.z.array(i.r6),org_logs:a.z.array(i.Tj),project_logs:a.z.array(i.Tj),project:a.z.array(i.Tj.merge(i.X9)),project_prompts:a.z.array(i.ys),org_prompts:a.z.array(i.ys),project_functions:a.z.array(i._G)}),W=["project_id","experiment_id","dataset_id","prompt_session_id","log_id","org_id"],H=a.z.strictObject({text:a.z.string(),parent_id:a.z.string().nullish(),reactions:a.z.record(a.z.array(a.z.string()))}),Z=a.z.strictObject({action:a.z.literal("merge"),path:a.z.array(a.z.string()),from:a.z.any(),to:a.z.any()}),X=a.z.union([Z,a.z.strictObject({action:a.z.literal("delete")}),a.z.strictObject({action:a.z.literal("upsert")})]),K=a.z.strictObject({origin:a.z.strictObject({id:a.z.string(),_xact_id:a.z.string().nullish()}),source:a.z.string(),metadata:a.z.record(a.z.any()).nullish(),comment:H.nullish(),audit_data:X.nullish()});a.z.strictObject({id:i.Tj.shape.id,_xact_id:i.Tj.shape._xact_id,created:i.Tj.shape.created,...Object.fromEntries(W.map(e=>[e,a.z.string().nullish()])),...K.shape});var ee=c.Dc.parse($(Y)),et=a.z.strictObject(Object.fromEntries(Object.entries(Y.shape).map(e=>{let[t,r]=e;return[t,function(e){let t=Object.fromEntries(Object.entries(e.element.shape).filter(e=>{let[t,r]=e;return["id","_xact_id","created"].concat(W).includes(t)}));return a.z.array(a.z.strictObject({...t,...K.shape,source:a.z.string()}))}(r)]})));c.Dc.parse($(et));var er={id:{path:["id"],type:{type:"varchar"}},span_id:{path:["span_id"],type:{type:"varchar"}},root_span_id:{path:["root_span_id"],type:{type:"varchar"}},_xact_id:{path:["_xact_id"],type:{type:"varchar"}},created:{path:["created"],type:{type:"varchar"}},tags:{path:["tags"],type:{type:"json"}}},en={...er,project_id:{path:["project_id"],type:{type:"varchar"}},input:{path:["input"],type:{type:"json"}},output:{path:["output"],type:{type:"json"}},expected:{path:["expected"],type:{type:"json"}},scores:{path:["scores"],type:{type:"json"}},metadata:{path:["metadata"],type:{type:"json"}},metrics:{path:["metrics"],type:{type:"json"}},context:{path:["context"],type:{type:"json"}},span_parents:{path:["span_parents"],type:{type:"json"}},span_attributes:{path:["span_attributes"],type:{type:"json"}}},ei={columns:{...en,experiment_id:{path:["experiment_id"],type:{type:"varchar"}},dataset_record_id:{path:["dataset_record_id"],type:{type:"varchar"}}}},ea={columns:{...en,org_id:{path:["org_id"],type:{type:"varchar"}},log_id:{path:["log_id"],type:{type:"varchar"}}}},eo={columns:{...ei.columns,...ea.columns}},es={columns:{...er,project_id:{path:["project_id"],type:{type:"varchar"}},dataset_id:{path:["dataset_id"],type:{type:"varchar"}},input:{path:["input"],type:{type:"json"}},expected:{path:["expected"],type:{type:"json"}},metadata:{path:["metadata"],type:{type:"json"}}}},el={columns:{...er,prompt_session_id:{path:["prompt_session_id"],type:{type:"varchar"}},prompt_session_data:{path:["prompt_session_data"],type:{type:"json"}},prompt_data:{path:["prompt_data"],type:{type:"json"}},object_data:{path:["object_data"],type:{type:"json"}},completion:{path:["completion"],type:{type:"json"}}}},ec={columns:{...er,org_id:{path:["org_id"],type:{type:"varchar"}},project_id:{path:["project_id"],type:{type:"varchar"}},log_id:{path:["log_id"],type:{type:"varchar"}},name:{path:["name"],type:{type:"varchar"}},slug:{path:["slug"],type:{type:"varchar"}},description:{path:["description"],type:{type:"varchar"}},prompt_data:{path:["prompt_data"],type:{type:"json"}},metadata:{path:["metadata"],type:{type:"json"}}}},eu={columns:{...ec.columns,function_data:{path:["function_data"],type:{type:"json"}}}},ep={type:"duckdb",tables:{experiment:ei,dataset:es,prompt_session:el,org_logs:ea,project_logs:ea,project:eo,project_prompts:ec,org_prompts:ec,project_functions:eu}};function ed(e,t){return Object.fromEntries(Object.entries(e).filter(e=>{let[r,n]=e;return t(r,n)}))}function eh(e,t){return Object.fromEntries(Object.entries(e).map(e=>{let[r,n]=e;return[r,t(r,n)]}))}function em(e){let{experimentScanRaw:t,modelSpecScan:r,scoreFields:n,scoreConfig:i,comparisonKey:a,filters:o,tags:s}=e;if(!t)return null;let l=[d(v)],c=l.join(","),u=i.filter(e=>eT(e.score_type)),p=n.filter(e=>!u.find(t=>t.name===e)),h=p.map((e,t)=>[e,"__score".concat(t)]),z=Object.entries(eI({scoreConfig:i,scoreNames:p,scoreToField:Object.fromEntries(h)})),b=z.length+h.length>0?"STRUCT_PACK(".concat(z.concat(h).map(e=>{let[t,r]=e;return"".concat(d(t)," := ").concat(r,"\n")}).join(","),') AS "').concat(L,'"'):'NULL AS "'.concat(L,'"'),y=J(s).map((e,t)=>({typedTag:e,field:'"__tag'.concat(t,'"')})),g=eA({comparisonKey:a}),x=e=>{let t=Q(e);return"CASE WHEN ".concat(t," THEN 1 ELSE 0 END")},k=(e,t)=>"+"===e.type?"MAX(".concat(t,")"):"MIN(".concat(t,")"),O=y.map(e=>{let{field:t}=e;return"".concat(t," = 1")}),w=O.length?"(".concat(O.join(" AND "),') AS "').concat(F,'"'):'TRUE AS "'.concat(F,'"');return"\nWITH\n".concat(r?"model_specs as (".concat(r,"),"):"","\nbase AS (\n    ").concat(r?'SELECT *,\n      CAST(json_extract("metrics", \'$."prompt_tokens"\') AS INTEGER) * "input_cost_per_token" AS "prompt_cost",\n      CAST(json_extract("metrics", \'$."completion_tokens"\') AS INTEGER) * "output_cost_per_token" as "completion_cost"\n    FROM (\n      SELECT *, json_extract_string("metadata", \'$.model\') AS "model" FROM ('.concat(t,') "t"\n    ) exp LEFT JOIN model_specs ON exp.model = model_specs.model'):"SELECT * FROM (".concat(t,') "t"'),"\n),\nspans_unpacked AS (\nSELECT\n    ").concat(l.concat(["json_extract(".concat(L,", [").concat(h.map(e=>{let[t,r]=e;return m([t])}),"]) AS all_scores")]).concat(y.map(e=>{let{typedTag:t,field:r}=e;return"".concat(x(t)," AS ").concat(r)})).concat(["json_extract(".concat(R,", 'cached') AS cached"),"".concat(f(R,["end"],"DOUBLE"),"-").concat(f(R,["start"],"DOUBLE")," AS duration")]).concat(r?['"prompt_cost"','"completion_cost"']:[]).join(","),"\nFROM\n    base\n),\nspans_aggregated AS (\nSELECT\n    ").concat(l.concat(h.map((e,t)=>{let[r,n]=e;return"AVG(all_scores[".concat(t+1,"]::double) AS ").concat(n)})).concat(y.map(e=>{let{typedTag:t,field:r}=e;return"".concat(k(t,r)," AS ").concat(r)})).concat(["MIN(cached) AS cached","MAX(duration) AS duration"]).concat(r?['SUM("prompt_cost" + "completion_cost") as "'.concat(B,'"')]:[]).join(","),"\nFROM\n    spans_unpacked\nGROUP BY\n    ").concat(c,"\n),\nspans_repacked AS (\nSELECT\n    ").concat(c,",\n    ").concat(b,",\n    ").concat(w,',\n    STRUCT_PACK(\n      cached := cached,\n      duration := duration,\n      "').concat(B,'" := ').concat(r?'"'.concat(B,'"'):"NULL",'\n    ) AS computed_metrics\nFROM\n    spans_aggregated\n),\ncandidate_spans AS (\nSELECT\n    base."').concat(v,'"\nFROM\n    base\n    ').concat((null==o?void 0:o.length)?"WHERE ".concat(o.map(e=>"(".concat(e,")")).join(" AND ")):"",'\n)\nSELECT\n    base.id,\n    base."').concat(j,'",\n    MD5(').concat(g,') AS comparison_key,\n    base."').concat(_,'",\n    base."').concat(v,'",\n    base."').concat(R,'",\n    spans_repacked."').concat(L,'",\n    spans_repacked.computed_metrics,\n    spans_repacked.computed_metrics.duration AS duration,\n    ').concat(r?'spans_repacked.computed_metrics."'.concat(B,'"'):"NULL",' AS "').concat(B,'"\nFROM\n    base\n        ').concat(((e,t)=>{let r=l.map(r=>"".concat(e,".").concat(r," IS NOT DISTINCT FROM ").concat(t,".").concat(r));return"JOIN ".concat(t," ON (").concat(r.concat("TRUE").join(" AND "),")")})("base","spans_repacked"),'\nSEMI JOIN\n    candidate_spans\nON\n    base."').concat(_,'" IS NOT DISTINCT FROM candidate_spans."').concat(v,'"\nWHERE\n    spans_repacked."').concat(F,'"\n  ')}function ef(e){let{experimentScanRaw:t,summaryScan:r}=e;return t&&r&&'(\n              SELECT\n                exp.* EXCLUDE (scores, metrics),\n                summary.comparison_key, summary.scores, summary.metrics, summary.computed_metrics,\n                summary.duration, summary."'.concat(B,'"\n              FROM\n                (').concat(t,") exp\n                INNER JOIN (").concat(r,") summary ON exp.id = summary.id\n          )")}function ez(e){let{scoreFields:t,metricFields:r,comparisonMetricFields:n,comparisonScoreFields:i,scoreConfig:a}=e,o=t.concat(a.filter(e=>eT(e.score_type)&&!t.includes(e.name)).map(e=>e.name)).map(e=>({name:e,def:t=>"".concat(t,".scores.").concat(d(e)),desc:!1})),s=[];r.includes("start")&&r.includes("end")&&s.push({name:"duration",def:e=>"(CASE WHEN ".concat(e,'.computed_metrics."cached" THEN NULL ELSE ').concat(f("".concat(e,".metrics"),["end"],"DOUBLE"),"-").concat(f("".concat(e,".metrics"),["start"],"DOUBLE")," END)"),desc:!0}),r.includes("prompt_tokens")&&r.includes("completion_tokens")&&s.push({name:"estimated_cost",def:e=>"(CASE WHEN ".concat(e,'.computed_metrics."cached" THEN NULL ELSE ').concat(e,'.computed_metrics."').concat(B,'" END)'),desc:!0});let l=s.map(e=>e.name),c=n.filter(e=>"tokens"===e).concat(["start","end"].every(e=>n.includes(e))?["duration"]:[]).concat(["prompt_tokens","completion_tokens"].every(e=>n.includes(e))?["estimated_cost"]:[]),u=o.concat(s),p=u.filter(e=>{let{name:t}=e;return i.includes(t)||c.includes(t)||a.find(e=>e.name===t&&eT(e.score_type))});return{allSummaryDefBatches:G(u,20),comparableDefBatches:G(p,20),summaryMetricNames:l}}function eb(e){let{primaryExperimentScan:t,allSummaryDefBatches:r,groupKey:n,comparisonKey:i}=e;return t&&r.length>0&&n?r.map(e=>"\n    SELECT\n      ".concat(n("e1"),' AS "__bt_group_key",\n      ').concat(e.map(e=>{let{name:t,def:r}=e;return"\n            struct_pack(\n              avg := AVG(".concat(r("e1"),"),\n              min := MIN(").concat(r("e1"),"),\n              max := MAX(").concat(r("e1"),"),\n              sum := SUM(").concat(r("e1"),"),\n              stddev := /*STDDEV_SAMP(").concat(r("e1"),")*/ NULL,\n              all_keys := ARRAY_AGG(DISTINCT ").concat(i("e1"),") FILTER (").concat(r("e1")," IS NOT NULL)\n            ) AS ").concat(d(t),",\n            ")}).join(""),"\n      FROM (").concat(t,') e1\n      WHERE "__bt_group_key" IS NOT NULL\n      GROUP BY 1\n      ')):null}function ey(e){let{primaryExperimentScan:t,comparisonExperimentScan:r,comparableDefBatches:n,groupKey:i,comparisonKey:a}=e;return t&&r&&n.length>0&&i?n.map(e=>"\n  WITH\n  e1 AS (\n    SELECT * FROM (".concat(t,") e1\n  ),\n  e2 AS (\n    SELECT * FROM (").concat(r,") e2\n  ),\n  diffs AS (\n    SELECT\n      ").concat(i("e1"),' AS "__bt_group_key",\n      ').concat(e.map(e=>{let{name:t,def:r}=e;return"struct_pack(\n            compareAvg := AVG(".concat(r("e2"),"),\n            compareMin := MIN(").concat(r("e2"),"),\n            compareMax := MAX(").concat(r("e2"),"),\n            compareSum := SUM(").concat(r("e2"),"),\n            diffAvg := AVG(").concat(r("e1"),") - AVG(").concat(r("e2"),"),\n            diffMin := MIN(").concat(r("e1"),") - MIN(").concat(r("e2"),"),\n            diffMax := MAX(").concat(r("e1"),") - MAX(").concat(r("e2"),"),\n            diffSum := SUM(").concat(r("e1"),") - SUM(").concat(r("e2"),")\n          ) AS ").concat(d(t),"\n          ")}).join(","),"\n    FROM e1 JOIN e2 ON ").concat(a("e1")," IS NOT DISTINCT FROM ").concat(a("e2"),'\n    WHERE "__bt_group_key" IS NOT NULL\n    GROUP BY 1\n  ),\n  e1_grouped AS (\n    SELECT\n      ').concat(a("e1"),' "input",\n      ANY_VALUE(').concat(i("e1"),') "__bt_group_key",\n      ').concat(e.map(e=>{let{name:t,def:r}=e;return"ROUND(AVG(".concat(r("e1"),"), ").concat(4,") ").concat(d(t),",")}).join("\n"),"\n      FROM e1\n      GROUP BY 1\n  ),\n  e2_grouped AS (\n    SELECT\n      ").concat(a("e2"),' "input",\n      ').concat(e.map(e=>{let{name:t,def:r}=e;return"ROUND(AVG(".concat(r("e2"),"), ").concat(4,") ").concat(d(t),",")}).join("\n"),'\n      FROM e2\n      GROUP BY 1\n  )\n  SELECT\n    (e1_grouped."__bt_group_key")::text AS "__bt_group_key",\n    ').concat(e.map(e=>{let{name:t,desc:r}=e;return"\n    struct_pack(\n      -- There is only one row in diffs so ANY_VALUE is fine\n      _name := ".concat(p(t),",\n      compareAvg := ANY_VALUE(diffs.").concat(d(t),".compareAvg),\n      compareMin := ANY_VALUE(diffs.").concat(d(t),".compareMin),\n      compareMax := ANY_VALUE(diffs.").concat(d(t),".compareMax),\n      compareSum := ANY_VALUE(diffs.").concat(d(t),".compareSum),\n      diffAvg := ANY_VALUE(diffs.").concat(d(t),".diffAvg),\n      diffMin := ANY_VALUE(diffs.").concat(d(t),".diffMin),\n      diffMax := ANY_VALUE(diffs.").concat(d(t),".diffMax),\n      diffSum := ANY_VALUE(diffs.").concat(d(t),'.diffSum),\n      improvements := ARRAY_AGG(DISTINCT e1_grouped."input") FILTER (e1_grouped.').concat(d(t)," ").concat(r?"<":">"," e2_grouped.").concat(d(t),'),\n      regressions := ARRAY_AGG(DISTINCT e1_grouped."input") FILTER (e1_grouped.').concat(d(t)," ").concat(r?">":"<"," e2_grouped.").concat(d(t),'),\n      equal := ARRAY_AGG(DISTINCT e1_grouped."input") FILTER (e1_grouped.').concat(d(t)," = e2_grouped.").concat(d(t),")\n    ) AS ").concat(d(t),",\n  ")}).join(""),'\n  FROM e1_grouped JOIN e2_grouped ON\n    -- This has already been transformed to the comparison key\n    e1_grouped."input" IS NOT DISTINCT FROM e2_grouped."input"\n    -- This is a single row relation\n    JOIN diffs ON e1_grouped."__bt_group_key" IS NOT DISTINCT FROM diffs."__bt_group_key"\n    GROUP BY 1\n  ')):null}function eg(e){var t;let{summaryData:r,diffData:i}=e,a=e_(r),o=e_(null!=i?i:[]);for(let e of Object.keys(a))a[e]=(0,n._$)(a[e],null!=(t=o[e])?t:{}),delete a[e].__bt_group_key;return a}function e_(e){let t={};for(let r of e)t[r.__bt_group_key]||(t[r.__bt_group_key]={}),Object.assign(t[r.__bt_group_key],r);return t}function ev(e){let{hasScores:t,hasMetrics:r,experimentScan:n}=e;return"\n      SELECT\n        1,\n        ".concat(t?"json_group_structure(json(".concat(L,")) as scores,"):"","\n        ").concat(r?"json_group_structure(json(".concat(R,")) as metrics,"):"",'\n      FROM (\n        -- This sort ensures that we look at scores from the top-level span first,\n        -- which means the "outermost" scores are the first that are displayed.\n        SELECT * FROM (').concat(n,")\n        ORDER BY ").concat(_," = ").concat(v,' DESC\n      ) "t"')}function ej(e){return["scores","metrics"].map(t=>{let r=e[t];if(!r)return null;let n=JSON.parse(r);return"NULL"===n||"JSON"===n||null===n?[]:b([],n)})}var ex="_bt_summary_group_key",ek=i.ic.strip().omit({score_type:!0,categories:!0}),eO=a.z.union([a.z.strictObject({score_type:a.z.literal("slider"),categories:a.z.unknown().nullish()}).merge(ek),a.z.strictObject({score_type:a.z.literal("categorical"),categories:i.GQ.array()}).merge(ek),a.z.strictObject({score_type:a.z.literal("weighted"),categories:a.z.record(a.z.number().nonnegative())}).merge(ek),a.z.strictObject({score_type:a.z.literal("minimum"),categories:a.z.array(a.z.string())}).merge(ek)]);function ew(e){return 0===e.length?{op:"literal",value:null}:e.reduce((e,t)=>({op:"add",left:e,right:t}))}function eT(e){return["weighted","minimum"].includes(e)}function eE(e,t,r){let n=[...e],i=t.map(e=>e.name.toLowerCase()),a=n.map(e=>{let n=i.indexOf((r?r(e):e).toLowerCase());return -1===n?{bucket:1,value:e,field:e}:{bucket:eT(t[n].score_type)?0:2,value:n,field:e}});return a.sort((e,t)=>(function(e,t,r){let n=ed(e,(e,t)=>void 0!==t),i=ed(t,(e,t)=>void 0!==t);for(let e of null!=r?r:Object.keys(n)){let t=n[e],r=i[e];if(void 0===t&&void 0!==r)return -1;if(void 0!==t&&void 0===r)return 1;if(t<r)return -1;if(t>r)return 1}return 0})(e,t,["bucket","value"])),a.map(e=>e.field)}function eI(e){let{scoreConfig:t,scoreNames:r,scoreToField:n}=e,i=function(e){let{scores:t,includeList:r}=e;return t.flatMap(e=>{switch(e.score_type){case"categorical":case"slider":return[];case"weighted":{let t=Object.entries(e.categories).filter(e=>{let[t]=e;return!r||r.includes(t)}),n=ew(t.map(e=>{let[t,r]=e;return{op:"mul",left:{op:"function",name:{op:"ident",name:["coalesce"]},args:[{op:"ident",name:[t]},{op:"literal",value:0}]},right:{op:"literal",value:r}}})),i={op:"function",name:{op:"ident",name:["nullif"]},args:[ew(t.map(e=>{let[t,r]=e;return{op:"if",conds:[{cond:{op:"isnull",expr:{op:"ident",name:[t]}},then:{op:"literal",value:0}}],else:{op:"literal",value:r}}})),{op:"literal",value:0}]};return[{name:e.name,expr:{op:"div",left:n,right:i}}]}case"minimum":{let t=e.categories.filter(e=>!r||r.includes(e));return[{name:e.name,expr:0===t.length?{op:"literal",value:null}:{op:"function",name:{op:"ident",name:["least"]},args:t.map(e=>({op:"ident",name:[e]}))}}]}default:throw Error("Unsupported score type ".concat(e))}})}({scores:t.filter(e=>eT(e.score_type)),includeList:r}),a={schema:ee.properties.experiment.items.properties.scores,scope:{},queryText:void 0,bindingMeasures:!1};return Object.fromEntries(i.map(e=>{let{name:t,expr:i}=e,o=(0,s.IY)(a,i);return[t,(0,l.m6)({schema:ep,table:{alias:null,schema:{columns:Object.fromEntries(r.map((e,t)=>{var r;return[e,{path:[null!=(r=null==n?void 0:n[e])?r:e],type:{type:"double"}}]}))}}},o).toPlainStringQuery()]}))}function eA(e){let{comparisonKey:t}=e,r=null!=t?t:"input",n=new o._b(r).parseExpr(),i={schema:ee.properties.experiment.items.properties,scope:{},queryText:r,bindingMeasures:!1},a=(0,s.IY)(i,n);return(0,l.m6)({schema:ep,table:{alias:"base",schema:ep.tables.experiment}},a).toPlainStringQuery()}},75570:function(e,t,r){r.d(t,{$V:function(){return w},A1:function(){return y},AZ:function(){return S},GG:function(){return k},HO:function(){return G},Ko:function(){return L},M6:function(){return rp},Ms:function(){return v},NG:function(){return I},Q4:function(){return N},Ri:function(){return h},Vt:function(){return V},_$:function(){return j},af:function(){return J},cX:function(){return A},e:function(){return f},kC:function(){return x},kt:function(){return O},qU:function(){return g},qf:function(){return F},qv:function(){return b},r:function(){return z},xi:function(){return rm}});var n,i,a,o,s=r(85422),l=r(87416),c=r(95370),u=r(94468),p=r(23824).Buffer,d=r(92104),h="_xact_id",m="_object_delete",f="_is_merge",z="_merge_paths",b="_audit_source",y="_audit_metadata",g=["app","api","external"],_="_parent_id",v="x-bt-found-existing";function j(e,t){for(let[r,n]of Object.entries(t)){let i=e[r];i instanceof Object&&!Array.isArray(i)&&t instanceof Object&&!Array.isArray(n)?j(i,n):e[r]=n}return e}function x(e,t){return(t?e.split(t):[e]).map(e=>e?e.charAt(0).toUpperCase()+e.slice(1):e).join(t||"")}function k(e){return"[".concat(e.join(","),"]")}function O(e,t){let r=e.get(t);if(void 0===r)throw Error("Map does not contain key ".concat(t));return r}function w(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.map((e,r)=>e.replace(/^\//,"").replace(r<t.length-1?/\/$/:"","")).filter(e=>""!==e.trim()).join("/")}function T(e){var t;let{graph:r,firstVisitF:n,lastVisitF:i}=e;for(let e of r.values())for(let t of e.values())if(!r.has(t))throw Error("Outgoing vertex ".concat(t," must be a key in the graph"));let a=new Set,o=(null!=(t=e.visitationOrder)?t:[...r.keys()]).map(e=>({eventType:"first",vertex:e,extras:{}})).reverse();for(;o.length;){let{eventType:e,vertex:t,extras:s}=o.pop();if("last"===e){null==i||i(t);continue}a.has(t)||(a.add(t),null==n||n(t,{parentVertex:s.parentVertex}),o.push({eventType:"last",vertex:t,extras:{}}),O(r,t).forEach(e=>{o.push({eventType:"first",vertex:e,extras:{parentVertex:t}})}))}}function E(e,t){return JSON.stringify(["org_id","project_id","experiment_id","dataset_id","prompt_session_id","log_id",null!=t&&t?_:"id"].map(t=>e[t]))}function I(e){for(let t of e)if(void 0===t.id)throw Error("Logged row is missing an id. This is an internal braintrust error. Please contact us at info@braintrust.dev for help");let t=new Map;for(let r of e){let e=E(r),n=t.get(e);if(void 0!==n&&r[f]){let e=!n[f];j(n,r),e&&delete n[f]}else t.set(e,r)}let r=[...t.values()],n=new Map(r.map((e,t)=>[E(e),t])),i=new Map(Array.from({length:r.length}).map((e,t)=>[t,new Set]));return r.forEach((e,t)=>{if(!e[_])return;let r=E(e,!0),a=n.get(r);void 0!==a&&O(i,a).add(t)}),(function(e){let t=new Map([...e.vertices].map(e=>[e,new Set]));for(let[r,n]of e.edges)O(t,r).add(n),O(t,n).add(r);let r=0,n=new Map;T({graph:t,firstVisitF:(e,t)=>{let i=(null==t?void 0:t.parentVertex)!==void 0?O(n,null==t?void 0:t.parentVertex):r++;n.set(e,i)}});let i=Array.from({length:r}).map(()=>[]);for(let[e,t]of n.entries())i[t].push(e);return i})({vertices:new Set(i.keys()),edges:new Set([...i.entries()].flatMap(e=>{let[t,r]=e;return[...r].map(e=>[t,e])}))}).map(e=>(function(e,t){let r=[];return T({graph:e,lastVisitF:e=>{r.push(e)},visitationOrder:t}),r.reverse()})(i,e)).map(e=>e.map(e=>r[e]))}function A(e){var t,r;let{items:n}=e,i=null!=(t=e.batchMaxNumItems)?t:Number.POSITIVE_INFINITY,a=null!=(r=e.batchMaxNumBytes)?r:Number.POSITIVE_INFINITY,o=[],s=[],l=[],c=[],u=0;function p(e){c.push(e),u+=e.length}function d(){l.push(c),c=[],u=0}for(;n.length;){for(let e of n){let t=0;for(let r of e){if(0===c.length||r.length+u<a&&c.length<i)p(r);else if(0===t)d(),p(r);else break;++t}t<e.length&&s.push(e.slice(t)),(u>=a||c.length>i)&&d()}c.length&&d(),l.length&&(o.push(l),l=[]),n=s,s=[]}return o}var S=!1;function N(e,t){return t?function(e){if("output"in e)return e;let t={...e,output:e.expected};return delete t.expected,t}(e):function(e){if("expected"in e)return e;let t={...e,tags:null,expected:e.output};return delete t.output,t}(e)}function L(e){if(!("dataset_id"in e)||!("expected"in e))return e;let t={...e,output:e.expected};if(delete t.expected,z in t)for(let e of t[z]||[])e.length>0&&"expected"===e[0]&&(e[0]="output");return t}function R(e){try{let t=s.Z(e);if(16!==t.length)throw Error();return{bytes:p.from(t),isUUID:!0}}catch(t){return{bytes:p.from(e,"utf-8"),isUUID:!1}}}var U=((n=U||{})[n.EXPERIMENT=1]="EXPERIMENT",n[n.PROJECT_LOGS=2]="PROJECT_LOGS",n),P=c.z.nativeEnum(U),q=class{toObject(){return{rowId:this.rowId,spanId:this.spanId,rootSpanId:this.rootSpanId}}constructor(e){if(this.rowId=e.rowId,this.spanId=e.spanId,this.rootSpanId=e.rootSpanId,!this.rowId)throw Error("rowId must be nonempty string");if(!this.spanId)throw Error("spanId must be nonempty string");if(!this.rootSpanId)throw Error("rootSpanId must be nonempty string")}},M=class e{toStr(){let e=[],{bytes:t,isUUID:r}=this.rowIds?R(this.rowIds.rowId):{bytes:p.from(""),isUUID:!1};e.push(p.from([1,this.objectType,this.rowIds?1:0,r?1:0]));let{bytes:n,isUUID:i}=R(this.objectId);if(!i)throw Error("object_id component must be a valid UUID");if(e.push(n),this.rowIds){let{bytes:r,isUUID:n}=R(this.rowIds.spanId);if(!n)throw Error("span_id component must be a valid UUID");let{bytes:i,isUUID:a}=R(this.rowIds.rootSpanId);if(!a)throw Error("root_span_id component must be a valid UUID");e.push(r,i,t)}return p.concat(e).toString("base64")}static fromStr(t){try{let r=p.from(t,"base64");if(1!==r[0])throw Error();let n=P.parse(r[1]);if(![0,1].includes(r[2])||![0,1].includes(r[3]))throw Error();let i=1==r[2],a=1==r[3],o=l.Z(r.subarray(4,20)),s=(()=>{if(!i)return;let e=l.Z(r.subarray(20,36)),t=l.Z(r.subarray(36,52)),n=a?l.Z(r.subarray(52)):r.subarray(52).toString("utf-8");return new q({rowId:n,spanId:e,rootSpanId:t})})();return new e({objectType:n,objectId:o,rowIds:s})}catch(e){throw Error("SpanComponents string is not properly encoded. This may be due to a version mismatch between the SDK library used to export the span and the library used to decode it. Please make sure you are using the same SDK version across the board")}}objectIdFields(){switch(this.objectType){case 1:return{experiment_id:this.objectId};case 2:return{project_id:this.objectId,log_id:"g"};default:throw Error("Impossible")}}toObject(){var e;return{objectType:this.objectType,objectId:this.objectId,rowIds:null==(e=this.rowIds)?void 0:e.toObject()}}constructor(e){this.objectType=e.objectType,this.objectId=e.objectId,this.rowIds=e.rowIds}};function C(e){try{let t=s.Z(e);if(16!==t.length)throw Error();return{bytes:p.from(t),isUUID:!0}}catch(t){return{bytes:p.from(e,"utf-8"),isUUID:!1}}}var D="SpanComponents string is not properly encoded. This library only supports encoding versions up to ".concat(2,". Please make sure the SDK library used to decode the SpanComponents is at least as new as any library used to encode it."),F=((i=F||{})[i.EXPERIMENT=1]="EXPERIMENT",i[i.PROJECT_LOGS=2]="PROJECT_LOGS",i),B=c.z.nativeEnum(F),V=class{toObject(){return{rowId:this.rowId,spanId:this.spanId,rootSpanId:this.rootSpanId}}constructor(e){if(this.rowId=e.rowId,this.spanId=e.spanId,this.rootSpanId=e.rootSpanId,!this.rowId)throw Error("rowId must be nonempty string");if(!this.spanId)throw Error("spanId must be nonempty string");if(!this.rootSpanId)throw Error("rootSpanId must be nonempty string")}},J=class e{toStr(){let e=[],{bytes:t,isUUID:r}=this.rowIds?C(this.rowIds.rowId):{bytes:p.from(""),isUUID:!1};if(e.push(p.from([2,this.objectType,this.objectId?1:0,this.computeObjectMetadataArgs?1:0,this.rowIds?1:0,r?1:0])),this.objectId){let{bytes:t,isUUID:r}=C(this.objectId);if(!r)throw Error("object_id component must be a valid UUID");e.push(t)}if(this.computeObjectMetadataArgs){let t=p.from(JSON.stringify(this.computeObjectMetadataArgs),"utf-8"),r=p.alloc(4);r.writeInt32BE(t.length),e.push(r,t)}if(this.rowIds){let{bytes:r,isUUID:n}=C(this.rowIds.spanId);if(!n)throw Error("span_id component must be a valid UUID");let{bytes:i,isUUID:a}=C(this.rowIds.rootSpanId);if(!a)throw Error("root_span_id component must be a valid UUID");e.push(r,i,t)}return p.concat(e).toString("base64")}static fromStr(t){try{let r,n;let i=p.from(t,"base64");if(i[0]<2){let r=M.fromStr(t);return new e({objectType:B.parse(r.objectType),objectId:r.objectId,rowIds:r.rowIds?new V({rowId:r.rowIds.rowId,spanId:r.rowIds.spanId,rootSpanId:r.rowIds.rootSpanId}):void 0})}if(2!==i[0])throw Error();let a=B.parse(i[1]);for(let e=2;e<6;++e)if(![0,1].includes(i[e]))throw Error();let o=1==i[2],s=1==i[3],c=1==i[4],u=1==i[5],d=6;if(o){let e=d+16;n=l.Z(i.subarray(d,e)),d=e}if(s){let e=d+4,t=i.readInt32BE(d);e=(d=e)+t,r=JSON.parse(i.subarray(d,e).toString("utf-8")),d=e}let h=(()=>{if(!c)return;let e=d+16,t=l.Z(i.subarray(d,e));e=(d=e)+16;let r=l.Z(i.subarray(d,e));d=e;let n=u?l.Z(i.subarray(d)):i.subarray(d).toString("utf-8");return new V({rowId:n,spanId:t,rootSpanId:r})})();return new e({objectType:a,objectId:n,computeObjectMetadataArgs:r,rowIds:h})}catch(e){throw Error(D)}}objectIdFields(){if(!this.objectId)throw Error("Impossible: cannot invoke `object_id_fields` unless SpanComponentsV2 is initialized with an `object_id`");switch(this.objectType){case 1:return{experiment_id:this.objectId};case 2:return{project_id:this.objectId,log_id:"g"};default:throw Error("Impossible")}}toObject(){var e;return{objectType:this.objectType,objectId:this.objectId,computeObjectMetadataArgs:this.computeObjectMetadataArgs,rowIds:null==(e=this.rowIds)?void 0:e.toObject()}}constructor(e){if(this.objectType=e.objectType,this.objectId=e.objectId,this.computeObjectMetadataArgs=e.computeObjectMetadataArgs,this.rowIds=e.rowIds,!(this.objectId||this.computeObjectMetadataArgs))throw Error("Must provide either objectId or computeObjectMetadataArgs")}},Q=["llm","score","function","eval","task","tool"],G=((a=G||{}).LLM="llm",a.SCORE="score",a.FUNCTION="function",a.EVAL="eval",a.TASK="task",a.TOOL="tool",a);(0,u.extendZodWithOpenApi)(c.z);var $=c.z.union([c.z.string(),c.z.number(),c.z.boolean(),c.z.null()]),Y=c.z.lazy(()=>c.z.union([$,c.z.array(Y),c.z.record(Y)])),W=c.z.string().transform((e,t)=>{let r=new Date(e);return isNaN(r.getTime())?(t.addIssue({code:c.z.ZodIssueCode.invalid_string,validation:"datetime",message:"Invalid datetime"}),c.z.NEVER):r.toISOString()}).openapi({format:"date-time"});function H(e){return"project"===e?"project_logs":e}function Z(e){return H(e).replace("_"," ")}c.z.enum(["project","experiment","dataset","prompt","prompt_session","role","group","acl","user","project_score","project_tag","function","view","organization","api_key"]),c.z.enum(["project","experiment","dataset","prompt","function","prompt_session"]),(0,u.extendZodWithOpenApi)(c.z);var X=c.z.enum(["default","stainless"]).parse(void 0===d?"default":(null==(o=null==d?void 0:d.env)?void 0:o.BRAINTRUST_TYPESPECS_MODE)||"default"),K={default:{any:c.z.any(),literalTrue:c.z.literal(!0),literalFalse:c.z.literal(!1)},stainless:{any:c.z.any().openapi({"x-stainless-any":!0}),literalTrue:c.z.boolean(),literalFalse:c.z.boolean()}}[X],ee=c.z.enum(["system","user","assistant","function","tool","model"]),et=c.z.object({content:c.z.string().default(""),role:c.z.literal("system"),name:c.z.string().optional()}),er=c.z.object({text:c.z.string().default(""),type:c.z.literal("text")}),en=c.z.object({url:c.z.string(),detail:c.z.union([c.z.literal("auto"),c.z.literal("low"),c.z.literal("high")]).optional()}),ei=c.z.object({image_url:en,type:c.z.literal("image_url")}),ea=c.z.union([er,ei]),eo=c.z.union([c.z.string().default(""),c.z.array(ea)]),es=c.z.object({content:eo,role:c.z.literal("user"),name:c.z.string().optional()}),el=c.z.object({arguments:c.z.string(),name:c.z.string()}),ec=c.z.object({arguments:c.z.string(),name:c.z.string()}),eu=c.z.object({content:c.z.string().default(""),role:c.z.literal("tool"),tool_call_id:c.z.string().default("")}),ep=c.z.object({content:c.z.string().default(""),name:c.z.string(),role:c.z.literal("function")}),ed=c.z.object({id:c.z.string(),function:ec,type:c.z.literal("function")}),eh=c.z.object({role:c.z.literal("assistant"),content:c.z.string().nullish(),function_call:el.optional(),name:c.z.string().optional(),tool_calls:c.z.array(ed).optional()}),em=c.z.object({role:ee.exclude(["system","user","assistant","tool","function"]),content:c.z.string().nullish()}),ef=c.z.union([et,es,eh,eu,ep]),ez=c.z.union([ef,em]),eb=c.z.record(c.z.unknown()),ey=c.z.object({name:c.z.string(),description:c.z.string().optional(),parameters:eb.optional()}),eg=c.z.object({function:ey,type:c.z.literal("function")});c.z.array(eg);var e_=c.z.union([c.z.object({type:c.z.literal("completion"),content:c.z.string()}),c.z.object({type:c.z.literal("chat"),messages:c.z.array(ez),tools:c.z.string().optional()})]),ev=c.z.object({use_cache:c.z.boolean().optional()});Object.keys(ev.shape);var ej=c.z.object({temperature:c.z.number().optional(),top_p:c.z.number().optional(),max_tokens:c.z.number().optional(),frequency_penalty:c.z.number().optional(),presence_penalty:c.z.number().optional(),response_format:c.z.object({type:c.z.literal("json_object")}).nullish(),tool_choice:c.z.union([c.z.literal("auto"),c.z.literal("none"),c.z.object({type:c.z.literal("function"),function:c.z.object({name:c.z.string()})})]).optional(),function_call:c.z.union([c.z.literal("auto"),c.z.literal("none"),c.z.object({name:c.z.string()})]).optional(),n:c.z.number().optional(),stop:c.z.array(c.z.string()).optional()}),ex=c.z.object({max_tokens:c.z.number(),temperature:c.z.number(),top_p:c.z.number().optional(),top_k:c.z.number().optional(),stop_sequences:c.z.array(c.z.string()).optional(),max_tokens_to_sample:c.z.number().optional().describe("This is a legacy parameter that should not be used.")}),ek=c.z.object({temperature:c.z.number().optional(),maxOutputTokens:c.z.number().optional(),topP:c.z.number().optional(),topK:c.z.number().optional()}),eO=c.z.object({temperature:c.z.number().optional(),topK:c.z.number().optional()}),ew=c.z.object({}),eT=c.z.union([ev.merge(ej).passthrough(),ev.merge(ex).passthrough(),ev.merge(ek).passthrough(),ev.merge(eO).passthrough(),ev.merge(ew).passthrough()]);ej.merge(ex).merge(ek).merge(ev);var eE=c.z.object({model:c.z.string().optional(),params:eT.optional(),position:c.z.string().optional()}),eI=c.z.object({prompt:e_.nullish(),options:eE.nullish(),origin:c.z.object({prompt_id:c.z.string().optional(),project_id:c.z.string().optional(),prompt_version:c.z.string().optional()}).nullish()}).openapi("PromptData"),eA=c.z.enum(["projects","logs","experiments","datasets","prompts","playgrounds","experiment","dataset"]).describe("Type of table that the view corresponds to."),eS=c.z.object({filter:c.z.array(K.any).nullish(),tag:c.z.array(K.any).nullish(),match:c.z.array(K.any).nullish(),sort:c.z.array(K.any).nullish()}).strip().openapi("ViewDataSearch"),eN=c.z.object({search:eS.nullish()}).strip().openapi("ViewData"),eL=c.z.object({columnVisibility:c.z.record(c.z.boolean()).nullish(),columnOrder:c.z.array(c.z.string()).nullish(),columnSizing:c.z.record(c.z.number()).nullish()}).strip().openapi("ViewOptions");function eR(e,t){let r="Name of the ".concat(e);return(null==t?void 0:t.uniqueName)&&(r+=". Within a project, ".concat(e," names are unique")),c.z.object({id:c.z.string().uuid().describe("Unique identifier for the ".concat(e)),project_id:c.z.string().uuid().describe("Unique identifier for the project that the ".concat(e," belongs under")),name:c.z.string().describe(r),description:c.z.string().nullish().describe("Textual description of the ".concat(e)),created:W.nullish().describe("Date of ".concat(e," creation")),deleted_at:W.nullish().describe("Date of ".concat(e," deletion, or null if the ").concat(e," is still active")),user_id:c.z.string().uuid().nullish().describe("Identifies the user who created the ".concat(e)),metadata:c.z.record(K.any).nullish().describe("User-controlled metadata about the ".concat(e))})}(0,u.extendZodWithOpenApi)(c.z);var eU=eR("user"),eP=c.z.object({id:eU.shape.id,given_name:c.z.string().nullish().describe("Given name of the user"),family_name:c.z.string().nullish().describe("Family name of the user"),email:c.z.string().nullish().describe("The user's email"),avatar_url:c.z.string().nullish().describe("URL of the user's Avatar image"),created:eU.shape.created}).openapi("User"),eq=eR("organization"),eM=c.z.object({id:eq.shape.id,name:eq.shape.name,api_url:c.z.string().nullish(),proxy_url:c.z.string().nullish(),realtime_url:c.z.string().nullish(),created:eq.shape.created}).openapi("Organization"),eC=c.z.object({window_size_days:c.z.number().int().positive(),max_value:c.z.number().nonnegative()}).openapi("MaxOverWindow");c.z.object({org_id:eM.shape.id,forbid_toggle_experiment_public_to_private:c.z.boolean().nullish(),num_private_experiment_row_actions:eC.nullish(),forbid_insert_datasets:c.z.boolean().nullish(),forbid_insert_prompt_sessions:c.z.boolean().nullish(),forbid_access_sql_explorer:c.z.boolean().nullish(),num_production_log_row_actions:eC.nullish(),num_dataset_row_actions:eC.nullish()}).openapi("Resources"),c.z.object({org_id:eM.shape.id,user_id:eP.shape.id}).openapi("Member");var eD=eR("org secrets");c.z.object({id:eD.shape.id,created:eD.shape.created,key_id:c.z.string().uuid(),org_id:eM.shape.id,name:eD.shape.name,secret:c.z.string().nullish(),type:c.z.string().nullish(),metadata:K.any}).openapi("OrgSecrets");var eF=eR("api key"),eB=c.z.object({id:eF.shape.id,created:eF.shape.created,name:eF.shape.name,preview_name:c.z.string(),user_id:eP.shape.id.nullish(),org_id:eM.shape.id.nullish()}).openapi("ApiKey"),eV=c.z.object({comparison_key:c.z.string().nullish().describe("The key used to join two experiments (defaults to `input`).")}),eJ=eR("project"),eQ=c.z.object({id:eJ.shape.id,org_id:c.z.string().uuid().describe("Unique id for the organization that the project belongs under"),name:eJ.shape.name,created:eJ.shape.created,deleted_at:eJ.shape.deleted_at,user_id:eJ.shape.user_id,settings:eV.nullish()}).openapi("Project"),eG=eR("dataset",{uniqueName:!0}),e$=c.z.object({id:eG.shape.id,project_id:eG.shape.project_id.nullish(),name:eG.shape.name,description:eG.shape.description,created:eG.shape.created,deleted_at:eG.shape.deleted_at,user_id:eG.shape.user_id,metadata:eG.shape.metadata}).openapi("Dataset"),eY=c.z.enum(["node"]);c.z.object({runtime:eY,version:c.z.string()});var eW=eR("prompt"),eH=c.z.object({id:eW.shape.id,_xact_id:c.z.string().describe("The transaction id of an event is unique to the network operation that processed the event insertion. Transaction ids are monotonically increasing over time and can be used to retrieve a versioned snapshot of the prompt (see the `version` parameter)"),project_id:eW.shape.project_id,log_id:c.z.literal("p").describe("A literal 'p' which identifies the object as a project prompt"),org_id:eM.shape.id,name:eW.shape.name,slug:c.z.string().describe("Unique identifier for the prompt"),description:eW.shape.description,created:eW.shape.created,prompt_data:eI.nullish().describe("The prompt, model, and its parameters"),tags:c.z.array(c.z.string()).nullish().describe("A list of tags for the prompt"),metadata:eW.shape.metadata}),eZ=eH.openapi("Prompt"),eX=c.z.object({runtime_context:c.z.object({runtime:eY,version:c.z.string()}),location:c.z.object({type:c.z.literal("experiment"),eval_name:c.z.string(),position:c.z.union([c.z.literal("task"),c.z.object({score:c.z.number()})])}),bundle_id:c.z.string()}),eK=c.z.union([c.z.object({type:c.z.literal("prompt")}),c.z.object({type:c.z.literal("code"),data:eX}),c.z.object({type:c.z.literal("global"),name:c.z.string()})]),e0=eH.merge(c.z.object({function_data:eK})).openapi("Function"),e1=c.z.object({commit:c.z.string().nullish().describe("SHA of most recent commit"),branch:c.z.string().nullish().describe("Name of the branch the most recent commit belongs to"),tag:c.z.string().nullish().describe("Name of the tag on the most recent commit"),dirty:c.z.boolean().nullish().describe("Whether or not the repo had uncommitted changes when snapshotted"),author_name:c.z.string().nullish().describe("Name of the author of the most recent commit"),author_email:c.z.string().nullish().describe("Email of the author of the most recent commit"),commit_message:c.z.string().nullish().describe("Most recent commit message"),commit_time:c.z.string().nullish().describe("Time of the most recent commit"),git_diff:c.z.string().nullish().describe("If the repo was dirty when run, this includes the diff between the current state of the repo and the most recent commit.")}).describe("Metadata about the state of the repo when the experiment was created").openapi("RepoInfo"),e2=eR("experiment",{uniqueName:!0}),e6=c.z.object({id:e2.shape.id,project_id:e2.shape.project_id,name:e2.shape.name,description:e2.shape.description,created:e2.shape.created,repo_info:e1.nullish(),commit:c.z.string().nullish().describe("Commit, taken directly from `repo_info.commit`"),base_exp_id:c.z.string().uuid().nullish().describe("Id of default base experiment to compare against when viewing this experiment"),deleted_at:e2.shape.deleted_at,dataset_id:c.z.string().uuid().nullish().describe("Identifier of the linked dataset, or null if the experiment is not linked to a dataset"),dataset_version:c.z.string().nullish().describe("Version number of the linked dataset the experiment was run against. This can be used to reproduce the experiment after the dataset has been modified."),public:c.z.boolean().describe("Whether or not the experiment is public. Public experiments can be viewed by anybody inside or outside the organization"),user_id:e2.shape.user_id,metadata:e2.shape.metadata}).openapi("Experiment"),e4=eR("promptSession",{uniqueName:!0});c.z.object({id:e4.shape.id,name:e4.shape.name,description:e4.shape.description,created:e4.shape.created,deleted_at:e4.shape.deleted_at,user_id:e4.shape.user_id,project_id:e4.shape.project_id,org_id:eM.shape.id.nullish().describe("This field is deprecated and will be removed in a future revision")}).openapi("PromptSession");var e3=c.z.enum(["create","read","update","delete","create_acls","read_acls","update_acls","delete_acls"]).describe("Each permission permits a certain type of operation on an object in the system\n\nPermissions can be assigned to to objects on an individual basis, or grouped into roles"),e8=c.z.enum(["organization","project","experiment","dataset","prompt","prompt_session","group","role","org_member","project_log","org_project"]).describe("The object type that the ACL applies to"),e9=eR("role"),e5=c.z.object({id:e9.shape.id,org_id:c.z.string().uuid().nullish().describe("Unique id for the organization that the role belongs under\n\nA null org_id indicates a system role, which may be assigned to anybody and inherited by any other role, but cannot be edited.\n\nIt is forbidden to change the org after creating a role"),user_id:e9.shape.user_id,created:e9.shape.created,name:e9.shape.name,description:e9.shape.description,deleted_at:e9.shape.deleted_at,member_permissions:c.z.array(c.z.object({permission:e3,restrict_object_type:e8.nullish()})).nullish().describe("(permission, restrict_object_type) tuples which belong to this role"),member_roles:c.z.array(c.z.string().uuid()).nullish().describe("Ids of the roles this role inherits from\n\nAn inheriting role has all the permissions contained in its member roles, as well as all of their inherited permissions")}).describe("A role is a collection of permissions which can be granted as part of an ACL\n\nRoles can consist of individual permissions, as well as a set of roles they inherit from").openapi("Role"),e7=eR("group"),te=c.z.object({id:e7.shape.id,org_id:c.z.string().uuid().describe("Unique id for the organization that the group belongs under\n\nIt is forbidden to change the org after creating a group"),user_id:e7.shape.user_id,created:e7.shape.created,name:e7.shape.name,description:e7.shape.description,deleted_at:e7.shape.deleted_at,member_users:c.z.array(c.z.string().uuid()).nullish().describe("Ids of users which belong to this group"),member_groups:c.z.array(c.z.string().uuid()).nullish().describe("Ids of the groups this group inherits from\n\nAn inheriting group has all the users contained in its member groups, as well as all of their inherited users")}).describe("A group is a collection of users which can be assigned an ACL\n\nGroups can consist of individual users, as well as a set of groups they inherit from").openapi("Group"),tt=c.z.enum(["slider","categorical","weighted","minimum"]).describe("The type of the configured score"),tr=c.z.object({name:c.z.string().describe("Name of the category"),value:c.z.number().describe("Numerical value of the category. Must be between 0 and 1, inclusive")}).describe("For categorical-type project scores, defines a single category").openapi("ProjectScoreCategory"),tn=eR("project score"),ti=c.z.object({id:tn.shape.id,project_id:tn.shape.project_id,user_id:tn.shape.user_id.unwrap().unwrap(),created:tn.shape.created,name:tn.shape.name,description:tn.shape.description,score_type:tt,categories:c.z.union([tr.array().describe("For categorical-type project scores, the list of all categories"),c.z.record(c.z.number()).describe("For weighted-type project scores, the weights of each score"),c.z.array(c.z.string()).describe("For minimum-type project scores, the list of included scores")]).nullish(),config:c.z.object({multi_select:c.z.boolean().nullish(),destination:c.z.literal("expected").nullish()}).nullish(),position:c.z.string().nullish().describe("An optional LexoRank-based string that sets the sort position for the score in the UI")}).describe("A project score is a user-configured score, which can be manually-labeled through the UI").openapi("ProjectScore"),ta=eR("project tag"),to=c.z.object({id:ta.shape.id,project_id:ta.shape.project_id,user_id:ta.shape.user_id.unwrap().unwrap(),created:ta.shape.created,name:ta.shape.name,description:ta.shape.description,color:c.z.string().nullish().describe("Color of the tag for the UI")}).describe("A project tag is a user-configured tag for tracking and filtering your experiments, logs, and other data").openapi("ProjectTag"),ts=eR("view"),tl=c.z.object({id:ts.shape.id,object_type:e8,object_id:c.z.string().uuid().describe("The id of the object the view applies to"),view_type:eA,name:ts.shape.name,created:ts.shape.created,view_data:eN.nullish().describe("The view definition"),options:eL.nullish().describe("Options for the view in the app"),user_id:ts.shape.user_id,deleted_at:e9.shape.deleted_at}).openapi("View"),tc=eR("acl"),tu=c.z.object({id:tc.shape.id,object_type:e8,object_id:c.z.string().uuid().describe("The id of the object the ACL applies to"),user_id:c.z.string().uuid().nullish().describe("Id of the user the ACL applies to. Exactly one of `user_id` and `group_id` will be provided"),group_id:c.z.string().uuid().nullish().describe("Id of the group the ACL applies to. Exactly one of `user_id` and `group_id` will be provided"),permission:e3.nullish().describe("Permission the ACL grants. Exactly one of `permission` and `role_id` will be provided"),restrict_object_type:e8.nullish().describe("When setting a permission directly, optionally restricts the permission grant to just the specified object type. Cannot be set alongside a `role_id`."),role_id:c.z.string().uuid().nullish().describe("Id of the role the ACL grants. Exactly one of `permission` and `role_id` will be provided"),_object_org_id:c.z.string().uuid().describe("The organization the ACL's referred object belongs to"),created:tc.shape.created}).describe("An ACL grants a certain permission or role to a certain user or group on an object.\n\nACLs are inherited across the object hierarchy. So for example, if a user has read permissions on a project, they will also have read permissions on any experiment, dataset, etc. created within that project.\n\nTo restrict a grant to a particular sub-object, you may specify `restrict_object_type` in the ACL, as part of a direct permission grant or as part of a role.").openapi("Acl");function tp(e){return c.z.object({org_name:c.z.string().nullish().describe("For nearly all users, this parameter should be unnecessary. But in the rare case that your API key belongs to multiple organizations, you may specify the name of the organization the ".concat(e," belongs in."))})}c.z.number().int().nonnegative().describe("Limit the number of objects to return"),c.z.string().uuid().describe("Pagination cursor id.\n\nFor example, if the final item in the last page you fetched had an id of `foo`, pass `starting_after=foo` to fetch the next page. Note: you may only pass one of `starting_after` and `ending_before`").openapi("StartingAfter"),c.z.string().uuid().describe("Pagination cursor id.\n\nFor example, if the initial item in the last page you fetched had an id of `foo`, pass `ending_before=foo` to fetch the previous page. Note: you may only pass one of `starting_after` and `ending_before`").openapi("EndingBefore");var td=tp("project");c.z.object({name:eQ.shape.name,org_name:td.shape.org_name}).openapi("CreateProject"),c.z.object({name:eQ.shape.name.nullish(),settings:eQ.shape.settings.describe("Project settings. Patch operations replace all settings, so make sure you include all settings you want to keep.").nullish()}).openapi("PatchProject"),c.z.object({project_id:e6.shape.project_id,name:e6.shape.name.nullish(),description:e6.shape.description,repo_info:e6.shape.repo_info,base_exp_id:e6.shape.base_exp_id,dataset_id:e6.shape.dataset_id,dataset_version:e6.shape.dataset_version,public:e6.shape.public.nullish(),metadata:e6.shape.metadata,ensure_new:c.z.boolean().nullish().describe("Normally, creating an experiment with the same name as an existing experiment will return the existing one un-modified. But if `ensure_new` is true, registration will generate a new experiment with a unique name in case of a conflict.")}).openapi("CreateExperiment").omit({project_id:!0,ensure_new:!0}).openapi("PatchExperiment"),c.z.object({project_id:e$.shape.project_id,name:e$.shape.name,description:e$.shape.description}).openapi("CreateDataset"),c.z.object({name:e$.shape.name.nullish(),description:e$.shape.description,metadata:e$.shape.metadata}).openapi("PatchDataset"),eZ.omit({id:!0,_xact_id:!0,org_id:!0,log_id:!0,created:!0,metadata:!0}).openapi("CreatePrompt"),e0.omit({id:!0,_xact_id:!0,org_id:!0,log_id:!0,created:!0,metadata:!0}).openapi("CreateFunction"),c.z.object({name:eZ.shape.name.nullish(),description:eZ.shape.description.nullish(),prompt_data:eZ.shape.prompt_data.nullish(),tags:eZ.shape.tags.nullish()}).openapi("PatchPrompt"),c.z.object({name:e0.shape.name.nullish(),description:e0.shape.description.nullish(),prompt_data:e0.shape.prompt_data.nullish(),function_data:e0.shape.function_data.nullish(),tags:e0.shape.tags.nullish()}).openapi("PatchFunction");var th=tp("role"),tm=c.z.object({name:e5.shape.name,description:e5.shape.description,member_permissions:e5.shape.member_permissions,member_roles:e5.shape.member_roles,org_name:th.shape.org_name}).openapi("CreateRole");tm.omit({name:!0,org_name:!0,member_permissions:!0,member_roles:!0}).merge(c.z.object({name:tm.shape.name.nullish(),add_member_permissions:e5.shape.member_permissions.nullish().describe("A list of permissions to add to the role"),remove_member_permissions:e5.shape.member_permissions.nullish().describe("A list of permissions to remove from the role"),add_member_roles:e5.shape.member_roles.nullish().describe("A list of role IDs to add to the role's inheriting-from set"),remove_member_roles:e5.shape.member_roles.nullish().describe("A list of role IDs to remove from the role's inheriting-from set")})).openapi("PatchRole");var tf=tp("group"),tz=c.z.object({name:te.shape.name,description:te.shape.description,member_users:te.shape.member_users,member_groups:te.shape.member_groups,org_name:tf.shape.org_name}).openapi("CreateGroup");tz.omit({name:!0,org_name:!0,member_users:!0,member_groups:!0}).merge(c.z.object({name:tz.shape.name.nullish(),add_member_users:te.shape.member_users.nullish().describe("A list of user IDs to add to the group"),remove_member_users:te.shape.member_users.nullish().describe("A list of user IDs to remove from the group"),add_member_groups:te.shape.member_groups.nullish().describe("A list of group IDs to add to the group's inheriting-from set"),remove_member_groups:te.shape.member_groups.nullish().describe("A list of group IDs to remove from the group's inheriting-from set")})).openapi("PatchGroup"),tu.omit({id:!0,created:!0,_object_org_id:!0}).openapi("CreateAcl"),c.z.object({project_id:ti.shape.project_id,name:ti.shape.name,description:ti.shape.description,score_type:ti.shape.score_type,categories:ti.shape.categories}).openapi("CreateProjectScore"),c.z.object({name:ti.shape.name.nullish(),description:ti.shape.description,score_type:ti.shape.score_type.nullish(),categories:ti.shape.categories}).openapi("PatchProjectScore"),c.z.object({project_id:to.shape.project_id,name:to.shape.name,description:to.shape.description,color:to.shape.color}).openapi("CreateProjectTag"),c.z.object({name:to.shape.name.nullish(),description:to.shape.description,color:to.shape.color}).openapi("PatchProjectTag"),tl.omit({id:!0,created:!0}).openapi("CreateView"),c.z.object({object_type:tl.shape.object_type,object_id:tl.shape.object_id,view_type:tl.shape.view_type.nullish(),name:tl.shape.name.nullish(),view_data:tl.shape.view_data,options:tl.shape.options,user_id:tl.shape.user_id}).openapi("PatchView"),c.z.object({object_type:tl.shape.object_type,object_id:tl.shape.object_id}).openapi("DeleteView"),c.z.object({name:eM.shape.name.nullish(),api_url:eM.shape.api_url.nullish(),proxy_url:eM.shape.proxy_url.nullish(),realtime_url:eM.shape.realtime_url.nullish()}).openapi("PatchOrganization");var tb=tp("API key");c.z.object({name:c.z.string().describe("Name of the api key. Does not have to be unique"),org_name:tb.shape.org_name}),eB.merge(c.z.object({key:c.z.string().describe("The raw API key. It will only be exposed this one time")})).openapi("CreateApiKeyOutput"),(0,u.extendZodWithOpenApi)(c.z);var ty=c.z.enum(g);function tg(e){let t=Z(e);return c.z.object({id:c.z.string().describe("A unique identifier for the ".concat(t," event. If you don't provide one, BrainTrust will generate one for you")),[h]:c.z.string().describe("The transaction id of an event is unique to the network operation that processed the event insertion. Transaction ids are monotonically increasing over time and can be used to retrieve a versioned snapshot of the ".concat(t," (see the `version` parameter)")),created:W.describe("The timestamp the ".concat(t," event was created")),input:K.any,output:K.any,expected:K.any,tags:c.z.array(c.z.string()).nullish().describe("A list of tags to log"),scores:c.z.record(c.z.number().min(0).max(1).nullish()).nullish(),metadata:c.z.record(K.any).nullish().describe("A dictionary with additional data about the test example, model outputs, or just about anything else that's relevant, that you can use to help find and analyze examples later. For example, you could log the `prompt`, example's `id`, or anything else that would be useful to slice/dice later. The values in `metadata` can be any JSON-serializable type, but its keys must be strings"),metrics:c.z.object({start:c.z.number().nullish().describe("A unix timestamp recording when the section of code which produced the ".concat(t," event started")),end:c.z.number().nullish().describe("A unix timestamp recording when the section of code which produced the ".concat(t," event finished")),prompt_tokens:c.z.number().int().nullish().describe("The number of tokens in the prompt used to generate the ".concat(t," event (only set if this is an LLM span)")),completion_tokens:c.z.number().int().nullish().describe("The number of tokens in the completion generated by the model (only set if this is an LLM span)"),tokens:c.z.number().int().nullish().describe("The total number of tokens in the input and output of the ".concat(t," event."))}).catchall(K.any).nullish().describe("Metrics are numerical measurements tracking the execution of the code that produced the ".concat(t,' event. Use "start" and "end" to track the time span over which the ').concat(t," event was produced")),context:c.z.object({caller_functionname:c.z.string().nullish().describe("The function in code which created the ".concat(t," event")),caller_filename:c.z.string().nullish().describe("Name of the file in code where the ".concat(t," event was created")),caller_lineno:c.z.number().int().nullish().describe("Line of code where the ".concat(t," event was created"))}).catchall(K.any).nullish().describe("Context is additional information about the code that produced the ".concat(t," event. It is essentially the textual counterpart to `metrics`. Use the `caller_*` attributes to track the location in code which produced the ").concat(t," event")),span_id:c.z.string().uuid().describe("A unique identifier used to link different ".concat(t," events together as part of a full trace. See the [tracing guide](https://www.braintrust.dev/docs/guides/tracing) for full details on tracing")),span_parents:c.z.string().array().nullish().describe("An array of the parent `span_ids` of this ".concat(t," event. This should be empty for the root span of a trace, and should most often contain just one parent element for subspans")),root_span_id:c.z.string().uuid().describe("The `span_id` of the root of the trace this ".concat(t," event belongs to")),span_attributes:c.z.object({name:c.z.string().nullish().describe("Name of the span, for display purposes only"),type:c.z.enum(Q).nullish().describe("Type of the span, for display purposes only")}).catchall(K.any).nullish().describe("Human-identifying attributes of the span, such as name, type, etc."),[m]:c.z.boolean().nullish().describe("Pass `".concat(m,"=true` to mark the ").concat(t," event deleted. Deleted events will not show up in subsequent fetches for this ").concat(t))})}function t_(e){let t=H(e),r=Z(e);return c.z.object({id:c.z.string().describe("The id of the ".concat(r," event to log feedback for. This is the row `id` returned by `POST /v1/").concat(t,"/{").concat(e,"_id}/insert`")),scores:c.z.record(c.z.number().min(0).max(1).nullish()).nullish().describe("A dictionary of numeric values (between 0 and 1) to log. These scores will be merged into the existing scores for the ".concat(r," event")),expected:K.any.describe("The ground truth value (an arbitrary, JSON serializable object) that you'd compare to `output` to determine if your `output` value is correct or not"),tags:c.z.array(c.z.string()).nullish().describe("A list of tags to log"),comment:c.z.string().nullish().describe("An optional comment string to log about the ".concat(r," event")),metadata:c.z.record(K.any).nullish().describe("A dictionary with additional data about the feedback. If you have a `user_id`, you can log it here and access it in the Braintrust UI."),source:ty.nullish().describe('The source of the feedback. Must be one of "external" (default), "app", or "api"')})}var tv=c.z.number().int().nonnegative().describe(["limit the number of traces fetched","Fetch queries may be paginated if the total result size is expected to be large (e.g. project_logs which accumulate over a long time). Note that fetch queries only support pagination in descending time order (from latest to earliest `".concat(h,"`. Furthermore, later pages may return rows which showed up in earlier pages, except with an earlier `").concat(h,"`. This happens because pagination occurs over the whole version history of the event log. You will most likely want to exclude any such duplicate, outdated rows (by `id`) from your combined result set."),"The `limit` parameter controls the number of full traces to return. So you may end up with more individual rows than the specified limit if you are fetching events containing traces."].join("\n\n")),tj=["DEPRECATION NOTICE: The manually-constructed pagination cursor is deprecated in favor of the explicit 'cursor' returned by object fetch requests. Please prefer the 'cursor' argument going forwards.","Together, `max_xact_id` and `max_root_span_id` form a pagination cursor","Since a paginated fetch query returns results in order from latest to earliest, the cursor for the next page can be found as the row with the minimum (earliest) value of the tuple `(".concat(h,", root_span_id)`. See the documentation of `limit` for an overview of paginating fetch queries.")].join("\n\n"),tx=c.z.string().describe(tj),tk=c.z.string().describe(tj),tO=c.z.string().describe("An opaque string to be used as a cursor for the next page of results, in order from latest to earliest.\n\nThe string can be obtained directly from the `cursor` property of the previous fetch query"),tw=c.z.string().describe("Retrieve a snapshot of events from a past time\n\nThe version id is essentially a filter on the latest event transaction id. You can use the `max_xact_id` returned by a past fetch as the version to reproduce that exact fetch."),tT=c.z.object({type:c.z.literal("path_lookup").describe("Denotes the type of filter as a path-lookup filter"),path:c.z.string().array().describe('List of fields describing the path to the value to be checked against. For instance, if you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `path=["input", "a", "b", "c"]`'),value:K.any.describe('The value to compare equality-wise against the event value at the specified `path`. The value must be a "primitive", that is, any JSON-serializable object except for objects and arrays. For instance, if you wish to filter on the value of "input.a.b.c" in the object `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `value="hello"`')}).describe('A path-lookup filter describes an equality comparison against a specific sub-field in the event row. For instance, if you wish to filter on the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `path=["input", "a", "b", "c"]` and `value="hello"`').openapi("PathLookupFilter"),tE=c.z.object({type:c.z.literal("sql_filter").describe("Denotes the type of filter as a sql-type filter"),expr:c.z.string().describe('A SQL expression in [duckDB syntax](https://duckdb.org/docs/sql/expressions/overview). For instance, if you wish to fuzzy-match the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `expr="input->\'a\'->\'b\'->>\'c\' LIKE \'%el%\'"`.')}).describe('A sql-type filter describes a general filter over an individual row in [duckDB syntax](https://duckdb.org/docs/sql/expressions/overview). For instance, if you wish to fuzzy-match the value of `c` in `{"input": {"a": {"b": {"c": "hello"}}}}`, pass `expr="input->\'a\'->\'b\'->>\'c\' LIKE \'%el%\'"`.').openapi("SQLFilter");c.z.union([tT,tE]).array().describe("A list of filters on the events to fetch. Filters can either be specialized `path=value` expressions or general SQL expressions in [duckDB syntax](https://duckdb.org/docs/sql/expressions/overview). When possible, prefer path-lookup type filters over general SQL-type filters, as they are likely to activate indices in the DB and run faster").openapi("AllFetchEventsFilters");var tI=tT.array().describe("A list of filters on the events to fetch. Currently, only path-lookup type filters are supported, but we may add more in the future").openapi("FetchEventsFilters");function tA(e,t){let r=x(H(e),"_").replace("_","");return c.z.object({events:t.array().describe("A list of fetched events"),cursor:c.z.string().nullish().describe("Pagination cursor\n\nPass this string directly as the `cursor` param to your next fetch request to get the next page of results. Not provided if the returned result set is empty.")}).openapi("Fetch".concat(r,"EventsResponse"))}c.z.object({limit:tv.nullish(),cursor:tO.nullish(),max_xact_id:tx.nullish(),max_root_span_id:tk.nullish(),filters:tI.nullish(),version:tw.nullish()}).openapi("FetchEventsRequest");var tS=tg("experiment"),tN=c.z.object({id:tS.shape.id,dataset_record_id:c.z.string().nullish().describe("If the experiment is associated to a dataset, this is the event-level dataset id this experiment event is tied to"),[h]:tS.shape[h],created:tS.shape.created,project_id:e6.shape.project_id,experiment_id:e6.shape.id,input:tS.shape.input.describe("The arguments that uniquely define a test case (an arbitrary, JSON serializable object). Later on, Braintrust will use the `input` to know whether two test cases are the same between experiments, so they should not contain experiment-specific state. A simple rule of thumb is that if you run the same experiment twice, the `input` should be identical"),output:tS.shape.output.describe("The output of your application, including post-processing (an arbitrary, JSON serializable object), that allows you to determine whether the result is correct or not. For example, in an app that generates SQL queries, the `output` should be the _result_ of the SQL query generated by the model, not the query itself, because there may be multiple valid queries that answer a single question"),expected:tS.shape.expected.describe("The ground truth value (an arbitrary, JSON serializable object) that you'd compare to `output` to determine if your `output` value is correct or not. Braintrust currently does not compare `output` to `expected` for you, since there are so many different ways to do that correctly. Instead, these values are just used to help you navigate your experiments while digging into analyses. However, we may later use these values to re-score outputs or fine-tune your models"),scores:tS.shape.scores.describe("A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety of signals that help you determine how accurate the outputs are compared to what you expect and diagnose failures. For example, a summarization app might have one score that tells you how accurate the summary is, and another that measures the word similarity between the generated and grouth truth summary. The word similarity score could help you determine whether the summarization was covering similar concepts or not. You can use these scores to help you sort, filter, and compare experiments"),metadata:tS.shape.metadata,tags:tS.shape.tags,metrics:tS.shape.metrics,context:tS.shape.context,span_id:tS.shape.span_id,span_parents:tS.shape.span_parents,root_span_id:tS.shape.root_span_id,span_attributes:tS.shape.span_attributes}).openapi("ExperimentEvent"),tL=tg("dataset"),tR=c.z.object({id:tL.shape.id,[h]:tL.shape[h],created:tL.shape.created,project_id:e$.shape.project_id,dataset_id:e$.shape.id,input:tL.shape.input.describe("The argument that uniquely define an input case (an arbitrary, JSON serializable object)"),expected:tL.shape.expected.describe("The output of your application, including post-processing (an arbitrary, JSON serializable object)"),metadata:tL.shape.metadata,tags:tL.shape.tags,span_id:tL.shape.span_id,root_span_id:tL.shape.root_span_id}).openapi("DatasetEvent"),tU=tg("prompt_session");c.z.object({id:tU.shape.id,[h]:tU.shape[h],created:tU.shape.created,project_id:eZ.shape.project_id,prompt_session_id:eZ.shape.id,prompt_session_data:K.any.describe("Data about the prompt session"),prompt_data:K.any.describe("Data about the prompt"),object_data:K.any.describe("Data about the mapped data"),completion:K.any.describe("Data about the completion"),tags:tU.shape.tags}).openapi("PromptSessionEvent");var tP=tg("project"),tq=c.z.object({id:tP.shape.id,[h]:tP.shape[h],created:tP.shape.created,org_id:eQ.shape.org_id,project_id:eQ.shape.id,log_id:c.z.literal("g").describe("A literal 'g' which identifies the log as a project log"),input:tP.shape.input.describe("The arguments that uniquely define a user input (an arbitrary, JSON serializable object)."),output:tP.shape.output.describe("The output of your application, including post-processing (an arbitrary, JSON serializable object), that allows you to determine whether the result is correct or not. For example, in an app that generates SQL queries, the `output` should be the _result_ of the SQL query generated by the model, not the query itself, because there may be multiple valid queries that answer a single question."),expected:tP.shape.expected.describe("The ground truth value (an arbitrary, JSON serializable object) that you'd compare to `output` to determine if your `output` value is correct or not. Braintrust currently does not compare `output` to `expected` for you, since there are so many different ways to do that correctly. Instead, these values are just used to help you navigate while digging into analyses. However, we may later use these values to re-score outputs or fine-tune your models."),scores:tP.shape.scores.describe("A dictionary of numeric values (between 0 and 1) to log. The scores should give you a variety of signals that help you determine how accurate the outputs are compared to what you expect and diagnose failures. For example, a summarization app might have one score that tells you how accurate the summary is, and another that measures the word similarity between the generated and grouth truth summary. The word similarity score could help you determine whether the summarization was covering similar concepts or not. You can use these scores to help you sort, filter, and compare logs."),metadata:tP.shape.metadata,tags:tP.shape.tags,metrics:tP.shape.metrics,context:tP.shape.context,span_id:tP.shape.span_id,span_parents:tP.shape.span_parents,root_span_id:tP.shape.root_span_id,span_attributes:tP.shape.span_attributes}).openapi("ProjectLogsEvent"),tM='The `_is_merge` field controls how the row is merged with any existing row with the same id in the DB. By default (or when set to `false`), the existing row is completely replaced by the new row. When set to `true`, the new row is deep-merged into the existing row\n\nFor example, say there is an existing row in the DB `{"id": "foo", "input": {"a": 5, "b": 10}}`. If we merge a new row as `{"_is_merge": true, "id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"a": 5, "b": 11, "c": 20}}`. If we replace the new row as `{"id": "foo", "input": {"b": 11, "c": 20}}`, the new row will be `{"id": "foo", "input": {"b": 11, "c": 20}}`',tC=c.z.object({[f]:K.literalTrue.describe(tM),[z]:c.z.string().array().array().nullish().describe('The `_merge_paths` field allows controlling the depth of the merge. It can only be specified alongside `_is_merge=true`. `_merge_paths` is a list of paths, where each path is a list of field names. The deep merge will not descend below any of the specified merge paths.\n\nFor example, say there is an existing row in the DB `{"id": "foo", "input": {"a": {"b": 10}, "c": {"d": 20}}, "output": {"a": 20}}`. If we merge a new row as `{"_is_merge": true, "_merge_paths": [["input", "a"], ["output"]], "input": {"a": {"q": 30}, "c": {"e": 30}, "bar": "baz"}, "output": {"d": 40}}`, the new row will be `{"id": "foo": "input": {"a": {"q": 30}, "c": {"d": 20, "e": 30}, "bar": "baz"}, "output": {"d": 40}}`. In this case, due to the merge paths, we have replaced `input.a` and `output`, but have still deep-merged `input` and `input.c`.')}),tD=c.z.object({[f]:K.literalFalse.nullish().describe(tM),[_]:c.z.string().nullish().describe('Use the `_parent_id` field to create this row as a subspan of an existing row. It cannot be specified alongside `_is_merge=true`. Tracking hierarchical relationships are important for tracing (see the [guide](https://www.braintrust.dev/docs/guides/tracing) for full details).\n\nFor example, say we have logged a row `{"id": "abc", "input": "foo", "output": "bar", "expected": "boo", "scores": {"correctness": 0.33}}`. We can create a sub-span of the parent row by logging `{"_parent_id": "abc", "id": "llm_call", "input": {"prompt": "What comes after foo?"}, "output": "bar", "metrics": {"tokens": 1}}`. In the webapp, only the root span row `"abc"` will show up in the summary view. You can view the full trace hierarchy (in this case, the `"llm_call"` row) by clicking on the "abc" row.')});function tF(e,t){let r=Z(e),n=["acl","api_key","experiment"].includes(e)?"an":"a",i=x(H(e),"_").replace("_",""),a=t.merge(tD).openapi("Insert".concat(i,"EventReplace")),o=t.merge(tC).openapi("Insert".concat(i,"EventMerge")),s=c.z.union([a,o]).describe("".concat(x(n)," ").concat(r," event")).openapi("Insert".concat(i,"Event")),l=c.z.object({events:s.array().describe("A list of ".concat(r," events to insert"))}).openapi("Insert".concat(i,"EventRequest"));return{eventSchema:s,requestSchema:l}}var tB=c.z.object({row_ids:c.z.string().array().describe("The ids of all rows that were inserted, aligning one-to-one with the rows provided as input")}).openapi("InsertEventsResponse"),{eventSchema:tV,requestSchema:tJ}=tF("experiment",c.z.object({input:tN.shape.input,output:tN.shape.output,expected:tN.shape.expected,scores:tN.shape.scores,metadata:tN.shape.metadata,tags:tN.shape.tags,metrics:tN.shape.metrics,context:tN.shape.context,span_attributes:tN.shape.span_attributes,id:tN.shape.id.nullish(),dataset_record_id:tN.shape.dataset_record_id,[m]:tS.shape[m],created:tS.shape.created.nullish()})),{eventSchema:tQ,requestSchema:tG}=tF("dataset",c.z.object({input:tR.shape.input,expected:tR.shape.expected,metadata:tR.shape.metadata,tags:tR.shape.tags,id:tR.shape.id.nullish(),[m]:tL.shape[m],created:tS.shape.created.nullish()})),{eventSchema:t$,requestSchema:tY}=tF("project",c.z.object({input:tq.shape.input,output:tq.shape.output,expected:tq.shape.expected,scores:tq.shape.scores,metadata:tq.shape.metadata,tags:tq.shape.tags,metrics:tq.shape.metrics,context:tq.shape.context,span_attributes:tq.shape.span_attributes,id:tq.shape.id.nullish(),[m]:tP.shape[m],created:tS.shape.created.nullish()}));function tW(e,t){let r=Z(e),n=x(H(e),"_").replace("_","");return c.z.object({feedback:t.array().describe("A list of ".concat(r," feedback items"))}).openapi("Feedback".concat(n,"EventRequest"))}var tH=t_("experiment"),tZ=c.z.object({id:tH.shape.id,scores:tH.shape.scores,expected:tH.shape.expected,comment:tH.shape.comment,metadata:tH.shape.metadata,source:tH.shape.source}).openapi("FeedbackExperimentItem"),tX=tW("experiment",tZ),tK=t_("dataset"),t0=c.z.object({id:tK.shape.id,comment:tK.shape.comment,metadata:tK.shape.metadata,source:tK.shape.source}).openapi("FeedbackDatasetItem"),t1=tW("dataset",t0),t2=t_("project"),t6=c.z.object({id:t2.shape.id,scores:t2.shape.scores,expected:t2.shape.expected,comment:t2.shape.comment,metadata:t2.shape.metadata,source:t2.shape.source}).openapi("FeedbackProjectLogsItem"),t4=tW("project",t6),t3=t_("prompt"),t8=c.z.object({id:t3.shape.id,comment:t3.shape.comment,metadata:t3.shape.metadata,source:t3.shape.source}).openapi("FeedbackPromptItem"),t9=tW("prompt",t8),t5=t_("function"),t7=c.z.object({id:t5.shape.id,comment:t5.shape.comment,metadata:t5.shape.metadata,source:t5.shape.source}).openapi("FeedbackFunctionItem"),re=tW("function",t7),rt={experiment:{event:tN,fetchResponse:tA("experiment",tN),insertEvent:tV,insertRequest:tJ,feedbackItem:tZ,feedbackRequest:tX},dataset:{event:tR,fetchResponse:tA("dataset",tR),insertEvent:tQ,insertRequest:tG,feedbackItem:t0,feedbackRequest:t1},project_logs:{event:tq,fetchResponse:tA("project",tq),insertEvent:t$,insertRequest:tY,feedbackItem:t6,feedbackRequest:t4},prompt:{event:eZ,feedbackItem:t8,feedbackRequest:t9},function:{event:e0,feedbackItem:t7,feedbackRequest:re},prompt_session:{}};function rr(e){let t=H(e),r=Z(e),n=rt[t],i=c.z.object({...n.insertEvent?{events:n.insertEvent.array().nullish().describe("A list of ".concat(r," events to insert"))}:{},...n.feedbackItem?{feedback:n.feedbackItem.array().nullish().describe("A list of ".concat(r," feedback items"))}:{}});return c.z.record(c.z.string().uuid(),i).nullish().describe("A mapping from ".concat(e," id to a set of log events and feedback items to insert"))}function rn(e){return c.z.record(c.z.string().uuid(),tB).nullish().describe("A mapping from ".concat(e," id to row ids for inserted `events`"))}c.z.object({experiment:rr("experiment"),dataset:rr("dataset"),project_logs:rr("project")}).openapi("CrossObjectInsertRequest"),c.z.object({experiment:rn("experiment"),dataset:rn("dataset"),project_logs:rn("project")}).openapi("CrossObjectInsertResponse"),c.z.boolean().describe("Whether to summarize the scores and metrics. If false (or omitted), only the metadata will be returned."),c.z.string().uuid().describe("The experiment to compare against, if summarizing scores and metrics. If omitted, will fall back to the `base_exp_id` stored in the experiment metadata, and then to the most recent experiment run in the same project. Must pass `summarize_scores=true` for this id to be used"),c.z.boolean().describe("Whether to summarize the data. If false (or omitted), only the metadata will be returned."),c.z.object({project_name:c.z.string().describe("Name of the project that the experiment belongs to"),experiment_name:c.z.string().describe("Name of the experiment"),project_url:c.z.string().url().describe("URL to the project's page in the Braintrust app"),experiment_url:c.z.string().url().describe("URL to the experiment's page in the Braintrust app"),comparison_experiment_name:c.z.string().nullish().describe("The experiment which scores are baselined against"),scores:c.z.record(c.z.object({name:c.z.string().describe("Name of the score"),score:c.z.number().min(0).max(1).describe("Average score across all examples"),diff:c.z.number().min(-1).max(1).optional().describe("Difference in score between the current and comparison experiment"),improvements:c.z.number().int().min(0).describe("Number of improvements in the score"),regressions:c.z.number().int().min(0).describe("Number of regressions in the score")}).describe("Summary of a score's performance").openapi("ScoreSummary")).nullish().describe("Summary of the experiment's scores"),metrics:c.z.record(c.z.object({name:c.z.string().describe("Name of the metric"),metric:c.z.number().describe("Average metric across all examples"),unit:c.z.string().describe("Unit label for the metric"),diff:c.z.number().optional().describe("Difference in metric between the current and comparison experiment"),improvements:c.z.number().int().min(0).describe("Number of improvements in the metric"),regressions:c.z.number().int().min(0).describe("Number of regressions in the metric")}).describe("Summary of a metric's performance").openapi("MetricSummary")).nullish().describe("Summary of the experiment's metrics")}).describe("Summary of an experiment").openapi("SummarizeExperimentResponse"),c.z.object({project_name:c.z.string().describe("Name of the project that the dataset belongs to"),dataset_name:c.z.string().describe("Name of the dataset"),project_url:c.z.string().url().describe("URL to the project's page in the Braintrust app"),dataset_url:c.z.string().url().describe("URL to the dataset's page in the Braintrust app"),data_summary:c.z.object({total_records:c.z.number().int().min(0).describe("Total number of records in the dataset")}).nullish().describe("Summary of a dataset's data").openapi("DataSummary")}).describe("Summary of a dataset").openapi("SummarizeDatasetResponse");var ri=c.z.union([c.z.object({function_id:c.z.string().describe("The ID of the function."),version:c.z.string().optional().describe("The version of the function.")}),c.z.object({project_name:c.z.string().describe("The name of the project containing the function."),slug:c.z.string().describe("The slug of the function."),version:c.z.string().optional().describe("The version of the function.")}),c.z.object({global_function:c.z.string().describe("The name of the global function. Currently, the global namespace includes the functions in autoevals.")}),c.z.object({prompt_session_id:c.z.string().describe("The ID of the prompt session."),prompt_session_function_id:c.z.string().describe("The ID of the function in the prompt session."),version:c.z.string().optional().describe("The version of the function.")})]);c.z.object({api_version:c.z.number().optional().default(1)}).and(ri).and(c.z.object({input:c.z.any().optional(),parent:c.z.string().optional(),stream:c.z.boolean().optional()}));var ra=c.z.object({id:c.z.string().optional(),data:c.z.string()}),ro=ra.merge(c.z.object({event:c.z.literal("text_delta")})),rs=ra.merge(c.z.object({event:c.z.literal("json_delta")})),rl=ra.omit({data:!0}).merge(c.z.object({event:c.z.literal("done"),data:c.z.literal("")}));c.z.union([ro,rs,rl]);var rc=e1.keyof(),ru=c.z.enum(["all","none","some"]),rp=c.z.strictObject({collect:ru,fields:c.z.array(rc).optional()});BigInt("0x0DE1"),BigInt(48);var rd=BigInt(1)<<BigInt(64),rh=BigInt("205891132094649");function rm(e){return(BigInt(e)*rh%rd).toString(16).padStart(16,"0")}BigInt("1522336535492693385")}}]);