@jmespath-community/jmespath 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -8
- package/dist/cli.cjs +2816 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +2 -0
- package/dist/cli.mjs +857 -244
- package/dist/cli.mjs.map +1 -1
- package/dist/index.cjs +849 -268
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +86 -34
- package/dist/index.d.ts +86 -34
- package/dist/index.esm.js +850 -242
- package/dist/index.esm.js.map +1 -1
- package/dist/index.esm.min.js +5 -1
- package/dist/index.esm.min.js.map +1 -1
- package/dist/index.mjs +850 -242
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +852 -273
- package/dist/index.umd.js.map +1 -1
- package/dist/index.umd.min.js +5 -1
- package/dist/index.umd.min.js.map +1 -1
- package/package.json +41 -6
package/dist/index.esm.min.js
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
|
-
var nt=Object.defineProperty;var it=(i,t,e)=>t in i?nt(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var a=(i,t,e)=>it(i,typeof t!="symbol"?t+"":t,e);var L=i=>i!==null&&Object.prototype.toString.call(i)==="[object Object]",O=(i,t)=>{if(i===t)return true;if(typeof i!=typeof t)return false;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return false;for(let e=0;e<i.length;e+=1)if(!O(i[e],t[e]))return false;return true}if(L(i)&&L(t)){let e=Object.entries(i),r=new Set(Object.keys(t));if(e.length!==r.size)return false;for(let[n,s]of e){if(!O(s,t[n]))return false;r.delete(n);}return r.size===0}return false},E=i=>i==null||i===false?true:typeof i=="string"?i==="":typeof i=="object"?Array.isArray(i)?i.length===0:i===null?true:Object.keys(i).length===0:false,S=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_",R=i=>i>="0"&&i<="9"||i==="-",J=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="_",f=i=>{if(typeof i!="number"||Math.floor(i)!==i)throw new Error("invalid-value: expecting an integer.");return i},d=i=>{if(typeof i!="number"||i<0||Math.floor(i)!==i)throw new Error("invalid-value: expecting a non-negative integer.");return i},_=(...i)=>{for(let t=0;t<i.length;t++){if(i[t]===null||i[t]===void 0)throw new Error("not-a-number: undefined");if(typeof i[t]!="number")throw new Error("not-a-number")}},B=i=>{if(i=+i,!i)throw new Error("not-a-number: divide by zero");return i},w=(i,t)=>(_(i,t),i+t),M=(i,t)=>(_(i,t),i-t),U=(i,t)=>(_(i,t),i*t),k=(i,t)=>(_(i,t),i/B(t)),C=(i,t)=>(_(i,t),Math.floor(i/B(t))),V=(i,t)=>(_(i,t),i%t);var G=(i,t,e,r)=>{if(!i||!t)return null;e=Math.max(f(e=e||0),0),r=Math.min(f(r=r||i.length),i.length);let n=i.slice(e,r).indexOf(t);return n===-1?null:n+e},D=(i,t,e,r)=>{if(!i||!t)return null;e=Math.max(f(e=e||0),0),r=Math.min(f(r=r||i.length),i.length);let n=i.slice(e,r).lastIndexOf(t);return n===-1?null:n+e},j=i=>i.toLowerCase(),$=(i,t,e)=>{if(e=e||" ",e.length>1)throw new Error(`invalid value, ${i} expects its 'pad' parameter to be a valid string with a single codepoint`);return d(t),e},Q=(i,t,e)=>(e=$("pad_left",t,e),i&&i.padStart(t,e)||""),H=(i,t,e)=>(e=$("pad_right",t,e),i&&i.padEnd(t,e)||""),N=(i,t,e,r)=>r===0?i:r?(d(r),[...Array(r).keys()].map(()=>i=i.replace(t,e)),i):i.split(t).join(e),X=(i,t,e)=>{if(i.length==0&&t.length===0)return [];if(e==null)return i.split(t);if(d(e),e===0)return [i];let r=i.split(t);return [...r.slice(0,e),r.slice(e).join(t)]},z=(i,t)=>I(x(i,t),t),I=(i,t)=>q(i,e=>new RegExp(`^[${e}]*(.*?)`),t),x=(i,t)=>q(i,e=>new RegExp(`(.*?)[${e}]*$`),t),q=(i,t,e)=>{let r=e?e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return i.replace(t(r),"$1")},W=i=>i.toUpperCase();var Z={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"},st={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true},ut={" ":true,"\n":true,"\r":true," ":true},P=class{constructor(){a(this,"_current",0);a(this,"_enable_legacy_literals",false);}tokenize(t,e){let r=[];this._current=0,this._enable_legacy_literals=e?.enable_legacy_literals||false;let n,s,u;for(;this._current<t.length;)if(S(t[this._current]))n=this._current,s=this.consumeUnquotedIdentifier(t),r.push({start:n,type:"UnquotedIdentifier",value:s});else if(Z[t[this._current]]!==void 0)r.push({start:this._current,type:Z[t[this._current]],value:t[this._current]}),this._current+=1;else if(t[this._current]==="$")n=this._current,this._current+1<t.length&&S(t[this._current+1])?(this._current+=1,s=this.consumeUnquotedIdentifier(t),r.push({start:n,type:"Variable",value:s})):(r.push({start:n,type:"Root",value:t[this._current]}),this._current+=1);else if(t[this._current]==="-")if(this._current+1<t.length&&R(t[this._current+1])){let o=this.consumeNumber(t);o&&r.push(o);}else {let o={start:this._current,type:"Minus",value:"-"};r.push(o),this._current+=1;}else if(R(t[this._current]))u=this.consumeNumber(t),r.push(u);else if(t[this._current]==="[")u=this.consumeLBracket(t),r.push(u);else if(t[this._current]==='"')n=this._current,s=this.consumeQuotedIdentifier(t),r.push({start:n,type:"QuotedIdentifier",value:s});else if(t[this._current]==="'")n=this._current,s=this.consumeRawStringLiteral(t),r.push({start:n,type:"Literal",value:s});else if(t[this._current]==="`"){n=this._current;let o=this.consumeLiteral(t);r.push({start:n,type:"Literal",value:o});}else if(st[t[this._current]]!==void 0)u=this.consumeOperator(t),u&&r.push(u);else if(ut[t[this._current]]!==void 0)this._current+=1;else {let o=new Error(`Syntax error: unknown character: ${t[this._current]}`);throw o.name="LexerError",o}return r}consumeUnquotedIdentifier(t){let e=this._current;for(this._current+=1;this._current<t.length&&J(t[this._current]);)this._current+=1;return t.slice(e,this._current)}consumeQuotedIdentifier(t){let e=this._current;this._current+=1;let r=t.length;for(;t[this._current]!=='"'&&this._current<r;){let u=this._current;t[u]==="\\"&&(t[u+1]==="\\"||t[u+1]==='"')?u+=2:u+=1,this._current=u;}this._current+=1;let[n,s]=this.parseJSON(t.slice(e,this._current));if(!s){let u=new Error("syntax: unexpected end of JSON input");throw u.name="LexerError",u}return n}consumeRawStringLiteral(t){let e=this._current;this._current+=1;let r=t.length;for(;t[this._current]!=="'"&&this._current<r;){let s=this._current;t[s]==="\\"&&(t[s+1]==="\\"||t[s+1]==="'")?s+=2:s+=1,this._current=s;}this._current+=1;let n=t.slice(e+1,this._current-1);return N(N(n,"\\\\","\\"),"\\'","'")}consumeNumber(t){let e=this._current;this._current+=1;let r=t.length;for(;R(t[this._current])&&this._current<r;)this._current+=1;let n=parseInt(t.slice(e,this._current),10);return {start:e,value:n,type:"Number"}}consumeLBracket(t){let e=this._current;return this._current+=1,t[this._current]==="?"?(this._current+=1,{start:e,type:"Filter",value:"[?"}):t[this._current]==="]"?(this._current+=1,{start:e,type:"Flatten",value:"[]"}):{start:e,type:"Lbracket",value:"["}}consumeOrElse(t,e,r,n){let s=this._current;return this._current+=1,this._current<t.length&&t[this._current]===e?(this._current+=1,{start:s,type:n,value:t.slice(s,this._current)}):{start:s,type:r,value:t[s]}}consumeOperator(t){let e=this._current;switch(t[e]){case "!":return this.consumeOrElse(t,"=","Not","NE");case "<":return this.consumeOrElse(t,"=","LT","LTE");case ">":return this.consumeOrElse(t,"=","GT","GTE");case "=":return this.consumeOrElse(t,"=","Assign","EQ");case "&":return this.consumeOrElse(t,"&","Expref","And");case "|":return this.consumeOrElse(t,"|","Pipe","Or");case "/":return this.consumeOrElse(t,"/","Divide","Div")}}consumeLiteral(t){this._current+=1;let e=this._current,r=t.length;for(;t[this._current]!=="`"&&this._current<r;){let o=this._current;t[o]==="\\"&&(t[o+1]==="\\"||t[o+1]==="`")?o+=2:o+=1,this._current=o;}let n=t.slice(e,this._current).trimStart();n=n.replace("\\`","`");let s=null,u=false;if(this.looksLikeJSON(n)&&([s,u]=this.parseJSON(n)),!u&&this._enable_legacy_literals&&([s,u]=this.parseJSON(`"${n}"`)),!u){let o=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${t[this._current]}`);throw o.name="LexerError",o}return this._current+=1,s}looksLikeJSON(t){let e='[{"',r=["true","false","null"],n="-0123456789";if(t==="")return false;if(e.includes(t[0])||r.includes(t))return true;if(n.includes(t[0])){let[s,u]=this.parseJSON(t);return u}return false}parseJSON(t){try{return [JSON.parse(t),!0]}catch{return [null,false]}}},ot=new P,y=ot;var p={EOF:0,Variable:0,UnquotedIdentifier:0,QuotedIdentifier:0,Rbracket:0,Rparen:0,Comma:0,Rbrace:0,Number:0,Current:0,Expref:0,Root:0,Assign:1,Pipe:1,Question:2,Or:3,And:4,EQ:5,GT:5,LT:5,GTE:5,LTE:5,NE:5,Minus:6,Plus:6,Div:7,Divide:7,Modulo:7,Multiply:7,Flatten:9,Star:20,Filter:21,Dot:40,Not:45,Lbrace:50,Lbracket:55,Lparen:60},b=class i{constructor(){a(this,"index",0);a(this,"tokens",[]);}parse(t,e){this.loadTokens(t,e||{enable_legacy_literals:false}),this.index=0;let r=this.expression(0);if(this.lookahead(0)!=="EOF"){let n=this.lookaheadToken(0);this.errorToken(n,`Syntax error: unexpected token type: ${n.type}, value: ${n.value}`);}return r}loadTokens(t,e){this.tokens=y.tokenize(t,e),this.tokens.push({type:"EOF",value:"",start:t.length});}expression(t){let e=this.lookaheadToken(0);this.advance();let r=this.nud(e),n=this.lookahead(0);for(;t<p[n];)this.advance(),r=this.led(n,r),n=this.lookahead(0);return r}lookahead(t){return this.tokens[this.index+t].type}lookaheadToken(t){return this.tokens[this.index+t]}advance(){this.index+=1;}nud(t){switch(t.type){case "Variable":return {type:"Variable",name:t.value};case "Literal":return {type:"Literal",value:t.value};case "UnquotedIdentifier":return i.isKeyword(t,"let")&&this.lookahead(0)==="Variable"?this.parseLetExpression():{type:"Field",name:t.value};case "QuotedIdentifier":if(this.lookahead(0)==="Lparen")throw new Error("Syntax error: quoted identifier not allowed for function names.");return {type:"Field",name:t.value};case "Not":return {type:"NotExpression",child:this.expression(p.Not)};case "Minus":{let e=this.expression(p.Minus);return {type:"Unary",operator:t.type,operand:e}}case "Plus":{let e=this.expression(p.Plus);return {type:"Unary",operator:t.type,operand:e}}case "Star":return {type:"ValueProjection",left:{type:"Identity"},right:this.parseProjectionRHS(p.Star)};case "Filter":return this.led(t.type,{type:"Identity"});case "Lbrace":return this.parseMultiselectHash();case "Flatten":{let e={type:"Flatten",child:{type:"Identity"}},r=this.parseProjectionRHS(p.Flatten);return {type:"Projection",left:e,right:r}}case "Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){let e=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},e)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance(),this.advance();let e=this.parseProjectionRHS(p.Star);return {left:{type:"Identity"},right:e,type:"Projection"}}return this.parseMultiselectList()}case "Current":return {type:"Current"};case "Root":return {type:"Root"};case "Expref":return {type:"ExpressionReference",child:this.expression(p.Expref)};case "Lparen":{let e=this.expression(0);return this.match("Rparen"),e}default:this.errorToken(t);}}led(t,e){switch(t){case "Question":{let r=this.expression(0);this.match("Colon");let n=this.expression(0);return {type:"Ternary",condition:e,trueExpr:r,falseExpr:n}}case "Dot":{let r=p.Dot;if(this.lookahead(0)!=="Star"){let s=this.parseDotRHS(r);return {type:"Subexpression",left:e,right:s}}this.advance();let n=this.parseProjectionRHS(r);return {type:"ValueProjection",left:e,right:n}}case "Pipe":{let r=this.expression(p.Pipe);return {type:"Pipe",left:e,right:r}}case "Or":{let r=this.expression(p.Or);return {type:"OrExpression",left:e,right:r}}case "And":{let r=this.expression(p.And);return {type:"AndExpression",left:e,right:r}}case "Lparen":{if(e.type!=="Field")throw new Error("Syntax error: expected a Field node");let r=e.name,n=this.parseCommaSeparatedExpressionsUntilToken("Rparen");return {name:r,type:"Function",children:n}}case "Filter":{let r=this.expression(0);this.match("Rbracket");let n=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(p.Filter);return {type:"FilterProjection",left:e,right:n,condition:r}}case "Flatten":{let r={type:"Flatten",child:e},n=this.parseProjectionRHS(p.Flatten);return {type:"Projection",left:r,right:n}}case "Assign":{let r=e,n=this.expression(0);return {type:"Binding",variable:r.name,reference:n}}case "EQ":case "NE":case "GT":case "GTE":case "LT":case "LTE":return this.parseComparator(e,t);case "Plus":case "Minus":case "Multiply":case "Star":case "Divide":case "Modulo":case "Div":return this.parseArithmetic(e,t);case "Lbracket":{let r=this.lookaheadToken(0);if(r.type==="Number"||r.type==="Colon"){let s=this.parseIndexExpression();return this.projectIfSlice(e,s)}this.match("Star"),this.match("Rbracket");let n=this.parseProjectionRHS(p.Star);return {type:"Projection",left:e,right:n}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(t,e){return t.type==="UnquotedIdentifier"&&t.value===e}match(t){if(this.lookahead(0)===t){this.advance();return}else {let e=this.lookaheadToken(0);this.errorToken(e,`Syntax error: expected ${t}, got: ${e.type}`);}}errorToken(t,e=""){let r=new Error(e||`Syntax error: invalid token (${t.type}): "${t.value}"`);throw r.name="ParserError",r}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon")return this.parseSliceExpression();let t=Number(this.lookaheadToken(0).value);return this.advance(),this.match("Rbracket"),{type:"Index",value:t}}projectIfSlice(t,e){let r={type:"IndexExpression",left:t,right:e};return e.type==="Slice"?{left:r,right:this.parseProjectionRHS(p.Star),type:"Projection"}:r}parseSliceExpression(){let t=[null,null,null],e=0,r=this.lookaheadToken(0);for(;r.type!="Rbracket"&&e<3;){if(r.type==="Colon")e++,e===3&&this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression"),this.advance();else if(r.type==="Number"){let o=this.lookaheadToken(0).value;t[e]=o,this.advance();}else {let o=this.lookaheadToken(0);this.errorToken(o,`Syntax error, unexpected token: ${o.value}(${o.type})`);}r=this.lookaheadToken(0);}this.match("Rbracket");let[n,s,u]=t;return {type:"Slice",start:n,stop:s,step:u}}parseLetExpression(){let t=this.parseCommaSeparatedExpressionsUntilKeyword("in"),e=this.expression(0);return {type:"LetExpression",bindings:t.map(n=>n),expression:e}}parseCommaSeparatedExpressionsUntilKeyword(t){return this.parseCommaSeparatedExpressionsUntil(()=>i.isKeyword(this.lookaheadToken(0),t),()=>{this.advance();})}parseCommaSeparatedExpressionsUntilToken(t){return this.parseCommaSeparatedExpressionsUntil(()=>this.lookahead(0)===t,()=>this.match(t))}parseCommaSeparatedExpressionsUntil(t,e){let r=[],n;for(;!t();)n=this.expression(0),this.lookahead(0)==="Comma"&&this.match("Comma"),r.push(n);return e(),r}parseComparator(t,e){let r=this.expression(p[e]);return {type:"Comparator",name:e,left:t,right:r}}parseArithmetic(t,e){let r=this.expression(p[e]);return {type:"Arithmetic",operator:e,left:t,right:r}}parseDotRHS(t){let e=this.lookahead(0);if(["UnquotedIdentifier","QuotedIdentifier","Star"].includes(e))return this.expression(t);if(e==="Lbracket")return this.match("Lbracket"),this.parseMultiselectList();if(e==="Lbrace")return this.match("Lbrace"),this.parseMultiselectHash();let n=this.lookaheadToken(0);this.errorToken(n,`Syntax error, unexpected token: ${n.value}(${n.type})`);}parseProjectionRHS(t){if(p[this.lookahead(0)]<10)return {type:"Identity"};if(this.lookahead(0)==="Lbracket")return this.expression(t);if(this.lookahead(0)==="Filter")return this.expression(t);if(this.lookahead(0)==="Dot")return this.match("Dot"),this.parseDotRHS(t);let e=this.lookaheadToken(0);this.errorToken(e,`Syntax error, unexpected token: ${e.value}(${e.type})`);}parseMultiselectList(){let t=[];for(;this.lookahead(0)!=="Rbracket";){let e=this.expression(0);if(t.push(e),this.lookahead(0)==="Comma"&&(this.match("Comma"),this.lookahead(0)==="Rbracket"))throw new Error("Syntax error: unexpected token Rbracket")}return this.match("Rbracket"),{type:"MultiSelectList",children:t}}parseMultiselectHash(){let t=[],e=["UnquotedIdentifier","QuotedIdentifier"],r,n,s;for(;;){if(r=this.lookaheadToken(0),!e.includes(r.type))throw new Error(`Syntax error: expecting an identifier token, got: ${r.type}`);if(n=r.value,this.advance(),this.match("Colon"),s=this.expression(0),t.push({value:s,type:"KeyValuePair",name:n}),this.lookahead(0)==="Comma")this.match("Comma");else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return {type:"MultiSelectHash",children:t}}},at=new b,Y=at;var g=class i{constructor(t){a(this,"_text");this._text=t;}get string(){return this._text}get length(){return this.codePoints.length}compareTo(t){return i.compare(this,new i(t))}static get comparer(){return (e,r)=>new i(e).compareTo(r)}static compare(t,e){let r=t.codePoints,n=e.codePoints;for(let s=0;s<Math.min(r.length,n.length);s++)if(r[s]!==n[s])return r[s]-n[s]>0?1:-1;return r.length-n.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){return [...this._text].map(e=>e.codePointAt(0))}};var K=i=>([t])=>i(t),et=i=>([t])=>i(t),rt=i=>([t])=>i(t),A=class{constructor(t){a(this,"_interpreter");a(this,"_functionTable");a(this,"_customFunctions",new Set);a(this,"TYPE_NAME_TABLE",Object.freeze({0:"number",1:"any",2:"string",3:"array",4:"object",5:"boolean",6:"expression",7:"null",8:"Array<number>",10:"Array<object>",9:"Array<string>",11:"Array<Array<any>>"}));a(this,"functionAvg",([t])=>{if(!t||t.length==0)return null;let e=0;for(let r=0;r<t.length;r+=1)e+=t[r];return e/t.length});a(this,"functionContains",([t,e])=>{if(Array.isArray(t))return t.includes(e);if(typeof t=="string"){let r=t;if(typeof e=="string")return r.includes(e)}return null});a(this,"functionEndsWith",t=>{let[e,r]=t;return e.includes(r,e.length-r.length)});a(this,"functionFindFirst",this.createFindFunction(G));a(this,"functionFindLast",this.createFindFunction(D));a(this,"functionFromItems",([t])=>(t.map(e=>{if(e.length!=2||typeof e[0]!="string")throw new Error("invalid value, each array must contain two elements, a pair of string and value")}),Object.fromEntries(t)));a(this,"functionGroupBy",([t,e])=>{let r=this.createKeyFunction(e,[2]);return t.reduce((n,s)=>{let u=r(s??{});return (n[u]=n[u]||[]).push(s),n},{})});a(this,"functionItems",([t])=>Object.entries(t));a(this,"functionJoin",t=>{let[e,r]=t;return r.join(e)});a(this,"functionLength",([t])=>typeof t=="string"?new g(t).length:Array.isArray(t)?t.length:Object.keys(t).length);a(this,"functionMap",([t,e])=>{if(!this._interpreter)return [];let r=[],n=this._interpreter;for(let s=0;s<e.length;s+=1)r.push(n.visit(t,e[s]));return r});a(this,"functionMax",([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===0)return Math.max(...t);let r=t,n=r[0];for(let s=1;s<r.length;s+=1)n.localeCompare(r[s])<0&&(n=r[s]);return n});a(this,"functionMaxBy",t=>{let e=t[1],r=t[0],n=this.createKeyFunction(e,[0,2]),s=-1/0,u,o;for(let c=0;c<r.length;c+=1)o=n&&n(r[c]),o!==void 0&&o>s&&(s=o,u=r[c]);return u||null});a(this,"functionMerge",t=>{let e={};for(let r=0;r<t.length;r+=1){let n=t[r];e=Object.assign(e,n);}return e});a(this,"functionMin",([t])=>{if(!t.length)return null;if(this.getTypeName(t[0])===0)return Math.min(...t);let r=t,n=r[0];for(let s=1;s<r.length;s+=1)r[s].localeCompare(n)<0&&(n=r[s]);return n});a(this,"functionMinBy",t=>{let e=t[1],r=t[0],n=this.createKeyFunction(e,[0,2]),s=1/0,u,o;for(let c=0;c<r.length;c+=1)o=n&&n(r[c]),o!==void 0&&o<s&&(s=o,u=r[c]);return u||null});a(this,"functionNotNull",t=>{for(let e=0;e<t.length;e+=1)if(this.getTypeName(t[e])!==7)return t[e];return null});a(this,"functionPadLeft",this.createPadFunction(Q));a(this,"functionPadRight",this.createPadFunction(H));a(this,"functionReplace",t=>{let e=t[0],r=t[1],n=t[2];return N(e,r,n,t.length>3?t[3]:void 0)});a(this,"functionSplit",t=>{let e=t[0],r=t[1];return X(e,r,t.length>2?t[2]:void 0)});a(this,"functionReverse",([t])=>{if(this.getTypeName(t)===2)return new g(t).reverse();let r=t.slice(0);return r.reverse(),r});a(this,"functionSort",([t])=>t.length==0?t:typeof t[0]=="string"?[...t].sort(g.comparer):[...t].sort());a(this,"functionSortBy",t=>{let e=t[0].slice(0);if(e.length===0)return e;let r=this._interpreter,n=t[1],s=this.getTypeName(r.visit(n,e[0]));if(s!==void 0&&![0,2].includes(s))throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[s]})`);function u(o,c){throw new Error(`Invalid type: expected (${o.TYPE_NAME_TABLE[s]}), received ${o.TYPE_NAME_TABLE[o.getTypeName(c)]}`)}return e.sort((o,c)=>{let l=r.visit(n,o),h=r.visit(n,c);return this.getTypeName(l)!==s?u(this,l):this.getTypeName(h)!==s&&u(this,h),s===2?g.comparer(l,h):l-h})});a(this,"functionStartsWith",([t,e])=>t.startsWith(e));a(this,"functionSum",([t])=>t.reduce((e,r)=>e+r,0));a(this,"functionToArray",([t])=>this.getTypeName(t)===3?t:[t]);a(this,"functionToNumber",([t])=>{let e=this.getTypeName(t),r;return e===0?t:e===2&&(r=+t,!isNaN(r))?r:null});a(this,"functionToString",([t])=>this.getTypeName(t)===2?t:JSON.stringify(t));a(this,"functionTrim",this.createTrimFunction(z));a(this,"functionTrimLeft",this.createTrimFunction(I));a(this,"functionTrimRight",this.createTrimFunction(x));a(this,"functionType",([t])=>{switch(this.getTypeName(t)){case 0:return "number";case 2:return "string";case 3:return "array";case 4:return "object";case 5:return "boolean";case 7:return "null";default:throw new Error("invalid-type")}});a(this,"functionZip",t=>{let e=Math.min(...t.map(n=>n.length));return Array(e).fill(null).map((n,s)=>t.map(u=>u[s]))});this._interpreter=t,this._functionTable=this.buildFunctionTable();}buildFunctionTable(){return {abs:{_func:K(Math.abs),_signature:[{types:[0]}]},ceil:{_func:K(Math.ceil),_signature:[{types:[0]}]},floor:{_func:K(Math.floor),_signature:[{types:[0]}]},lower:{_func:et(j),_signature:[{types:[2]}]},upper:{_func:et(W),_signature:[{types:[2]}]},keys:{_func:rt(Object.keys),_signature:[{types:[4]}]},values:{_func:rt(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[3],variadic:true}]}}}registerFunction(t,e,r,n){let s=this._registerInternal(t,e,r,n);if(!s.success)throw new Error(s.message)}_registerInternal(t,e,r,n={}){if(!t||typeof t!="string"||t.trim()==="")return {success:false,reason:"invalid-name",message:"Function name must be a non-empty string"};try{this.validateInputSignatures(t,r);}catch(l){return {success:false,reason:"invalid-signature",message:l instanceof Error?l.message:"Invalid function signature"}}let{override:s=false,warn:u=false}=n,o=t in this._functionTable;return o&&!s?{success:false,reason:"already-exists",message:`Function already defined: ${t}(). Use { override: true } to replace it.`}:(o&&s&&u&&console.warn(`Warning: Overriding existing function: ${t}()`),this._functionTable[t]={_func:e.bind(this),_signature:r},this._customFunctions.add(t),{success:true,message:o?`Function ${t}() overridden successfully`:`Function ${t}() registered successfully`})}register(t,e,r,n={}){return this._registerInternal(t,e,r,n)}unregister(t){return this._customFunctions.has(t)?(delete this._functionTable[t],this._customFunctions.delete(t),true):false}isRegistered(t){return t in this._functionTable}getRegistered(){return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(let t of this._customFunctions)delete this._functionTable[t];this._customFunctions.clear();}callFunction(t,e){let r=this._functionTable[t];if(r===void 0)throw new Error(`Unknown function: ${t}()`);return this.validateArgs(t,e,r._signature),r._func.call(this,e)}validateInputSignatures(t,e){for(let r=0;r<e.length;r+=1)if("variadic"in e[r]&&r!==e.length-1)throw new Error(`Invalid arity: ${t}() 'variadic' argument ${r+1} must occur last`)}validateArgs(t,e,r){this.validateInputSignatures(t,r),this.validateArity(t,e,r),this.validateTypes(t,e,r);}validateArity(t,e,r){let n=r.filter(c=>!(c.optional??false)).length,s=r[r.length-1]?.variadic??false,u=e.length<n,o=e.length>r.length;if(s&&u||!s&&(u||o)){let c=u&&(!s&&n>1||s)?"at least ":"",l=r.length>1;throw new Error(`Invalid arity: ${t}() takes ${c}${n} argument${l&&"s"||""} but received ${e.length}`)}}validateTypes(t,e,r){for(let n=0;n<r.length;n+=1){let s=r[n].types,u=this.getTypeName(e[n]);if(u===void 0)continue;if(!s.some(c=>this.typeMatches(u,c,e[n]))){let c=s.map(l=>this.TYPE_NAME_TABLE[l]).join(" | ");throw new Error(`Invalid type: ${t}() expected argument ${n+1} to be type (${c}) but received type ${this.TYPE_NAME_TABLE[u]} instead.`)}}}typeMatches(t,e,r){if(e===1)return true;if(e===9||e===8||e===10||e===11||e===3){if(e===3)return t===3;if(t===3){let n;e===8?n=0:e===10?n=4:e===9?n=2:e===11&&(n=3);let s=r;for(let u=0;u<s.length;u+=1){let o=this.getTypeName(s[u]);if(o!==void 0&&n!==void 0&&!this.typeMatches(o,n,s[u]))return false}return true}}else return t===e;return false}getTypeName(t){if(t===null)return 7;if(typeof t=="string")return 2;if(typeof t=="number")return 0;if(typeof t=="boolean")return 5;if(Array.isArray(t))return 3;if(typeof t=="object")return t.expref?6:4}createKeyFunction(t,e){let r=this._interpreter;return s=>{let u=r.visit(t,s);if(!e.includes(this.getTypeName(u))){let o=`Invalid type: expected one of (${e.map(c=>this.TYPE_NAME_TABLE[c]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(u)]}`;throw new Error(o)}return u}}createFindFunction(t){return e=>{let r=e[0],n=e[1],s=e.length>2?e[2]:void 0,u=e.length>3?e[3]:void 0;return t(r,n,s,u)}}createPadFunction(t){return e=>{let r=e[0],n=e[1],s=e.length>2?e[2]:void 0;return t(r,n,s)}}createTrimFunction(t){return e=>{let r=e[0],n=e.length>1?e[1]:void 0;return t(r,n)}}};var m=class i{constructor(){a(this,"inner");a(this,"data",{});}get currentScopeData(){return this.data}withScope(t){let e=new i;return e.inner=this,e.data=t,e}getValue(t){return Object.prototype.hasOwnProperty.call(this.data,t)?this.data[t]:this.inner?this.inner.getValue(t):null}};var ct=new m,v=class i{constructor(){a(this,"runtime");a(this,"_rootValue",null);a(this,"_scope");this.runtime=new A(this),this._scope=new m;}withScope(t){let e=new i;return e.runtime._functionTable=this.runtime._functionTable,e._rootValue=this._rootValue,e._scope=this._scope.withScope(t),e}search(t,e){return this._rootValue=e,this._scope=ct,this.visit(t,e)}visit(t,e){switch(t.type){case "Ternary":{let n=this.visit(t.condition,e);return E(n)?this.visit(t.falseExpr,e):this.visit(t.trueExpr,e)}case "Field":let r=t.name;return e===null||typeof e!="object"||Array.isArray(e)?null:e[r]??null;case "LetExpression":{let{bindings:n,expression:s}=t,u={};return n.forEach(o=>{let c=this.visit(o,e);u={...u,...c};}),this.withScope(u).visit(s,e)}case "Binding":{let{variable:n,reference:s}=t,u=this.visit(s,e);return {[n]:u}}case "Variable":{let n=t.name;if(!this._scope.getValue(n)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,n))throw new Error(`Error referencing undefined variable ${n}`);return this._scope.getValue(n)}case "IndexExpression":return this.visit(t.right,this.visit(t.left,e));case "Subexpression":{let n=this.visit(t.left,e);return n!=null?this.visit(t.right,n)??null:null}case "Index":{if(!Array.isArray(e))return null;let n=t.value<0?e.length+t.value:t.value;return e[n]??null}case "Slice":{if(!Array.isArray(e)&&typeof e!="string")return null;let{start:n,stop:s,step:u}=this.computeSliceParams(e.length,t);if(typeof e=="string"){let o=[...e];return this.slice(o,n,s,u).join("")}else return this.slice(e,n,s,u)}case "Projection":{let{left:n,right:s}=t,u=false;n.type==="IndexExpression"&&n.right.type==="Slice"&&(u=true);let o=this.visit(n,e);if(u&&typeof o=="string")return this.visit(s,o);if(!Array.isArray(o))return null;let c=[];for(let l of o){let h=this.visit(s,l);h!==null&&c.push(h);}return c}case "ValueProjection":{let{left:n,right:s}=t,u=this.visit(n,e);if(u===null||typeof u!="object"||Array.isArray(u))return null;let o=[],c=Object.values(u);for(let l of c){let h=this.visit(s,l);h!==null&&o.push(h);}return o}case "FilterProjection":{let{left:n,right:s,condition:u}=t,o=this.visit(n,e);if(!Array.isArray(o))return null;let c=[];for(let l of o){let h=this.visit(u,l);if(E(h))continue;let F=this.visit(s,l);F!==null&&c.push(F);}return c}case "Arithmetic":{let n=this.visit(t.left,e),s=this.visit(t.right,e);switch(t.operator){case "Plus":return w(n,s);case "Minus":return M(n,s);case "Multiply":case "Star":return U(n,s);case "Divide":return k(n,s);case "Modulo":return V(n,s);case "Div":return C(n,s);default:throw new Error(`Syntax error: unknown arithmetic operator: ${t.operator}`)}}case "Unary":{let n=this.visit(t.operand,e);switch(t.operator){case "Plus":return _(n),n;case "Minus":return _(n),-n;default:throw new Error(`Syntax error: unknown arithmetic operator: ${t.operator}`)}}case "Comparator":{let n=this.visit(t.left,e),s=this.visit(t.right,e);switch(t.name){case "EQ":return O(n,s);case "NE":return !O(n,s)}if(typeof n!="number"||typeof s!="number")return null;switch(t.name){case "GT":return n>s;case "GTE":return n>=s;case "LT":return n<s;case "LTE":return n<=s}}case "Flatten":{let n=this.visit(t.child,e);return Array.isArray(n)?n.flat():null}case "Root":return this._rootValue;case "MultiSelectList":{let n=[];for(let s of t.children)n.push(this.visit(s,e));return n}case "MultiSelectHash":{let n={};for(let s of t.children)n[s.name]=this.visit(s.value,e);return n}case "OrExpression":{let n=this.visit(t.left,e);return E(n)?this.visit(t.right,e):n}case "AndExpression":{let n=this.visit(t.left,e);return E(n)?n:this.visit(t.right,e)}case "NotExpression":return E(this.visit(t.child,e));case "Literal":return t.value;case "Pipe":return this.visit(t.right,this.visit(t.left,e));case "Function":{let n=[];for(let s of t.children)n.push(this.visit(s,e));return this.runtime.callFunction(t.name,n)}case "ExpressionReference":return {expref:true,...t.child};case "Current":case "Identity":return e}}computeSliceParams(t,e){let{start:r,stop:n,step:s}=e;if(s===null)s=1;else if(s===0){let u=new Error("Invalid value: slice step cannot be 0");throw u.name="RuntimeError",u}return r=r===null?s<0?t-1:0:this.capSliceRange(t,r,s),n=n===null?s<0?-1:t:this.capSliceRange(t,n,s),{start:r,stop:n,step:s}}capSliceRange(t,e,r){let n=e;return n<0?(n+=t,n<0&&(n=r<0?-1:0)):n>=t&&(n=r<0?t-1:t),n}slice(t,e,r,n){let s=[];if(n>0)for(let u=e;u<r;u+=n)s.push(t[u]);else for(let u=e;u>r;u+=n)s.push(t[u]);return s}},pt=new v,T=pt;var lt=1,ht=3,Ne=11,Tt=8,Re=10,_t=9,gt=5,mt=6,Et=7,Ot=0,ft=4,Nt=2;function Rt(i,t){return Y.parse(i,t)}function dt(i,t){return y.tokenize(i,t)}var yt=(i,t,e,r)=>{T.runtime.registerFunction(i,t,e,r);},At=(i,t,e,r)=>T.runtime.register(i,t,e,r),St=i=>T.runtime.unregister(i),It=i=>T.runtime.isRegistered(i),xt=()=>T.runtime.getRegistered(),Pt=()=>T.runtime.getCustomFunctions(),bt=()=>{T.runtime.clearCustomFunctions();};function Yt(i,t,e){let r=Y.parse(t,e);return T.search(r,i)}function de(){return new m}var Kt=T,ye={compile:Rt,registerFunction:yt,register:At,unregisterFunction:St,isRegistered:It,getRegisteredFunctions:xt,getCustomFunctions:Pt,clearCustomFunctions:bt,search:Yt,tokenize:dt,TreeInterpreter:Kt,TYPE_ANY:lt,TYPE_ARRAY_NUMBER:Tt,TYPE_ARRAY_STRING:_t,TYPE_ARRAY:ht,TYPE_BOOLEAN:gt,TYPE_EXPREF:mt,TYPE_NULL:Et,TYPE_NUMBER:Ot,TYPE_OBJECT:ft,TYPE_STRING:Nt};export{de as Scope,lt as TYPE_ANY,ht as TYPE_ARRAY,Ne as TYPE_ARRAY_ARRAY,Tt as TYPE_ARRAY_NUMBER,Re as TYPE_ARRAY_OBJECT,_t as TYPE_ARRAY_STRING,gt as TYPE_BOOLEAN,mt as TYPE_EXPREF,Et as TYPE_NULL,Ot as TYPE_NUMBER,ft as TYPE_OBJECT,Nt as TYPE_STRING,Kt as TreeInterpreter,bt as clearCustomFunctions,Rt as compile,ye as default,Pt as getCustomFunctions,xt as getRegisteredFunctions,It as isRegistered,ye as jmespath,At as register,yt as registerFunction,Yt as search,dt as tokenize,St as unregisterFunction};//# sourceMappingURL=index.esm.min.js.map
|
|
1
|
+
var de=Object.defineProperty;var Te=(i,e,t)=>e in i?de(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t;var c=(i,e,t)=>Te(i,typeof e!="symbol"?e+"":e,t);var _e=["left","right","condition","child","operand","trueExpr","falseExpr","expression"];function ge(i,e){let t=i;for(let n of _e){let r=t[n];r&&typeof r=="object"&&"type"in r&&e.push(r);}if(Array.isArray(t.children))for(let n of t.children)n&&(e.push(n),n.type==="KeyValuePair"&&n.value&&e.push(n.value));if(Array.isArray(t.bindings))for(let n of t.bindings)n&&(e.push(n),n.reference&&e.push(n.reference));}function U(i,e){let t=[i];for(;t.length>0;){let n=t.pop();if(!n)break;if(e(n)===false)return;ge(n,t);}}function x(i){let e=0;return U(i,()=>(e+=1,true)),e}function I(i,e){let{allowedFunctions:t,disallowedFunctions:n}=e;if(!t&&!n)return null;let r=null;return U(i,s=>{if(s.type!=="Function")return true;let o=s.name;return t&&!t.includes(o)?(r=`Function '${o}' is not allowed`,false):n&&n.includes(o)?(r=`Function '${o}' is disallowed`,false):true}),r}var D=i=>i!==null&&Object.prototype.toString.call(i)==="[object Object]",y=(i,e)=>{if(i===e)return true;if(typeof i!=typeof e)return false;if(Array.isArray(i)&&Array.isArray(e)){if(i.length!==e.length)return false;for(let t=0;t<i.length;t+=1)if(!y(i[t],e[t]))return false;return true}if(D(i)&&D(e)){let t=Object.entries(i),n=new Set(Object.keys(e));if(t.length!==n.size)return false;for(let[r,s]of t){if(!y(s,e[r]))return false;n.delete(r);}return n.size===0}return false},d=i=>i==null||i===false?true:typeof i=="string"?i==="":typeof i=="object"?Array.isArray(i)?i.length===0:Object.keys(i).length===0:false,F=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i==="_",b=i=>i>="0"&&i<="9"||i==="-",j=i=>i>="a"&&i<="z"||i>="A"&&i<="Z"||i>="0"&&i<="9"||i==="_",N=i=>{if(typeof i!="number"||Math.floor(i)!==i)throw new Error("invalid-value: expecting an integer.");return i},P=i=>{if(typeof i!="number"||i<0||Math.floor(i)!==i)throw new Error("invalid-value: expecting a non-negative integer.");return i},_=(...i)=>{for(let e=0;e<i.length;e++){if(i[e]===null||i[e]===void 0)throw new Error("not-a-number: undefined");if(typeof i[e]!="number")throw new Error("not-a-number")}},G=i=>{if(i=+i,!i)throw new Error("not-a-number: divide by zero");return i},$=(i,e)=>(_(i,e),i+e),z=(i,e)=>(_(i,e),i-e),Q=(i,e)=>(_(i,e),i*e),H=(i,e)=>(_(i,e),i/G(e)),X=(i,e)=>(_(i,e),Math.floor(i/G(e))),q=(i,e)=>(_(i,e),i%e);var W={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"},Oe={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true},Ee={" ":true,"\n":true,"\r":true," ":true},J=class{constructor(){c(this,"_current",0);c(this,"_enable_legacy_literals",false);}tokenize(e,t){let n=[];this._current=0,this._enable_legacy_literals=t?.enable_legacy_literals||false;let r,s,o;for(;this._current<e.length;)if(F(e[this._current]))r=this._current,s=this.consumeUnquotedIdentifier(e),n.push({start:r,type:"UnquotedIdentifier",value:s});else if(W[e[this._current]]!==void 0)n.push({start:this._current,type:W[e[this._current]],value:e[this._current]}),this._current+=1;else if(e[this._current]==="$")r=this._current,this._current+1<e.length&&F(e[this._current+1])?(this._current+=1,s=this.consumeUnquotedIdentifier(e),n.push({start:r,type:"Variable",value:s})):(n.push({start:r,type:"Root",value:e[this._current]}),this._current+=1);else if(e[this._current]==="-")if(this._current+1<e.length&&b(e[this._current+1])){let u=this.consumeNumber(e);u&&n.push(u);}else {let u={start:this._current,type:"Minus",value:"-"};n.push(u),this._current+=1;}else if(b(e[this._current]))o=this.consumeNumber(e),n.push(o);else if(e[this._current]==="[")o=this.consumeLBracket(e),n.push(o);else if(e[this._current]==='"')r=this._current,s=this.consumeQuotedIdentifier(e),n.push({start:r,type:"QuotedIdentifier",value:s});else if(e[this._current]==="'")r=this._current,s=this.consumeRawStringLiteral(e),n.push({start:r,type:"Literal",value:s});else if(e[this._current]==="`"){r=this._current;let u=this.consumeLiteral(e);n.push({start:r,type:"Literal",value:u});}else if(Oe[e[this._current]]!==void 0)o=this.consumeOperator(e),o&&n.push(o);else if(Ee[e[this._current]]!==void 0)this._current+=1;else {let u=new Error(`Syntax error: unknown character: ${e[this._current]}`);throw u.name="LexerError",u}return n}consumeUnquotedIdentifier(e){let t=this._current;for(this._current+=1;this._current<e.length&&j(e[this._current]);)this._current+=1;return e.slice(t,this._current)}consumeQuotedIdentifier(e){let t=this._current;this._current+=1;let n=e.length;for(;e[this._current]!=='"'&&this._current<n;){let o=this._current;e[o]==="\\"&&(e[o+1]==="\\"||e[o+1]==='"')?o+=2:o+=1,this._current=o;}this._current+=1;let[r,s]=this.parseJSON(e.slice(t,this._current));if(!s){let o=new Error("syntax: unexpected end of JSON input");throw o.name="LexerError",o}return r}consumeRawStringLiteral(e){let t=this._current;this._current+=1;let n=e.length;for(;e[this._current]!=="'"&&this._current<n;){let s=this._current;e[s]==="\\"&&(e[s+1]==="\\"||e[s+1]==="'")?s+=2:s+=1,this._current=s;}return this._current+=1,e.slice(t+1,this._current-1).replace(/\\(['\\])/g,"$1")}consumeNumber(e){let t=this._current;this._current+=1;let n=e.length;for(;b(e[this._current])&&this._current<n;)this._current+=1;let r=parseInt(e.slice(t,this._current),10);return {start:t,value:r,type:"Number"}}consumeLBracket(e){let t=this._current;return this._current+=1,e[this._current]==="?"?(this._current+=1,{start:t,type:"Filter",value:"[?"}):e[this._current]==="]"?(this._current+=1,{start:t,type:"Flatten",value:"[]"}):{start:t,type:"Lbracket",value:"["}}consumeOrElse(e,t,n,r){let s=this._current;return this._current+=1,this._current<e.length&&e[this._current]===t?(this._current+=1,{start:s,type:r,value:e.slice(s,this._current)}):{start:s,type:n,value:e[s]}}consumeOperator(e){let t=this._current;switch(e[t]){case "!":return this.consumeOrElse(e,"=","Not","NE");case "<":return this.consumeOrElse(e,"=","LT","LTE");case ">":return this.consumeOrElse(e,"=","GT","GTE");case "=":return this.consumeOrElse(e,"=","Assign","EQ");case "&":return this.consumeOrElse(e,"&","Expref","And");case "|":return this.consumeOrElse(e,"|","Pipe","Or");case "/":return this.consumeOrElse(e,"/","Divide","Div")}}consumeLiteral(e){this._current+=1;let t=this._current,n=e.length;for(;e[this._current]!=="`"&&this._current<n;){let u=this._current;e[u]==="\\"&&(e[u+1]==="\\"||e[u+1]==="`")?u+=2:u+=1,this._current=u;}let r=e.slice(t,this._current).trimStart();r=r.replace("\\`","`");let s=null,o=false;if(this.looksLikeJSON(r)&&([s,o]=this.parseJSON(r)),!o&&this._enable_legacy_literals&&([s,o]=this.parseJSON(`"${r}"`)),!o){let u=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${e[this._current]}`);throw u.name="LexerError",u}return this._current+=1,s}looksLikeJSON(e){let n=["true","false","null"],r="-0123456789";if(e==="")return false;if('[{"'.includes(e[0])||n.includes(e))return true;if(r.includes(e[0])){let[s,o]=this.parseJSON(e);return o}return false}parseJSON(e){try{return [JSON.parse(e),!0]}catch{return [null,false]}}},ye=new J,v=ye;var h={EOF:0,Variable:0,UnquotedIdentifier:0,QuotedIdentifier:0,Rbracket:0,Rparen:0,Comma:0,Rbrace:0,Number:0,Current:0,Expref:0,Root:0,Assign:1,Pipe:1,Question:2,Or:3,And:4,EQ:5,GT:5,LT:5,GTE:5,LTE:5,NE:5,Minus:6,Plus:6,Div:7,Divide:7,Modulo:7,Multiply:7,Flatten:9,Star:20,Filter:21,Dot:40,Not:45,Lbrace:50,Lbracket:55,Lparen:60},L=class i{constructor(){c(this,"index",0);c(this,"tokens",[]);c(this,"depth",0);c(this,"maxDepth");c(this,"nodeCount",0);c(this,"maxNodes");}parse(e,t){this.loadTokens(e,t||{enable_legacy_literals:false}),this.index=0,this.depth=0,this.nodeCount=0,this.maxDepth=t?.maxDepth,this.maxNodes=t?.maxNodes;let n=this.expression(0);if(this.lookahead(0)!=="EOF"){let r=this.lookaheadToken(0);this.errorToken(r,`Syntax error: unexpected token type: ${r.type}, value: ${r.value}`);}if(this.maxNodes!==void 0&&x(n)>this.maxNodes)throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`);return n}loadTokens(e,t){this.tokens=v.tokenize(e,t),this.tokens.push({type:"EOF",value:"",start:e.length});}expression(e){if(this.maxDepth!==void 0&&this.depth>=this.maxDepth)throw new Error(`Expression exceeds maximum allowed depth of ${this.maxDepth}`);this.depth+=1,this.trackNode();try{let t=this.lookaheadToken(0);this.advance();let n=this.nud(t),r=this.lookahead(0);for(;e<h[r];)this.trackNode(),this.advance(),n=this.led(r,n),r=this.lookahead(0);return n}finally{this.depth-=1;}}trackNode(){if(this.nodeCount+=1,this.maxNodes!==void 0&&this.nodeCount>this.maxNodes)throw new Error(`Expression exceeds maximum allowed node count of ${this.maxNodes}`)}lookahead(e){return this.tokens[this.index+e].type}lookaheadToken(e){return this.tokens[this.index+e]}advance(){this.index+=1;}nud(e){switch(e.type){case "Variable":return {type:"Variable",name:e.value};case "Literal":return {type:"Literal",value:e.value};case "UnquotedIdentifier":return i.isKeyword(e,"let")&&this.lookahead(0)==="Variable"?this.parseLetExpression():{type:"Field",name:e.value};case "QuotedIdentifier":if(this.lookahead(0)==="Lparen")throw new Error("Syntax error: quoted identifier not allowed for function names.");return {type:"Field",name:e.value};case "Not":return {type:"NotExpression",child:this.expression(h.Not)};case "Minus":{let t=this.expression(h.Minus);return {type:"Unary",operator:e.type,operand:t}}case "Plus":{let t=this.expression(h.Plus);return {type:"Unary",operator:e.type,operand:t}}case "Star":return {type:"ValueProjection",left:{type:"Identity"},right:this.parseProjectionRHS(h.Star)};case "Filter":return this.led(e.type,{type:"Identity"});case "Lbrace":return this.parseMultiselectHash();case "Flatten":{let t={type:"Flatten",child:{type:"Identity"}},n=this.parseProjectionRHS(h.Flatten);return {type:"Projection",left:t,right:n}}case "Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){let t=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},t)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance(),this.advance();let t=this.parseProjectionRHS(h.Star);return {left:{type:"Identity"},right:t,type:"Projection"}}return this.parseMultiselectList()}case "Current":return {type:"Current"};case "Root":return {type:"Root"};case "Expref":return {type:"ExpressionReference",child:this.expression(h.Expref)};case "Lparen":{let t=this.expression(0);return this.match("Rparen"),t}default:this.errorToken(e);}}led(e,t){switch(e){case "Question":{let n=this.expression(0);this.match("Colon");let r=this.expression(0);return {type:"Ternary",condition:t,trueExpr:n,falseExpr:r}}case "Dot":{let n=h.Dot;if(this.lookahead(0)!=="Star"){let s=this.parseDotRHS(n);return {type:"Subexpression",left:t,right:s}}this.advance();let r=this.parseProjectionRHS(n);return {type:"ValueProjection",left:t,right:r}}case "Pipe":{let n=this.expression(h.Pipe);return {type:"Pipe",left:t,right:n}}case "Or":{let n=this.expression(h.Or);return {type:"OrExpression",left:t,right:n}}case "And":{let n=this.expression(h.And);return {type:"AndExpression",left:t,right:n}}case "Lparen":{if(t.type!=="Field")throw new Error("Syntax error: expected a Field node");let n=t.name,r=this.parseCommaSeparatedExpressionsUntilToken("Rparen");return {name:n,type:"Function",children:r}}case "Filter":{let n=this.expression(0);this.match("Rbracket");let r=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(h.Filter);return {type:"FilterProjection",left:t,right:r,condition:n}}case "Flatten":{let n={type:"Flatten",child:t},r=this.parseProjectionRHS(h.Flatten);return {type:"Projection",left:n,right:r}}case "Assign":{let n=t,r=this.expression(0);return {type:"Binding",variable:n.name,reference:r}}case "EQ":case "NE":case "GT":case "GTE":case "LT":case "LTE":return this.parseComparator(t,e);case "Plus":case "Minus":case "Multiply":case "Star":case "Divide":case "Modulo":case "Div":return this.parseArithmetic(t,e);case "Lbracket":{let n=this.lookaheadToken(0);if(n.type==="Number"||n.type==="Colon"){let s=this.parseIndexExpression();return this.projectIfSlice(t,s)}this.match("Star"),this.match("Rbracket");let r=this.parseProjectionRHS(h.Star);return {type:"Projection",left:t,right:r}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(e,t){return e.type==="UnquotedIdentifier"&&e.value===t}match(e){if(this.lookahead(0)===e){this.advance();return}else {let t=this.lookaheadToken(0);this.errorToken(t,`Syntax error: expected ${e}, got: ${t.type}`);}}errorToken(e,t=""){let n=new Error(t||`Syntax error: invalid token (${e.type}): "${e.value}"`);throw n.name="ParserError",n}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon")return this.parseSliceExpression();let e=Number(this.lookaheadToken(0).value);return this.advance(),this.match("Rbracket"),{type:"Index",value:e}}projectIfSlice(e,t){let n={type:"IndexExpression",left:e,right:t};if(t.type==="Slice"){let r=this.parseProjectionRHS(h.Star);return r.type==="Identity"?n:{left:n,right:r,type:"Projection"}}return n}parseSliceExpression(){let e=[null,null,null],t=0,n=this.lookaheadToken(0);for(;n.type!="Rbracket"&&t<3;){if(n.type==="Colon")t++,t===3&&this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression"),this.advance();else if(n.type==="Number"){let u=this.lookaheadToken(0).value;e[t]=u,this.advance();}else {let u=this.lookaheadToken(0);this.errorToken(u,`Syntax error, unexpected token: ${u.value}(${u.type})`);}n=this.lookaheadToken(0);}this.match("Rbracket");let[r,s,o]=e;return {type:"Slice",start:r,stop:s,step:o}}parseLetExpression(){let e=this.parseCommaSeparatedExpressionsUntilKeyword("in"),t=this.expression(0);return {type:"LetExpression",bindings:e.map(r=>r),expression:t}}parseCommaSeparatedExpressionsUntilKeyword(e){return this.parseCommaSeparatedExpressionsUntil(()=>i.isKeyword(this.lookaheadToken(0),e),()=>{this.advance();})}parseCommaSeparatedExpressionsUntilToken(e){return this.parseCommaSeparatedExpressionsUntil(()=>this.lookahead(0)===e,()=>this.match(e))}parseCommaSeparatedExpressionsUntil(e,t){let n=[],r;for(;!e();)r=this.expression(0),this.lookahead(0)==="Comma"&&this.match("Comma"),n.push(r);return t(),n}parseComparator(e,t){let n=this.expression(h[t]);return {type:"Comparator",name:t,left:e,right:n}}parseArithmetic(e,t){let n=this.expression(h[t]);return {type:"Arithmetic",operator:t,left:e,right:n}}parseDotRHS(e){let t=this.lookahead(0);if(["UnquotedIdentifier","QuotedIdentifier","Star"].includes(t))return this.expression(e);if(t==="Lbracket")return this.match("Lbracket"),this.parseMultiselectList();if(t==="Lbrace")return this.match("Lbrace"),this.parseMultiselectHash();let r=this.lookaheadToken(0);this.errorToken(r,`Syntax error, unexpected token: ${r.value}(${r.type})`);}parseProjectionRHS(e){if(h[this.lookahead(0)]<10)return {type:"Identity"};if(this.lookahead(0)==="Lbracket")return this.expression(e);if(this.lookahead(0)==="Filter")return this.expression(e);if(this.lookahead(0)==="Dot")return this.match("Dot"),this.parseDotRHS(e);let t=this.lookaheadToken(0);this.errorToken(t,`Syntax error, unexpected token: ${t.value}(${t.type})`);}parseMultiselectList(){let e=[];for(;this.lookahead(0)!=="Rbracket";){let t=this.expression(0);if(e.push(t),this.lookahead(0)==="Comma"&&(this.match("Comma"),this.lookahead(0)==="Rbracket"))throw new Error("Syntax error: unexpected token Rbracket")}return this.match("Rbracket"),{type:"MultiSelectList",children:e}}parseMultiselectHash(){let e=[],t=["UnquotedIdentifier","QuotedIdentifier"],n,r,s;for(;;){if(n=this.lookaheadToken(0),!t.includes(n.type))throw new Error(`Syntax error: expecting an identifier token, got: ${n.type}`);if(r=n.value,this.advance(),this.match("Colon"),s=this.expression(0),e.push({value:s,type:"KeyValuePair",name:r}),this.lookahead(0)==="Comma")this.match("Comma");else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return {type:"MultiSelectHash",children:e}}},Ne=new L,g=Ne;var ee=(i,e,t,n)=>{if(!i||!e)return null;let r=Math.max(N(t??0),0),s=Math.min(N(n??i.length),i.length),o=i.slice(r,s).indexOf(e);return o===-1?null:o+r},te=(i,e,t,n)=>{if(!i||!e)return null;let r=Math.max(N(t??0),0),s=Math.min(N(n??i.length),i.length),o=i.slice(r,s).lastIndexOf(e);return o===-1?null:o+r},ne=i=>i.toLowerCase(),re=(i,e,t=" ")=>{if(t.length>1)throw new Error(`invalid value, ${i} expects its 'pad' parameter to be a valid string with a single codepoint`);return P(e),t},ie=(i,e,t)=>(t=re("pad_left",e,t),i&&i.padStart(e,t)||""),se=(i,e,t)=>(t=re("pad_right",e,t),i&&i.padEnd(e,t)||""),oe=(i,e,t,n)=>{if(n===0)return i;if(!n)return i.split(e).join(t);for(P(n);n-- >0&&i.includes(e);)i=i.replace(e,t);return i},ue=(i,e,t)=>{if(i.length==0&&e.length===0)return [];if(t==null)return i.split(e);if(P(t),t===0)return [i];let n=i.split(e);return [...n.slice(0,t),n.slice(t).join(e)]},ae=(i,e)=>k(V(i,e),e),k=(i,e)=>ce(i,t=>new RegExp(`^[${t}]*(.*?)`),e),V=(i,e)=>ce(i,t=>new RegExp(`(.*?)[${t}]*$`),e),ce=(i,e,t)=>{let n=t?t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return i.replace(e(n),"$1")},pe=i=>i.toUpperCase();var O=class i{constructor(e){c(this,"_text");this._text=e;}get string(){return this._text}get length(){let e=0;for(let t of this._text)e+=1;return e}compareTo(e){return i.compare(this,new i(e))}static get comparer(){return (t,n)=>new i(t).compareTo(n)}static compare(e,t){let n=e.codePoints,r=t.codePoints;for(let s=0;s<Math.min(n.length,r.length);s++)if(n[s]!==r[s])return n[s]-r[s]>0?1:-1;return n.length-r.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){return [...this._text].map(t=>t.codePointAt(0))}};var M=i=>([e])=>i(e),le=i=>([e])=>i(e),he=i=>([e])=>i(e),Se={8:0,10:4,9:2,11:3},w=class{constructor(e){c(this,"_interpreter");c(this,"_functionTable");c(this,"_customFunctions",new Set);c(this,"TYPE_NAME_TABLE",Object.freeze({0:"number",1:"any",2:"string",3:"array",4:"object",5:"boolean",6:"expression",7:"null",8:"Array<number>",10:"Array<object>",9:"Array<string>",11:"Array<Array<any>>"}));c(this,"functionAvg",([e])=>{if(!e||e.length==0)return null;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n];return t/e.length});c(this,"functionContains",([e,t])=>{if(Array.isArray(e))return e.includes(t);if(typeof e=="string"){let n=e;if(typeof t=="string")return n.includes(t)}return null});c(this,"functionEndsWith",([e,t])=>e.endsWith(t));c(this,"functionFindFirst",this.createFindFunction(ee));c(this,"functionFindLast",this.createFindFunction(te));c(this,"functionFromItems",([e])=>{for(let t of e)if(t.length!==2||typeof t[0]!="string")throw new Error("invalid value, each array must contain two elements, a pair of string and value");return Object.fromEntries(e)});c(this,"functionGroupBy",([e,t])=>{let n=this.createKeyFunction(t,[2]),r={};for(let s of e){let o=n(s);r[o]||(r[o]=[]),r[o].push(s);}return r});c(this,"functionItems",([e])=>Object.entries(e));c(this,"functionJoin",e=>{let[t,n]=e;return n.join(t)});c(this,"functionLength",([e])=>typeof e=="string"?new O(e).length:Array.isArray(e)?e.length:Object.keys(e).length);c(this,"functionMap",([e,t])=>{if(!this._interpreter)return [];let n=[],r=this._interpreter;for(let s=0;s<t.length;s+=1)n.push(r.visit(e,t[s]));return n});c(this,"functionMax",([e])=>{if(!e.length)return null;if(this.getTypeName(e[0])===0)return Math.max(...e);let n=e,r=n[0];for(let s=1;s<n.length;s+=1)r.localeCompare(n[s])<0&&(r=n[s]);return r});c(this,"functionMaxBy",e=>{let t=e[1],n=e[0],r=this.createKeyFunction(t,[0,2]),s=-1/0,o,u;for(let a=0;a<n.length;a+=1)u=r&&r(n[a]),u!==void 0&&u>s&&(s=u,o=n[a]);return o||null});c(this,"functionMerge",e=>Object.assign({},...e));c(this,"functionMin",([e])=>{if(!e.length)return null;if(this.getTypeName(e[0])===0)return Math.min(...e);let n=e,r=n[0];for(let s=1;s<n.length;s+=1)n[s].localeCompare(r)<0&&(r=n[s]);return r});c(this,"functionMinBy",e=>{let t=e[1],n=e[0],r=this.createKeyFunction(t,[0,2]),s=1/0,o,u;for(let a=0;a<n.length;a+=1)u=r&&r(n[a]),u!==void 0&&u<s&&(s=u,o=n[a]);return o||null});c(this,"functionNotNull",e=>e.find(t=>t!==null)??null);c(this,"functionPadLeft",this.createPadFunction(ie));c(this,"functionPadRight",this.createPadFunction(se));c(this,"functionReplace",e=>{let t=e[0],n=e[1],r=e[2];return oe(t,n,r,e.length>3?e[3]:void 0)});c(this,"functionSplit",e=>{let t=e[0],n=e[1];return ue(t,n,e.length>2?e[2]:void 0)});c(this,"functionReverse",([e])=>{if(this.getTypeName(e)===2)return new O(e).reverse();let n=[...e];return n.reverse(),n});c(this,"functionSort",([e])=>e.length<=1?e:typeof e[0]=="string"?[...e].sort(O.comparer):[...e].sort());c(this,"functionSortBy",e=>{let t=[...e[0]];if(t.length<=1)return t;let n=this._interpreter,r=e[1],s=this.getTypeName(n.visit(r,t[0]));if(s!==void 0&&![0,2].includes(s))throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[s]})`);function o(u,a){throw new Error(`Invalid type: expected (${u.TYPE_NAME_TABLE[s]}), received ${u.TYPE_NAME_TABLE[u.getTypeName(a)]}`)}return t.sort((u,a)=>{let p=n.visit(r,u),l=n.visit(r,a);return this.getTypeName(p)!==s?o(this,p):this.getTypeName(l)!==s&&o(this,l),s===2?O.comparer(p,l):p-l})});c(this,"functionStartsWith",([e,t])=>e.startsWith(t));c(this,"functionSum",([e])=>e.reduce((t,n)=>t+n,0));c(this,"functionToArray",([e])=>Array.isArray(e)?e:[e]);c(this,"functionToNumber",([e])=>{let t=this.getTypeName(e),n;return t===0?e:t===2&&(n=+e,!isNaN(n))?n:null});c(this,"functionToString",([e])=>typeof e=="string"?e:JSON.stringify(e));c(this,"functionTrim",this.createTrimFunction(ae));c(this,"functionTrimLeft",this.createTrimFunction(k));c(this,"functionTrimRight",this.createTrimFunction(V));c(this,"functionType",([e])=>{let t=this.getTypeName(e),n=t!==void 0?this.TYPE_NAME_TABLE[t]:void 0;if(!n)throw new Error("invalid-type");return n});c(this,"functionZip",e=>{let t=Math.min(...e.map(n=>n.length));return Array.from({length:t},(n,r)=>e.map(s=>s[r]))});this._interpreter=e,this._functionTable=this.buildFunctionTable();}buildFunctionTable(){return {abs:{_func:M(Math.abs),_signature:[{types:[0]}]},ceil:{_func:M(Math.ceil),_signature:[{types:[0]}]},floor:{_func:M(Math.floor),_signature:[{types:[0]}]},lower:{_func:le(ne),_signature:[{types:[2]}]},upper:{_func:le(pe),_signature:[{types:[2]}]},keys:{_func:he(Object.keys),_signature:[{types:[4]}]},values:{_func:he(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[3],variadic:true}]}}}registerFunction(e,t,n,r){let s=this._registerInternal(e,t,n,r);if(!s.success)throw new Error(s.message)}_registerInternal(e,t,n,r={}){if(!e||typeof e!="string"||e.trim()==="")return {success:false,reason:"invalid-name",message:"Function name must be a non-empty string"};try{this.validateInputSignatures(e,n);}catch(p){return {success:false,reason:"invalid-signature",message:p instanceof Error?p.message:"Invalid function signature"}}let{override:s=false,warn:o=false}=r,u=e in this._functionTable;return u&&!s?{success:false,reason:"already-exists",message:`Function already defined: ${e}(). Use { override: true } to replace it.`}:(u&&s&&o&&console.warn(`Warning: Overriding existing function: ${e}()`),this._functionTable[e]={_func:t.bind(this),_signature:n},this._customFunctions.add(e),{success:true,message:u?`Function ${e}() overridden successfully`:`Function ${e}() registered successfully`})}register(e,t,n,r={}){return this._registerInternal(e,t,n,r)}unregister(e){return this._customFunctions.has(e)?(delete this._functionTable[e],this._customFunctions.delete(e),true):false}isRegistered(e){return e in this._functionTable}getRegistered(){return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(let e of this._customFunctions)delete this._functionTable[e];this._customFunctions.clear();}callFunction(e,t){let n=this._functionTable[e];if(n===void 0)throw new Error(`Unknown function: ${e}()`);return this.validateArgs(e,t,n._signature),n._func.call(this,t)}validateInputSignatures(e,t){for(let n=0;n<t.length;n+=1)if("variadic"in t[n]&&n!==t.length-1)throw new Error(`Invalid arity: ${e}() 'variadic' argument ${n+1} must occur last`)}validateArgs(e,t,n){this.validateInputSignatures(e,n),this.validateArity(e,t,n),this.validateTypes(e,t,n);}validateArity(e,t,n){let r=n.filter(a=>!(a.optional??false)).length,s=n[n.length-1]?.variadic??false,o=t.length<r,u=t.length>n.length;if(s&&o||!s&&(o||u)){let a=o&&(!s&&r>1||s)?"at least ":"",p=n.length>1;throw new Error(`Invalid arity: ${e}() takes ${a}${r} argument${p&&"s"||""} but received ${t.length}`)}}validateTypes(e,t,n){for(let r=0;r<n.length;r+=1){let s=n[r].types,o=this.getTypeName(t[r]);if(o===void 0)continue;if(!s.some(a=>this.typeMatches(o,a,t[r]))){let a=s.map(p=>this.TYPE_NAME_TABLE[p]).join(" | ");throw new Error(`Invalid type: ${e}() expected argument ${r+1} to be type (${a}) but received type ${this.TYPE_NAME_TABLE[o]} instead.`)}}}typeMatches(e,t,n){if(t===1)return true;let r=Se[t];return r!==void 0?e!==3?false:n.every(o=>{let u=this.getTypeName(o);return u===void 0||this.typeMatches(u,r,o)}):e===t}getTypeName(e){if(e===null)return 7;if(typeof e=="string")return 2;if(typeof e=="number")return 0;if(typeof e=="boolean")return 5;if(Array.isArray(e))return 3;if(typeof e=="object")return e.expref?6:4}createKeyFunction(e,t){let n=this._interpreter;return s=>{let o=n.visit(e,s);if(!t.includes(this.getTypeName(o))){let u=`Invalid type: expected one of (${t.map(a=>this.TYPE_NAME_TABLE[a]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(o)]}`;throw new Error(u)}return o}}createFindFunction(e){return t=>{let n=t[0],r=t[1],s=t.length>2?t[2]:void 0,o=t.length>3?t[3]:void 0;return e(n,r,s,o)}}createPadFunction(e){return t=>{let n=t[0],r=t[1],s=t.length>2?t[2]:void 0;return e(n,r,s)}}createTrimFunction(e){return t=>{let n=t[0],r=t.length>1?t[1]:void 0;return e(n,r)}}};var E=class i{constructor(){c(this,"inner");c(this,"data",{});}get currentScopeData(){return this.data}withScope(e){let t=new i;return t.inner=this,t.data=e,t}getValue(e){return Object.prototype.hasOwnProperty.call(this.data,e)?this.data[e]:this.inner?this.inner.getValue(e):null}};var Re=new E,S=class i{constructor(e){c(this,"runtime");c(this,"_rootValue",null);c(this,"_scope");c(this,"_options");c(this,"_depth",0);c(this,"_deadline",0);this.runtime=new w(this),this._scope=new E,e&&(this._options=e,this._deadline=e.timeoutMs!==void 0?Date.now()+e.timeoutMs:0);}withScope(e){let t=new i(this._options);return t.runtime._functionTable=this.runtime._functionTable,t._rootValue=this._rootValue,t._scope=this._scope.withScope(e),t._depth=this._depth,t._deadline=this._deadline,t}search(e,t,n){if(n?.maxNodes!==void 0&&x(e)>n.maxNodes)throw new Error(`Expression exceeds maximum allowed node count of ${n.maxNodes}`);this._rootValue=t,this._scope=Re,this._options=n,this._depth=0,this._deadline=n?.timeoutMs!==void 0?Date.now()+n.timeoutMs:0;let r=this.visit(e,t);return this.checkOutputSize(r),r}checkOutputSize(e){let t=this._options?.maxOutputSize;if(t===void 0||e==null)return;if((Array.isArray(e)||typeof e=="string"?e.length:typeof e=="object"?Object.keys(e).length:0)>t)throw new Error(`Output size exceeds maximum allowed size of ${t}`)}collect(e,t){if(e.push(t),this._options?.maxOutputSize!==void 0&&e.length>this._options.maxOutputSize)throw new Error(`Output size exceeds maximum allowed size of ${this._options.maxOutputSize}`)}evaluateProjectionItems(e,t){let n=[];if(t.type==="Field"){let r=t.name;for(let s=0;s<e.length;s++){if(this._deadline>0&&Date.now()>=this._deadline)throw new Error(`Query execution timed out after ${this._options?.timeoutMs}ms`);let o=e[s];if(!o||typeof o!="object"||Array.isArray(o))continue;let u=o[r];u!=null&&this.collect(n,u);}return n}if(t.type==="Identity"){for(let r=0;r<e.length;r++){let s=e[r];s!==null&&this.collect(n,s);}return n}for(let r of e){let s=this.visit(t,r);s!==null&&this.collect(n,s);}return n}visit(e,t){if(this._options){if(this._options.maxDepth!==void 0&&this._depth>=this._options.maxDepth)throw new Error(`Evaluation exceeds maximum allowed depth of ${this._options.maxDepth}`);if(this._deadline>0&&Date.now()>=this._deadline)throw new Error(`Query execution timed out after ${this._options.timeoutMs}ms`)}this._depth+=1;try{return this.evaluateNode(e,t)}finally{this._depth-=1;}}evaluateNode(e,t){switch(e.type){case "Ternary":{let r=this.visit(e.condition,t);return d(r)?this.visit(e.falseExpr,t):this.visit(e.trueExpr,t)}case "Field":let n=e.name;return t===null||typeof t!="object"||Array.isArray(t)?null:t[n]??null;case "LetExpression":{let r={};for(let s of e.bindings)Object.assign(r,this.visit(s,t));return this.withScope(r).visit(e.expression,t)}case "Binding":{let{variable:r,reference:s}=e,o=this.visit(s,t);return {[r]:o}}case "Variable":{let r=e.name;if(!this._scope.getValue(r)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,r))throw new Error(`Error referencing undefined variable ${r}`);return this._scope.getValue(r)}case "IndexExpression":return this.visit(e.right,this.visit(e.left,t));case "Subexpression":{let r=this.visit(e.left,t);return r!=null?this.visit(e.right,r)??null:null}case "Index":{if(!Array.isArray(t))return null;let r=e.value<0?t.length+e.value:e.value;return t[r]??null}case "Slice":{if(!Array.isArray(t)&&typeof t!="string")return null;let{start:r,stop:s,step:o}=this.computeSliceParams(t.length,e),u=typeof t=="string"?[...t]:t,a=this.slice(u,r,s,o),p=typeof t=="string"?a.join(""):a;return this.checkOutputSize(p),p}case "Projection":{let{left:r,right:s}=e,o=r.type==="IndexExpression"&&r.right.type==="Slice",u=this.visit(r,t);return o&&typeof u=="string"?this.visit(s,u):Array.isArray(u)?this.evaluateProjectionItems(u,s):null}case "ValueProjection":{let r=this.visit(e.left,t);return r===null||typeof r!="object"||Array.isArray(r)?null:this.evaluateProjectionItems(Object.values(r),e.right)}case "FilterProjection":{let{left:r,right:s,condition:o}=e,u=this.visit(r,t);if(!Array.isArray(u))return null;let a=[];if(s.type==="Field"){let p=s.name;for(let l=0;l<u.length;l++){let m=u[l];if(d(this.visit(o,m))||!m||typeof m!="object"||Array.isArray(m))continue;let f=m[p];f!=null&&this.collect(a,f);}return a}if(s.type==="Identity"){for(let p=0;p<u.length;p++){let l=u[p];d(this.visit(o,l))||l!==null&&this.collect(a,l);}return a}for(let p of u){if(d(this.visit(o,p)))continue;let l=this.visit(s,p);l!==null&&this.collect(a,l);}return a}case "Arithmetic":{let r=this.visit(e.left,t),s=this.visit(e.right,t);switch(e.operator){case "Plus":return $(r,s);case "Minus":return z(r,s);case "Multiply":case "Star":return Q(r,s);case "Divide":return H(r,s);case "Modulo":return q(r,s);case "Div":return X(r,s);default:throw new Error(`Syntax error: unknown arithmetic operator: ${e.operator}`)}}case "Unary":{let r=this.visit(e.operand,t);switch(e.operator){case "Plus":return _(r),r;case "Minus":return _(r),-r;default:throw new Error(`Syntax error: unknown arithmetic operator: ${e.operator}`)}}case "Comparator":{let r=this.visit(e.left,t),s=this.visit(e.right,t);switch(e.name){case "EQ":return y(r,s);case "NE":return !y(r,s)}if(typeof r!="number"||typeof s!="number")return null;switch(e.name){case "GT":return r>s;case "GTE":return r>=s;case "LT":return r<s;case "LTE":return r<=s}}case "Flatten":{let r=this.visit(e.child,t),s=Array.isArray(r)?r.flat():null;return this.checkOutputSize(s),s}case "Root":return this._rootValue;case "MultiSelectList":{let r=[];for(let s of e.children)r.push(this.visit(s,t));return this.checkOutputSize(r),r}case "MultiSelectHash":{let r={};for(let s of e.children)r[s.name]=this.visit(s.value,t);return this.checkOutputSize(r),r}case "OrExpression":{let r=this.visit(e.left,t);return d(r)?this.visit(e.right,t):r}case "AndExpression":{let r=this.visit(e.left,t);return d(r)?r:this.visit(e.right,t)}case "NotExpression":return d(this.visit(e.child,t));case "Literal":return e.value;case "Pipe":return this.visit(e.right,this.visit(e.left,t));case "Function":{if(this._options?.allowedFunctions&&!this._options.allowedFunctions.includes(e.name))throw new Error(`Function '${e.name}' is not allowed`);if(this._options?.disallowedFunctions&&this._options.disallowedFunctions.includes(e.name))throw new Error(`Function '${e.name}' is disallowed`);let r=[];for(let o of e.children)r.push(this.visit(o,t));let s=this.runtime.callFunction(e.name,r);return this.checkOutputSize(s),s}case "ExpressionReference":return {expref:true,...e.child};case "Current":case "Identity":return t}}computeSliceParams(e,t){let{start:n,stop:r,step:s}=t;if(s===null)s=1;else if(s===0){let o=new Error("Invalid value: slice step cannot be 0");throw o.name="RuntimeError",o}return n=n===null?s<0?e-1:0:this.capSliceRange(e,n,s),r=r===null?s<0?-1:e:this.capSliceRange(e,r,s),{start:n,stop:r,step:s}}capSliceRange(e,t,n){let r=t;return r<0?(r+=e,r<0&&(r=n<0?-1:0)):r>=e&&(r=n<0?e-1:e),r}slice(e,t,n,r){if(r===1)return e.slice(t,n);let s=Math.ceil(Math.abs(t-n)/Math.abs(r)),o=new Array(s),u=0;if(r>0)for(let a=t;a<n;a+=r)o[u++]=e[a];else for(let a=t;a>n;a+=r)o[u++]=e[a];return o}},C=new S,T=C;async function*Ae(i){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Invalid stream source: expected AsyncIterable, Iterable, or ReadableStream");if(Symbol.asyncIterator in i){for await(let e of i)yield e;return}if(typeof i.getReader=="function"){let e=i.getReader();try{for(;;){let{done:t,value:n}=await e.read();if(t)break;yield n;}}finally{e.releaseLock();}return}if(Symbol.iterator in i){for(let e of i)yield e;return}throw new TypeError("Invalid stream source: expected AsyncIterable, Iterable, or ReadableStream")}}function R(i,e){if(e===true)return JSON.parse(i);if(e==="auto")try{return JSON.parse(i)}catch{return i}return i}async function*xe(i,e){let t=e?.parseJson??"auto",n=e?.flattenChunks??true,r="",s=typeof TextDecoder<"u"?new TextDecoder:null;for await(let o of Ae(i))if(o instanceof Uint8Array&&s){if(r+=s.decode(o,{stream:true}),r.includes(`
|
|
2
|
+
`)){let u=r.split(`
|
|
3
|
+
`);r=u.pop()??"";for(let a of u){let p=a.trim();p&&(yield R(p,t));}}}else if(typeof o=="string"){if(t===false)yield o;else if(r+=o,r.includes(`
|
|
4
|
+
`)){let u=r.split(`
|
|
5
|
+
`);r=u.pop()??"";for(let a of u){let p=a.trim();p&&(yield R(p,t));}}}else if(n&&Array.isArray(o)){r.trim()&&(yield R(r.trim(),t),r="");for(let u=0;u<o.length;u++)yield o[u];}else r.trim()&&(yield R(r.trim(),t),r=""),yield o;s&&r&&(r+=s.decode()),r.trim()&&(yield R(r.trim(),t));}function Y(i){switch(i.type){case "Projection":if(i.left.type==="Identity"||i.left.type==="Current")return true;if(i.left.type==="IndexExpression"&&i.left.right.type==="Slice"){let e=i.left.right;return (e.start===null||e.start>=0)&&(e.stop===null||e.stop>=0)&&(e.step===null||e.step>0)}return false;case "FilterProjection":return i.left.type==="Identity"||i.left.type==="Current";case "IndexExpression":if(i.right.type==="Slice"&&(i.left.type==="Identity"||i.left.type==="Current")){let e=i.right;return (e.start===null||e.start>=0)&&(e.stop===null||e.stop>=0)&&(e.step===null||e.step>0)}return true;case "Field":case "Identity":case "Current":case "Subexpression":case "MultiSelectHash":case "MultiSelectList":case "Ternary":case "Comparator":case "Arithmetic":case "NotExpression":return true;case "Pipe":return Y(i.left)&&Y(i.right);default:return false}}async function*K(i,e,t,n){let r=n?.timeoutMs!==void 0?Date.now()+n.timeoutMs:0;function s(){if(r>0&&Date.now()>=r)throw new Error(`Query execution timed out after ${n?.timeoutMs}ms`)}switch(e.type){case "Projection":{let{left:o,right:u}=e,a=i;if(o.type==="IndexExpression"&&o.right.type==="Slice"&&(a=K(i,o,t,n)),u.type==="Identity"||u.type==="Current"){for await(let p of a)s(),p!=null&&(yield p);return}if(u.type==="Field"){let p=u.name;for await(let l of a)if(s(),l&&typeof l=="object"&&!Array.isArray(l)){let m=l[p];m!=null&&(yield m);}return}for await(let p of a){s();let l=t.visit(u,p);l!=null&&(yield l);}return}case "IndexExpression":{if(e.right.type==="Slice"&&(e.left.type==="Identity"||e.left.type==="Current")){let o=e.right,u=o.start??0,a=o.stop??1/0,p=o.step??1;if(u>=0&&a>=0&&p>0){let f=0;for await(let me of i)if(s(),f>=a||(f>=u&&(f-u)%p===0&&(yield me),f++,f>=a))break;return}let l=[];for await(let f of i)if(s(),l.push(f),n?.maxOutputSize!==void 0&&l.length>n.maxOutputSize)throw new Error(`Output size exceeds maximum allowed size of ${n.maxOutputSize}`);let m=t.search(e,l,n);if(Array.isArray(m))for(let f of m)yield f;return}for await(let o of i){s();let u=t.visit(e,o);u!=null&&(yield u);}return}case "FilterProjection":{let{condition:o,right:u}=e;if(u.type==="Identity"||u.type==="Current"){for await(let a of i)s(),d(t.visit(o,a))||(yield a);return}if(u.type==="Field"){let a=u.name;for await(let p of i)if(s(),!d(t.visit(o,p))&&p&&typeof p=="object"&&!Array.isArray(p)){let l=p[a];l!=null&&(yield l);}return}for await(let a of i)if(s(),!d(t.visit(o,a))){let p=t.visit(u,a);p!=null&&(yield p);}return}case "Pipe":{let o=K(i,e.left,t,n);if(Y(e.right))for await(let u of K(o,e.right,t,n))yield u;else {let u=[];for await(let p of o)if(s(),u.push(p),n?.maxOutputSize!==void 0&&u.length>n.maxOutputSize)throw new Error(`Output size exceeds maximum allowed size of ${n.maxOutputSize}`);let a=t.search(e.right,u,n);a!=null&&(yield a);}return}case "Identity":case "Current":{for await(let o of i)s(),yield o;return}case "Field":{let o=e.name;for await(let u of i)if(s(),u&&typeof u=="object"&&!Array.isArray(u)){let a=u[o];a!=null&&(yield a);}return}default:{if(Y(e)){for await(let a of i){s();let p=t.visit(e,a);p!=null&&(yield p);}return}let o=[];for await(let a of i)if(s(),o.push(a),n?.maxOutputSize!==void 0&&o.length>n.maxOutputSize)throw new Error(`Output size exceeds maximum allowed size of ${n.maxOutputSize}`);let u=t.search(e,o,n);u!=null&&(yield u);return}}}function fe(i){return typeof i=="object"&&i!==null&&"type"in i&&typeof i.type=="string"&&!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i)}async function*B(i,e,t){let n,r;if(typeof i=="string"||fe(i)?(n=i,r=e):(r=i,n=e),typeof n!="string"&&!fe(n))throw new TypeError("Expression must be a string or AST ExpressionNode");let s=typeof n=="string"?g.parse(n,t):n;if(t){let f=I(s,t);if(f)throw new Error(f)}let o=new S(t);o.runtime._functionTable=C.runtime._functionTable;let u=xe(r,t),a=K(u,s,o,t),p=t?.limit,l=t?.maxOutputSize,m=0;for await(let f of a){if(yield f,m++,p!==void 0&&m>=p)break;if(l!==void 0&&m>l)throw new Error(`Output size exceeds maximum allowed size of ${l}`)}}var Ie=1,be=3,Pe=11,ve=8,we=10,Ke=9,Ye=5,Fe=6,Je=7,Le=0,ke=4,Ve=2;function Me(i,e){return g.parse(i,e)}function Ce(i,e){let t=g.parse(i,e),n=function(r){return T.search(t,r,e)};return n.search=r=>T.search(t,r,e),n.searchStream=(r,s)=>B(r,t,{...e,...s}),n.ast=t,n}function Be(i,e){if(typeof i!="string")return {valid:false,error:"Expression must be a string"};try{let t=g.parse(i,e);if(e){let n=I(t,e);if(n)return {valid:!1,error:n}}return {valid:!0,ast:t}}catch(t){return {valid:false,error:t instanceof Error?t.message:String(t)}}}function Ue(i,e){return v.tokenize(i,e)}var De=(i,e,t,n)=>{T.runtime.registerFunction(i,e,t,n);},je=(i,e,t,n)=>T.runtime.register(i,e,t,n),Ge=i=>T.runtime.unregister(i),$e=i=>T.runtime.isRegistered(i),ze=()=>T.runtime.getRegistered(),Qe=()=>T.runtime.getCustomFunctions(),He=()=>{T.runtime.clearCustomFunctions();},Xe=1e3,A=new Map;function qe(i,e,t){let n;if(t)n=g.parse(e,t);else if(n=A.get(e),!n){if(n=g.parse(e),A.size>=Xe){let r=A.keys().next().value;r!==void 0&&A.delete(r);}A.set(e,n);}return T.search(n,i,t)}function We(){return new E}var Ze=T,et={compile:Me,compileQuery:Ce,searchStream:B,validate:Be,registerFunction:De,register:je,unregisterFunction:Ge,isRegistered:$e,getRegisteredFunctions:ze,getCustomFunctions:Qe,clearCustomFunctions:He,search:qe,tokenize:Ue,TreeInterpreter:Ze,TYPE_ANY:Ie,TYPE_ARRAY_NUMBER:ve,TYPE_ARRAY_STRING:Ke,TYPE_ARRAY:be,TYPE_BOOLEAN:Ye,TYPE_EXPREF:Fe,TYPE_NULL:Je,TYPE_NUMBER:Le,TYPE_OBJECT:ke,TYPE_STRING:Ve,TYPE_ARRAY_ARRAY:Pe,TYPE_ARRAY_OBJECT:we,Scope:We},qt=et;export{qt as default};//# sourceMappingURL=index.esm.min.js.map
|
|
2
6
|
//# sourceMappingURL=index.esm.min.js.map
|