fig-tree-evaluator 2.22.0 → 2.22.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  The format below (from v2.21.4 onwards) is loosely based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
4
4
 
5
+ ## [2.22.1] - 2026-06-30
6
+
7
+ ### Fixed
8
+
9
+ - `convertToShorthand` now handles operator nodes in the positional `children` array form (previously emitted verbatim).
10
+ - `convertToShorthand` of `buildObject` now uses the array form regardless of whether the input uses the `properties` or `values` parameter name.
11
+
5
12
  ## [2.22.0] - 2026-06-29
6
13
 
7
14
  ### Changed
@@ -1 +1 @@
1
- "use strict";var e=require("object-property-extractor"),r=require("dequal/lite");const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},i=(e,r)=>r[s(e)],n=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),p=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,c=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},g=y,v=(e,r={},t,a=!0)=>a&&f(e)?b(e,r,t):e,b=(e,r,s)=>{if(t(e)||a(e))return e;const i=Object.entries(e),n=i.filter((([e])=>u(e))),o=i.filter((([e])=>!u(e)));return{...n.reduce(((e,[t,a])=>e={...e,...T(t,a,r,s)}),{}),...Object.fromEntries(o)}},T=(e,r,t,a)=>{const s=e.slice(1),n=i(s,g);return n?Array.isArray(r)?{operator:n,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:n,...r}:{operator:n,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class w extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),i=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===i?"":i}`}}const C=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:i=!1})=>{if(void 0!==e)return e;if(a instanceof w){if(!i)throw a;return a.prettyPrint}const n=new w("string"==typeof a?new Error(a):a,r,t,s);if(i)return n.prettyPrint;throw n},E=e=>f(e)&&"literal"in e,A=({value:e,name:r,expectedType:t})=>{if(E(t)){const{literal:a}=t;return!!a.includes(e)||O(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===A({value:e,name:r,expectedType:t})))||O(r,e,t.join("|"));return!!(0,q[t])(e)||O(r,e,t)},S=(...e)=>{const r=[];return e.forEach((e=>{const t=A(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},q={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},O=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${x(r)}) is not of type: ${t}`:`- ${x(r)} is not of type: ${t}`,x=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},N=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},P=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(E(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const i=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:i}})),j=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},L=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=S(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},k=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,I=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>k(e))):t?null===s?null:k(s):s},U=e=>/^https?:\/\/.+/.test(e),R=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,i=r.slice(a,s);return""===i?e:e+(0===t?"":"/")+i}),""),D=async(e,r)=>{const{url:t,params:a={},data:s={},headers:i={},method:n="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[n]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...i},params:a,data:s})}catch(r){e.throwError(r)}},Q=async(e,r)=>{const{options:s,operators:n,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const c=Object.keys(r.options?.functions??{});u=v(u,r.options?.fragments,c,!s.noShorthand),Array.isArray(u)&&(u=await _(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:i,useCache:n,input:o,args:l,...u}=e,p={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(p.fallback=a),void 0!==s&&(p.outputType=s),void 0!==i&&(p.type=i),void 0!==n&&(p.useCache=n),void 0!==l&&(p.args=l),void 0!==o?p.input=o:Object.keys(u).length>0&&(p.input=u),p})(u,r)),s.evaluateFullObject&&!h&&!m)return p(await $(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:p(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[i,n]=await _([e.fragment,e.parameters],r),o=v(s?.fragments?.[i],s.fragments,c,!s.noShorthand);if(void 0===o)return C({fallback:await Q(y,r),error:`Fragment not defined: ${i}`,expression:u,returnErrorAsString:g});if(!t(o))return p(o,r);u={...e,...o,...n},delete u.fragment}const b=u,T=i(b.operator,o);if(!T)return C({fallback:await Q(y,r),error:`Invalid operator: ${b.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return C({fallback:await Q(y,r),error:`Excluded operator: ${b.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:E,parseChildren:A}=n[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,b);const q=await F(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await Q(S.children,O)),!Array.isArray(S.children))return C({fallback:await Q(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=A(S,O),delete S.children}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let x;try{x=await E(S,O)}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const N=S?.outputType??S?.type;if(!N)return x;const P=await Q(N,r);return P in d?d[P](x):C({fallback:await Q(y,r),operator:T,error:`- Invalid output type: ${P}`,expression:S,returnErrorAsString:g})},_=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>Q(e,r)))):await Q(e,r),F=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push(Q(e[t],r))));const s=await Promise.all(a),i=j(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(i[t[e]]=i?.[r]??r);return i},$=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=v(e,r.options?.fragments,t);if(!f(a))return e;const s=[],i=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(i.push(e,Q(t,r)),delete a[e])}));const n=await Promise.all(i);r.resolvedAliasNodes={...r.resolvedAliasNodes,...L(n)},Object.entries(a).forEach((([e,t])=>{s.push(e,Q(t,r))}));const o=await Promise.all(s);return p(L(o),r)},H=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],M=N(H),G={description:"Logical AND",aliases:["and","&","&&"],parameters:H},B=e=>{const r=e.children;return{...e,values:r}},z={propertyAliases:M,operatorData:G,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(G.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:B},W=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],J=N(W),V={description:"Logical OR",aliases:["or","|","||"],parameters:W},Y={propertyAliases:J,operatorData:V,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(V.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:B},X=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Z=N(X),K={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:X},ee={propertyAliases:Z,operatorData:K,evaluate:async(e,t)=>{const[a,s,i]=await _([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(P(K.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.every((e=>r.dequal(e,n[0]))):n.every((e=>null==e))},parseChildren:B},re=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],te=N(re),ae={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:re},se={propertyAliases:te,operatorData:ae,evaluate:async(e,t)=>{const[a,s,i]=await _([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(P(ae.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.some((e=>!r.dequal(e,n[0]))):n.some((e=>null===e&&void 0===e))},parseChildren:B},ie=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],ne=N(ie),oe={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:ie},le={propertyAliases:ne,operatorData:oe,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(oe.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:B},ue=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],pe=N(ue),ce={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:ue},de={propertyAliases:pe,operatorData:ce,evaluate:async(e,r)=>{const[t,a,s]=await _([e.values,e.from,e.subtract],r);r.typeChecker(P(ce.parameters,{values:t,from:a,subtract:s}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return i[0]-i[1]},parseChildren:B},he=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],me=N(he),fe={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:he},ye={propertyAliases:me,operatorData:fe,evaluate:async(e,r)=>{const t=await _(e.values,r);if(r.typeChecker(P(fe.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:B},ge=[{name:"values",description:"Array of values - 1st element will be divided by the first",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder"]},default:"quotient"}],ve=N(ge),be={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:ge},Te={propertyAliases:ve,operatorData:be,evaluate:async(e,r)=>{const[t,a,s,i]=await _([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(P(be.parameters,{values:t,dividend:a,divisor:s,output:i}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===n[1])throw new Error("Division by zero!");switch(i){case"quotient":return Math.floor(n[0]/n[1]);case"remainder":return n[0]%n[1];default:return n[0]/n[1]}},parseChildren:B},we=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ce=N(we),Ee={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:we},Ae={propertyAliases:Ce,operatorData:Ee,evaluate:async(e,r)=>{const[t,a=!0]=await _([e.values,e.strict],r);if(r.typeChecker(P(Ee.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s>i},parseChildren:B},Se=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],qe=N(Se),Oe={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Se},xe={propertyAliases:qe,operatorData:Oe,evaluate:async(e,r)=>{const[t,a=!0]=await _([e.values,e.strict],r);if(r.typeChecker(P(Oe.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s<i},parseChildren:B},Ne=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],Pe=N(Ne),je={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:Ne},Le={propertyAliases:Pe,operatorData:je,evaluate:async(e,r)=>{r.typeChecker(P(je.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await Q(e.condition,r)?await Q(e.valueIfTrue,r):await Q(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},ke=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Ie=N(ke),Ue={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:ke},Re={propertyAliases:Ie,operatorData:Ue,evaluate:async(e,r)=>{const[t,a]=await _([e.testString,e.pattern],r);r.typeChecker(P(Ue.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},De=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],Qe=N(De),_e={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:De},Fe={propertyAliases:Qe,operatorData:_e,evaluate:async(r,t)=>{const[a,s={}]=await _([r.property,r.additionalData],t);t.typeChecker(P(_e.parameters,{property:a,additionalData:s}));const i={...t.options?.data??{},...s};return e(i,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},$e=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],He=N($e),Me={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:$e},Ge={propertyAliases:He,operatorData:Me,evaluate:async(e,r)=>{const[t,a={},s=!0,i="%",n={}]=await _([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(P(Me.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:i,numberMapping:n})),Array.isArray(a)){const e="$"===i?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),n=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(n),l=j(Array.from(o),a.map((e=>s?String(e).trim():e)));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(`\\${e}`,e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace("\\{{","{{"));continue}const t=await Be(e,a,n,r);l.push(s?String(t).trim():t)}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},Be=async(r,t,a,s)=>{const i=s.options?.data??{},n=r.replace(/{{(.+)}}/,"$1"),o=await Q(e(t,n,e(i,n,"")),s);if("number"!=typeof o)return o;if(!(n in a))return o;const l=a[n];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[n]),p=u.find((e=>e.startsWith(">")));if(p){if(o>Number(p.slice(1)))return l?.[p]}const c=u.find((e=>e.startsWith("<")));if(c){if(o<Number(c.slice(1)))return l?.[c]}return l.other?l.other.replace("{}",String(o)):o},ze=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],We=N(ze),Je={description:"Count elements in an array",aliases:["count","length"],parameters:ze},Ve={propertyAliases:We,operatorData:Je,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(Je.parameters,{values:t})),t.length},parseChildren:B},Ye=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],Xe=N(Ye),Ze={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Ye},Ke=" ",er={propertyAliases:Xe,operatorData:Ze,evaluate:async(e,r)=>{const[t,a,s,i]=await _([e.value,e.delimiter??Ke,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(P(Ze.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:i}));let n=t.split(a);return s&&(n=n.map((e=>e.trim()))),i&&""===n[n.length-1]&&n.pop(),n},parseChildren:e=>{const[r,t=Ke]=e.children;return{...e,value:r,delimiter:t}}},rr=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],tr=N(rr),ar={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:rr},sr={propertyAliases:tr,operatorData:ar,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,i,n,o,l]=await _([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(P(ar.parameters,{query:a,single:i,flatten:n,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,i)=>{const n=await t.query({query:e,values:r})||[];["array","string","number"].includes(i??"")&&(s=!0);const o=s?n.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):n;return a?o[0]:o}),a,s,i,n,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},ir=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],nr=N(ir),or={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:ir},lr={propertyAliases:nr,operatorData:or,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,i,n,o,l]=await _([e.query,e.url,await $(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:p}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...P(or.parameters,{url:u,query:a,variables:i,returnNode:n,headers:o,useCache:l}),{name:"headers",value:p,expectedType:["object","null"]}]);const c=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=U(c)?c:R(d,c),m={query:a,variables:i},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const i=await D(t,{url:e,method:"post",data:r,headers:a});return I(i?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...p,...o},n);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,i=Array.isArray(a)?a:[a],n=s.slice(0,i.length),o=j(i,n),l={...e,query:r,url:t,variables:o};return s.length>i.length&&(l.returnNode=s.pop()),l}},ur=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],pr=N(ur),cr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:ur},dr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],i=a.slice(0,s.length),n=j(s,i),o={...e,url:r,parameters:n};return a.length>s.length&&(o.returnProperty=a.pop()),o},hr=dr,mr={propertyAliases:pr,operatorData:cr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await _([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...P(cr.parameters,{url:l,returnProperty:i,headers:n,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const p=r.options.baseEndpoint??"",c={...r.options?.headers,...u,...n},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await D(t,{url:e,params:r,headers:a});return I(i,s)}),U(l)?l:R(p,l),s,c,i);return h},parseChildren:dr},fr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],yr=N(fr),gr={description:"HTTP POST Request",aliases:["POST","post"],parameters:fr},vr={propertyAliases:yr,operatorData:gr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await _([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...P(gr.parameters,{url:l,headers:n,data:s,returnProperty:i,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const p=r.options.baseEndpoint??"",c={...r.options?.headers,...u,...n},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await D(t,{url:e,data:r,headers:a,method:"post"});return I(i,s)}),U(l)?l:R(p,l),s,c,i);return h},parseChildren:hr},br=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],Tr=N(br),wr={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:br},Cr=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},Er={propertyAliases:Tr,operatorData:wr,evaluate:async(e,r)=>{const t=await _(e.properties,r);r.typeChecker(P(wr.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Cr({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await _(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Cr},Ar=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],Sr={propertyAliases:N(Ar),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:Ar},evaluate:async(e,r)=>{const a=await Q(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?L(e.branches):e.branches??{},i=t(s)?await Q(s,r):s;if(!f(i))throw new Error("Branches don't evaluate to an object");if(a in i)return await Q(i[a],r);if("fallback"in i)return await Q(i.fallback,r);if(a in e)return await Q(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=L(t);return{...e,matchExpression:r,branches:a}}},qr=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],Or=N(qr),xr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:qr},Nr={propertyAliases:Or,operatorData:xr,evaluate:async(r,t)=>{const[a,s=[],i,n]=await _([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(P(xr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const p=n??t.options.useCache??!1,c=[...void 0===i?[]:[await $(i,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(p,(async(e,...r)=>await u(...r)),a,...c)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Pr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],jr=N(Pr),Lr={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Pr},kr={propertyAliases:jr,operatorData:Lr,evaluate:async(e,r)=>(r.typeChecker(P(Lr.parameters,{value:e.value})),await Q(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Ir=Object.freeze({__proto__:null,AND:z,BUILD_OBJECT:Er,CONDITIONAL:Le,COUNT:Ve,CUSTOM_FUNCTIONS:Nr,DIVIDE:Te,EQUAL:ee,GET:mr,GRAPHQL:lr,GREATER_THAN:Ae,LESS_THAN:xe,MATCH:Sr,MULTIPLY:ye,NOT_EQUAL:se,OBJECT_PROPERTIES:Fe,OR:Y,PASSTHRU:kr,PLUS:le,POST:vr,REGEX:Re,SPLIT:er,SQL:sr,STRING_SUBSTITUTION:Ge,SUBTRACT:de});class Ur{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Rr(t),s=a in this.store,i=Date.now(),n=s&&i-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=i,n&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:i},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Rr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),Dr=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?Qr(window.fetch):void 0),Qr=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,i=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",n=await e(t+i,{headers:a,method:"GET"}),o=await n.json();if(!n.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:n.status,error:n.statusText,url:n.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:i}=r,n=new URLSearchParams(s),o=n.size>0?`?${n.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(i),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class _r{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=S(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.22.0",this.options=Fr(e),this.operators=n(Ir,this.options?.excludeOperators??[],y),this.operatorAliases=y,this.cache=new Ur({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=Dr(e.graphQLConnection?.httpClient),this.httpClient=Dr(e.httpClient)}async evaluate(e,r={}){const t=c(this.options,Fr(r),!0);return r.httpClient&&(this.httpClient=Dr(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=Dr(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await Q(e,{options:t,operators:r.excludeOperators?n(Ir,r.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}getOptions(){return this.options}updateOptions(e){this.options=c(this.options,Fr(e),!1),this.options.excludeOperators&&(this.operators=n(Ir,this.options.excludeOperators,y))}getOperators(){const e=this.options.excludeOperators?n(Ir,this.options.excludeOperators,y):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(y))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:i,backgroundColor:n}=r;return e&&(a.description=e),t&&(a.argsDefault=t),s&&(a.inputDefault=s),i&&(a.textColor=i),n&&(a.backgroundColor=n),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?n(Ir,this.options.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Fr=e=>"objects"in e?{...e,data:e.objects}:e,$r=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Hr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(Mr("additionalData",r,a.parameters))return Object.fromEntries(r);const e=Mr("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:i,aliases:n,required:o}of a.parameters){const a=[i,...n],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${i}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Mr=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},Gr=(e,r)=>u(e)&&!r.has(e),Br=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},zr=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},Wr=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};Object.defineProperty(exports,"dequal",{enumerable:!0,get:function(){return r.dequal}}),exports.AxiosClient=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),exports.FetchClient=Qr,exports.FigTreeError=w,exports.FigTreeEvaluator=_r,exports.SQLNodePostgres=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),exports.SQLite=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),exports.convertFromShorthand=(e,r)=>{const i=r.getOperators(),n=r.getFragments(),o=r.getCustomFunctions(),l=n.map((e=>e.name)),u=o.map((e=>e.name)),p=e=>{if(Array.isArray(e))return e.map((e=>p(e)));if(!f(e))return e;const n=Object.entries(e);if(0===n.length)return e;const o=n[0][0].replace("$",""),d=s(o),h=i.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=n[0][1];if(Array.isArray(s)){const t=s.map((e=>p(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...c(n)}}const i=p(s);if(!f(i)||!Wr(i,h)||t(i)||a(i)){return{operator:e,[h.parameters[0].name]:i}}return{operator:e,...i,...c(n)}}if(m){const r=p(e[n[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...c(n)}}if(y){const e=o,r=n[0][1],s=p(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...c(n)}}return Object.fromEntries(n.map((([e,r])=>[e,p(r)])))},c=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,p(r)])))};return p(e)},exports.convertToShorthand=(e,r,t=2)=>{const a=r.getOperators(),i=r.getFragments(),n=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=i.map((e=>e.name)),p=n.map((e=>e.name)),c=new Set([...l,...u,...p]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:r,fragment:i,...n}=e;if(!r&&!i)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));const l=p.includes(r);i&&n?.parameters&&(Object.entries(n.parameters).forEach((([e,r])=>{n[e]=r})),delete n.parameters);const u=l?r:Br(r,a),h=`$${u??i}`,m=i?zr(i,o):[],y=Object.keys(n).filter((e=>Gr(e,c)&&!m.includes(e))),g=Object.entries(n).filter((([e])=>!y.includes(e)&&!m.includes(e))).map((([e,r])=>[e,d(r)])),v=Object.fromEntries(y.map((e=>[e,d(n[e])]))),b=Object.fromEntries(m.map((e=>[e,d(n[e])])));switch(!0){case Object.keys(b).length>0:return{[h]:b,...v};case l:return 1!==g.length||"input"in n?{[h]:Object.fromEntries(g),...v}:{[h]:g[0][1]};case"values"in n:return 1===g.length?{[h]:g[0][1]}:{[h]:Object.fromEntries(g),...v};case"match"===u:return{[h]:Object.fromEntries(g),...v};case g.length>t||!!i||g.some((([e])=>"useCache"===e||"outputType"===e))||g.some((e=>Array.isArray(e[1]))):return{[h]:Object.fromEntries(g),...v};case 1===g.length:return{[h]:g[0][1],...v};default:return{[h]:Hr(s(r),g,a),...v}}};return d(e)},exports.convertV1ToV2=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const i=$r(e)?(()=>{const{operator:a}=e,i=s(a),n=t.find((e=>e.name===i||e.aliases.includes(i)));if(n){const t=n.parseChildren(e,r.getConfig());delete t.children;const a=n.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,n={};for(const[e,r]of Object.entries(i)){const t="type"===e?"outputType":e;Array.isArray(r)?n[t]=r.map((e=>a(e))):n[t]=a(r)}return n};return a(e)},exports.evaluateExpression=(e,r)=>new _r(r).evaluate(e),exports.isAliasString=u,exports.isFigTreeError=e=>e instanceof w,exports.isFigTreeExpression=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),exports.isFragmentNode=a,exports.isObject=f,exports.isOperatorNode=t,exports.isV1Node=$r,exports.preProcessShorthand=v,exports.standardiseOperatorName=s,exports.truncateString=o;
1
+ "use strict";var e=require("object-property-extractor"),r=require("dequal/lite");const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},i=(e,r)=>r[s(e)],n=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),p=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,c=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},g=y,v=(e,r={},t,a=!0)=>a&&f(e)?b(e,r,t):e,b=(e,r,s)=>{if(t(e)||a(e))return e;const i=Object.entries(e),n=i.filter((([e])=>u(e))),o=i.filter((([e])=>!u(e)));return{...n.reduce(((e,[t,a])=>e={...e,...T(t,a,r,s)}),{}),...Object.fromEntries(o)}},T=(e,r,t,a)=>{const s=e.slice(1),n=i(s,g);return n?Array.isArray(r)?{operator:n,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:n,...r}:{operator:n,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class w extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),i=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===i?"":i}`}}const C=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:i=!1})=>{if(void 0!==e)return e;if(a instanceof w){if(!i)throw a;return a.prettyPrint}const n=new w("string"==typeof a?new Error(a):a,r,t,s);if(i)return n.prettyPrint;throw n},E=e=>f(e)&&"literal"in e,A=({value:e,name:r,expectedType:t})=>{if(E(t)){const{literal:a}=t;return!!a.includes(e)||O(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===A({value:e,name:r,expectedType:t})))||O(r,e,t.join("|"));return!!(0,q[t])(e)||O(r,e,t)},S=(...e)=>{const r=[];return e.forEach((e=>{const t=A(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},q={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},O=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${x(r)}) is not of type: ${t}`:`- ${x(r)} is not of type: ${t}`,x=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},N=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},P=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(E(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const i=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:i}})),j=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},L=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=S(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},k=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,I=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>k(e))):t?null===s?null:k(s):s},U=e=>/^https?:\/\/.+/.test(e),R=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,i=r.slice(a,s);return""===i?e:e+(0===t?"":"/")+i}),""),D=async(e,r)=>{const{url:t,params:a={},data:s={},headers:i={},method:n="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[n]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...i},params:a,data:s})}catch(r){e.throwError(r)}},Q=async(e,r)=>{const{options:s,operators:n,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const c=Object.keys(r.options?.functions??{});u=v(u,r.options?.fragments,c,!s.noShorthand),Array.isArray(u)&&(u=await _(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:i,useCache:n,input:o,args:l,...u}=e,p={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(p.fallback=a),void 0!==s&&(p.outputType=s),void 0!==i&&(p.type=i),void 0!==n&&(p.useCache=n),void 0!==l&&(p.args=l),void 0!==o?p.input=o:Object.keys(u).length>0&&(p.input=u),p})(u,r)),s.evaluateFullObject&&!h&&!m)return p(await $(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:p(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[i,n]=await _([e.fragment,e.parameters],r),o=v(s?.fragments?.[i],s.fragments,c,!s.noShorthand);if(void 0===o)return C({fallback:await Q(y,r),error:`Fragment not defined: ${i}`,expression:u,returnErrorAsString:g});if(!t(o))return p(o,r);u={...e,...o,...n},delete u.fragment}const b=u,T=i(b.operator,o);if(!T)return C({fallback:await Q(y,r),error:`Invalid operator: ${b.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return C({fallback:await Q(y,r),error:`Excluded operator: ${b.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:E,parseChildren:A}=n[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,b);const q=await F(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await Q(S.children,O)),!Array.isArray(S.children))return C({fallback:await Q(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=A(S,O),delete S.children}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let x;try{x=await E(S,O)}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const N=S?.outputType??S?.type;if(!N)return x;const P=await Q(N,r);return P in d?d[P](x):C({fallback:await Q(y,r),operator:T,error:`- Invalid output type: ${P}`,expression:S,returnErrorAsString:g})},_=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>Q(e,r)))):await Q(e,r),F=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push(Q(e[t],r))));const s=await Promise.all(a),i=j(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(i[t[e]]=i?.[r]??r);return i},$=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=v(e,r.options?.fragments,t);if(!f(a))return e;const s=[],i=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(i.push(e,Q(t,r)),delete a[e])}));const n=await Promise.all(i);r.resolvedAliasNodes={...r.resolvedAliasNodes,...L(n)},Object.entries(a).forEach((([e,t])=>{s.push(e,Q(t,r))}));const o=await Promise.all(s);return p(L(o),r)},H=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],M=N(H),G={description:"Logical AND",aliases:["and","&","&&"],parameters:H},B=e=>{const r=e.children;return{...e,values:r}},z={propertyAliases:M,operatorData:G,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(G.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:B},W=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],J=N(W),V={description:"Logical OR",aliases:["or","|","||"],parameters:W},Y={propertyAliases:J,operatorData:V,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(V.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:B},X=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Z=N(X),K={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:X},ee={propertyAliases:Z,operatorData:K,evaluate:async(e,t)=>{const[a,s,i]=await _([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(P(K.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.every((e=>r.dequal(e,n[0]))):n.every((e=>null==e))},parseChildren:B},re=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],te=N(re),ae={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:re},se={propertyAliases:te,operatorData:ae,evaluate:async(e,t)=>{const[a,s,i]=await _([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(P(ae.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.some((e=>!r.dequal(e,n[0]))):n.some((e=>null===e&&void 0===e))},parseChildren:B},ie=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],ne=N(ie),oe={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:ie},le={propertyAliases:ne,operatorData:oe,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(oe.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:B},ue=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],pe=N(ue),ce={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:ue},de={propertyAliases:pe,operatorData:ce,evaluate:async(e,r)=>{const[t,a,s]=await _([e.values,e.from,e.subtract],r);r.typeChecker(P(ce.parameters,{values:t,from:a,subtract:s}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return i[0]-i[1]},parseChildren:B},he=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],me=N(he),fe={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:he},ye={propertyAliases:me,operatorData:fe,evaluate:async(e,r)=>{const t=await _(e.values,r);if(r.typeChecker(P(fe.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:B},ge=[{name:"values",description:"Array of values - 1st element will be divided by the first",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder"]},default:"quotient"}],ve=N(ge),be={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:ge},Te={propertyAliases:ve,operatorData:be,evaluate:async(e,r)=>{const[t,a,s,i]=await _([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(P(be.parameters,{values:t,dividend:a,divisor:s,output:i}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===n[1])throw new Error("Division by zero!");switch(i){case"quotient":return Math.floor(n[0]/n[1]);case"remainder":return n[0]%n[1];default:return n[0]/n[1]}},parseChildren:B},we=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ce=N(we),Ee={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:we},Ae={propertyAliases:Ce,operatorData:Ee,evaluate:async(e,r)=>{const[t,a=!0]=await _([e.values,e.strict],r);if(r.typeChecker(P(Ee.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s>i},parseChildren:B},Se=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],qe=N(Se),Oe={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Se},xe={propertyAliases:qe,operatorData:Oe,evaluate:async(e,r)=>{const[t,a=!0]=await _([e.values,e.strict],r);if(r.typeChecker(P(Oe.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s<i},parseChildren:B},Ne=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],Pe=N(Ne),je={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:Ne},Le={propertyAliases:Pe,operatorData:je,evaluate:async(e,r)=>{r.typeChecker(P(je.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await Q(e.condition,r)?await Q(e.valueIfTrue,r):await Q(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},ke=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Ie=N(ke),Ue={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:ke},Re={propertyAliases:Ie,operatorData:Ue,evaluate:async(e,r)=>{const[t,a]=await _([e.testString,e.pattern],r);r.typeChecker(P(Ue.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},De=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],Qe=N(De),_e={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:De},Fe={propertyAliases:Qe,operatorData:_e,evaluate:async(r,t)=>{const[a,s={}]=await _([r.property,r.additionalData],t);t.typeChecker(P(_e.parameters,{property:a,additionalData:s}));const i={...t.options?.data??{},...s};return e(i,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},$e=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],He=N($e),Me={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:$e},Ge={propertyAliases:He,operatorData:Me,evaluate:async(e,r)=>{const[t,a={},s=!0,i="%",n={}]=await _([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(P(Me.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:i,numberMapping:n})),Array.isArray(a)){const e="$"===i?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),n=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(n),l=j(Array.from(o),a.map((e=>s?String(e).trim():e)));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(`\\${e}`,e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace("\\{{","{{"));continue}const t=await Be(e,a,n,r);l.push(s?String(t).trim():t)}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},Be=async(r,t,a,s)=>{const i=s.options?.data??{},n=r.replace(/{{(.+)}}/,"$1"),o=await Q(e(t,n,e(i,n,"")),s);if("number"!=typeof o)return o;if(!(n in a))return o;const l=a[n];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[n]),p=u.find((e=>e.startsWith(">")));if(p){if(o>Number(p.slice(1)))return l?.[p]}const c=u.find((e=>e.startsWith("<")));if(c){if(o<Number(c.slice(1)))return l?.[c]}return l.other?l.other.replace("{}",String(o)):o},ze=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],We=N(ze),Je={description:"Count elements in an array",aliases:["count","length"],parameters:ze},Ve={propertyAliases:We,operatorData:Je,evaluate:async(e,r)=>{const t=await _(e.values,r);return r.typeChecker(P(Je.parameters,{values:t})),t.length},parseChildren:B},Ye=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],Xe=N(Ye),Ze={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Ye},Ke=" ",er={propertyAliases:Xe,operatorData:Ze,evaluate:async(e,r)=>{const[t,a,s,i]=await _([e.value,e.delimiter??Ke,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(P(Ze.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:i}));let n=t.split(a);return s&&(n=n.map((e=>e.trim()))),i&&""===n[n.length-1]&&n.pop(),n},parseChildren:e=>{const[r,t=Ke]=e.children;return{...e,value:r,delimiter:t}}},rr=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],tr=N(rr),ar={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:rr},sr={propertyAliases:tr,operatorData:ar,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,i,n,o,l]=await _([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(P(ar.parameters,{query:a,single:i,flatten:n,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,i)=>{const n=await t.query({query:e,values:r})||[];["array","string","number"].includes(i??"")&&(s=!0);const o=s?n.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):n;return a?o[0]:o}),a,s,i,n,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},ir=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],nr=N(ir),or={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:ir},lr={propertyAliases:nr,operatorData:or,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,i,n,o,l]=await _([e.query,e.url,await $(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:p}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...P(or.parameters,{url:u,query:a,variables:i,returnNode:n,headers:o,useCache:l}),{name:"headers",value:p,expectedType:["object","null"]}]);const c=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=U(c)?c:R(d,c),m={query:a,variables:i},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const i=await D(t,{url:e,method:"post",data:r,headers:a});return I(i?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...p,...o},n);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,i=Array.isArray(a)?a:[a],n=s.slice(0,i.length),o=j(i,n),l={...e,query:r,url:t,variables:o};return s.length>i.length&&(l.returnNode=s.pop()),l}},ur=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],pr=N(ur),cr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:ur},dr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],i=a.slice(0,s.length),n=j(s,i),o={...e,url:r,parameters:n};return a.length>s.length&&(o.returnProperty=a.pop()),o},hr=dr,mr={propertyAliases:pr,operatorData:cr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await _([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...P(cr.parameters,{url:l,returnProperty:i,headers:n,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const p=r.options.baseEndpoint??"",c={...r.options?.headers,...u,...n},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await D(t,{url:e,params:r,headers:a});return I(i,s)}),U(l)?l:R(p,l),s,c,i);return h},parseChildren:dr},fr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],yr=N(fr),gr={description:"HTTP POST Request",aliases:["POST","post"],parameters:fr},vr={propertyAliases:yr,operatorData:gr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await _([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...P(gr.parameters,{url:l,headers:n,data:s,returnProperty:i,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const p=r.options.baseEndpoint??"",c={...r.options?.headers,...u,...n},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await D(t,{url:e,data:r,headers:a,method:"post"});return I(i,s)}),U(l)?l:R(p,l),s,c,i);return h},parseChildren:hr},br=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],Tr=N(br),wr={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:br},Cr=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},Er={propertyAliases:Tr,operatorData:wr,evaluate:async(e,r)=>{const t=await _(e.properties,r);r.typeChecker(P(wr.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Cr({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await _(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Cr},Ar=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],Sr={propertyAliases:N(Ar),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:Ar},evaluate:async(e,r)=>{const a=await Q(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?L(e.branches):e.branches??{},i=t(s)?await Q(s,r):s;if(!f(i))throw new Error("Branches don't evaluate to an object");if(a in i)return await Q(i[a],r);if("fallback"in i)return await Q(i.fallback,r);if(a in e)return await Q(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=L(t);return{...e,matchExpression:r,branches:a}}},qr=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],Or=N(qr),xr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:qr},Nr={propertyAliases:Or,operatorData:xr,evaluate:async(r,t)=>{const[a,s=[],i,n]=await _([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(P(xr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const p=n??t.options.useCache??!1,c=[...void 0===i?[]:[await $(i,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(p,(async(e,...r)=>await u(...r)),a,...c)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Pr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],jr=N(Pr),Lr={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Pr},kr={propertyAliases:jr,operatorData:Lr,evaluate:async(e,r)=>(r.typeChecker(P(Lr.parameters,{value:e.value})),await Q(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Ir=Object.freeze({__proto__:null,AND:z,BUILD_OBJECT:Er,CONDITIONAL:Le,COUNT:Ve,CUSTOM_FUNCTIONS:Nr,DIVIDE:Te,EQUAL:ee,GET:mr,GRAPHQL:lr,GREATER_THAN:Ae,LESS_THAN:xe,MATCH:Sr,MULTIPLY:ye,NOT_EQUAL:se,OBJECT_PROPERTIES:Fe,OR:Y,PASSTHRU:kr,PLUS:le,POST:vr,REGEX:Re,SPLIT:er,SQL:sr,STRING_SUBSTITUTION:Ge,SUBTRACT:de});class Ur{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Rr(t),s=a in this.store,i=Date.now(),n=s&&i-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=i,n&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:i},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Rr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),Dr=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?Qr(window.fetch):void 0),Qr=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,i=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",n=await e(t+i,{headers:a,method:"GET"}),o=await n.json();if(!n.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:n.status,error:n.statusText,url:n.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:i}=r,n=new URLSearchParams(s),o=n.size>0?`?${n.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(i),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class _r{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=S(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.22.1",this.options=Fr(e),this.operators=n(Ir,this.options?.excludeOperators??[],y),this.operatorAliases=y,this.cache=new Ur({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=Dr(e.graphQLConnection?.httpClient),this.httpClient=Dr(e.httpClient)}async evaluate(e,r={}){const t=c(this.options,Fr(r),!0);return r.httpClient&&(this.httpClient=Dr(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=Dr(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await Q(e,{options:t,operators:r.excludeOperators?n(Ir,r.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}getOptions(){return this.options}updateOptions(e){this.options=c(this.options,Fr(e),!1),this.options.excludeOperators&&(this.operators=n(Ir,this.options.excludeOperators,y))}getOperators(){const e=this.options.excludeOperators?n(Ir,this.options.excludeOperators,y):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(y))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:i,backgroundColor:n}=r;return e&&(a.description=e),t&&(a.argsDefault=t),s&&(a.inputDefault=s),i&&(a.textColor=i),n&&(a.backgroundColor=n),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?n(Ir,this.options.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Fr=e=>"objects"in e?{...e,data:e.objects}:e,$r=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Hr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(Gr("additionalData",r,a.parameters))return Object.fromEntries(r);const e=Gr("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:i,aliases:n,required:o}of a.parameters){const a=[i,...n],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${i}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Mr=(e,r,t)=>{if(!e)return!1;const a=s(e),i=t.find((e=>e.name===a||e.aliases.includes(a)))?.parameters[0];if(!i)return!1;return!!("array"===i.type||Array.isArray(i.type)&&i.type.includes("array"))&&[i.name,...i.aliases].some((e=>e in r))},Gr=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},Br=(e,r)=>u(e)&&!r.has(e),zr=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},Wr=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},Jr=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};Object.defineProperty(exports,"dequal",{enumerable:!0,get:function(){return r.dequal}}),exports.AxiosClient=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),exports.FetchClient=Qr,exports.FigTreeError=w,exports.FigTreeEvaluator=_r,exports.SQLNodePostgres=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),exports.SQLite=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),exports.convertFromShorthand=(e,r)=>{const i=r.getOperators(),n=r.getFragments(),o=r.getCustomFunctions(),l=n.map((e=>e.name)),u=o.map((e=>e.name)),p=e=>{if(Array.isArray(e))return e.map((e=>p(e)));if(!f(e))return e;const n=Object.entries(e);if(0===n.length)return e;const o=n[0][0].replace("$",""),d=s(o),h=i.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=n[0][1];if(Array.isArray(s)){const t=s.map((e=>p(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...c(n)}}const i=p(s);if(!f(i)||!Jr(i,h)||t(i)||a(i)){return{operator:e,[h.parameters[0].name]:i}}return{operator:e,...i,...c(n)}}if(m){const r=p(e[n[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...c(n)}}if(y){const e=o,r=n[0][1],s=p(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...c(n)}}return Object.fromEntries(n.map((([e,r])=>[e,p(r)])))},c=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,p(r)])))};return p(e)},exports.convertToShorthand=(e,r,t=2)=>{const a=r.getOperators(),i=r.getFragments(),n=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=i.map((e=>e.name)),p=n.map((e=>e.name)),c=new Set([...l,...u,...p]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:i,fragment:n,...l}=e;if(!i&&!n)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));if(i&&Array.isArray(l.children)){const e=s(i),t=a.find((r=>r.name===e||r.aliases.includes(e)));if(t){const e=t.parseChildren({...l,operator:i},r.getConfig());return delete e.children,d(e)}}const u=p.includes(i);n&&l?.parameters&&(Object.entries(l.parameters).forEach((([e,r])=>{l[e]=r})),delete l.parameters);const h=u?i:zr(i,a),m=`$${h??n}`,y=n?Wr(n,o):[],g=Object.keys(l).filter((e=>Br(e,c)&&!y.includes(e))),v=Object.entries(l).filter((([e])=>!g.includes(e)&&!y.includes(e))).map((([e,r])=>[e,d(r)])),b=Object.fromEntries(g.map((e=>[e,d(l[e])]))),T=Object.fromEntries(y.map((e=>[e,d(l[e])])));switch(!0){case Object.keys(T).length>0:return{[m]:T,...b};case u:return 1!==v.length||"input"in l?{[m]:Object.fromEntries(v),...b}:{[m]:v[0][1]};case Mr(i,l,a):return 1===v.length?{[m]:v[0][1]}:{[m]:Object.fromEntries(v),...b};case"match"===h:return{[m]:Object.fromEntries(v),...b};case v.length>t||!!n||v.some((([e])=>"useCache"===e||"outputType"===e))||v.some((e=>Array.isArray(e[1]))):return{[m]:Object.fromEntries(v),...b};case 1===v.length:return{[m]:v[0][1],...b};default:return{[m]:Hr(s(i),v,a),...b}}};return d(e)},exports.convertV1ToV2=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const i=$r(e)?(()=>{const{operator:a}=e,i=s(a),n=t.find((e=>e.name===i||e.aliases.includes(i)));if(n){const t=n.parseChildren(e,r.getConfig());delete t.children;const a=n.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,n={};for(const[e,r]of Object.entries(i)){const t="type"===e?"outputType":e;Array.isArray(r)?n[t]=r.map((e=>a(e))):n[t]=a(r)}return n};return a(e)},exports.evaluateExpression=(e,r)=>new _r(r).evaluate(e),exports.isAliasString=u,exports.isFigTreeError=e=>e instanceof w,exports.isFigTreeExpression=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),exports.isFragmentNode=a,exports.isObject=f,exports.isOperatorNode=t,exports.isV1Node=$r,exports.preProcessShorthand=v,exports.standardiseOperatorName=s,exports.truncateString=o;
@@ -1 +1 @@
1
- import e from"object-property-extractor";import{dequal as r}from"dequal/lite";export{dequal}from"dequal/lite";const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},i=(e,r)=>r[s(e)],n=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),c=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,p=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),g={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},v=g,b=(e,r={},t,a=!0)=>a&&f(e)?T(e,r,t):e,T=(e,r,s)=>{if(t(e)||a(e))return e;const i=Object.entries(e),n=i.filter((([e])=>u(e))),o=i.filter((([e])=>!u(e)));return{...n.reduce(((e,[t,a])=>e={...e,...w(t,a,r,s)}),{}),...Object.fromEntries(o)}},w=(e,r,t,a)=>{const s=e.slice(1),n=i(s,v);return n?Array.isArray(r)?{operator:n,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:n,...r}:{operator:n,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class C extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),i=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===i?"":i}`}}const E=e=>e instanceof C,A=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:i=!1})=>{if(void 0!==e)return e;if(a instanceof C){if(!i)throw a;return a.prettyPrint}const n=new C("string"==typeof a?new Error(a):a,r,t,s);if(i)return n.prettyPrint;throw n},S=e=>f(e)&&"literal"in e,q=({value:e,name:r,expectedType:t})=>{if(S(t)){const{literal:a}=t;return!!a.includes(e)||j(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===q({value:e,name:r,expectedType:t})))||j(r,e,t.join("|"));return!!(0,N[t])(e)||j(r,e,t)},O=(...e)=>{const r=[];return e.forEach((e=>{const t=q(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},N={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},j=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${P(r)}) is not of type: ${t}`:`- ${P(r)} is not of type: ${t}`,P=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},x=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},L=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(S(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const i=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:i}})),k=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},I=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=O(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},U=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,R=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>U(e))):t?null===s?null:U(s):s},D=e=>/^https?:\/\/.+/.test(e),Q=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,i=r.slice(a,s);return""===i?e:e+(0===t?"":"/")+i}),""),_=async(e,r)=>{const{url:t,params:a={},data:s={},headers:i={},method:n="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[n]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...i},params:a,data:s})}catch(r){e.throwError(r)}},$=async(e,r)=>{const{options:s,operators:n,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const p=Object.keys(r.options?.functions??{});u=b(u,r.options?.fragments,p,!s.noShorthand),Array.isArray(u)&&(u=await F(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:i,useCache:n,input:o,args:l,...u}=e,c={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(c.fallback=a),void 0!==s&&(c.outputType=s),void 0!==i&&(c.type=i),void 0!==n&&(c.useCache=n),void 0!==l&&(c.args=l),void 0!==o?c.input=o:Object.keys(u).length>0&&(c.input=u),c})(u,r)),s.evaluateFullObject&&!h&&!m)return c(await M(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:c(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[i,n]=await F([e.fragment,e.parameters],r),o=b(s?.fragments?.[i],s.fragments,p,!s.noShorthand);if(void 0===o)return A({fallback:await $(y,r),error:`Fragment not defined: ${i}`,expression:u,returnErrorAsString:g});if(!t(o))return c(o,r);u={...e,...o,...n},delete u.fragment}const v=u,T=i(v.operator,o);if(!T)return A({fallback:await $(y,r),error:`Invalid operator: ${v.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return A({fallback:await $(y,r),error:`Excluded operator: ${v.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:C,parseChildren:E}=n[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,v);const q=await H(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await $(S.children,O)),!Array.isArray(S.children))return A({fallback:await $(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=E(S,O),delete S.children}catch(e){return A({fallback:await $(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let N;try{N=await C(S,O)}catch(e){return A({fallback:await $(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const j=S?.outputType??S?.type;if(!j)return N;const P=await $(j,r);return P in d?d[P](N):A({fallback:await $(y,r),operator:T,error:`- Invalid output type: ${P}`,expression:S,returnErrorAsString:g})},F=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>$(e,r)))):await $(e,r),H=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push($(e[t],r))));const s=await Promise.all(a),i=k(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(i[t[e]]=i?.[r]??r);return i},M=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=b(e,r.options?.fragments,t);if(!f(a))return e;const s=[],i=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(i.push(e,$(t,r)),delete a[e])}));const n=await Promise.all(i);r.resolvedAliasNodes={...r.resolvedAliasNodes,...I(n)},Object.entries(a).forEach((([e,t])=>{s.push(e,$(t,r))}));const o=await Promise.all(s);return c(I(o),r)},G=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],B=x(G),z={description:"Logical AND",aliases:["and","&","&&"],parameters:G},W=e=>{const r=e.children;return{...e,values:r}},J={propertyAliases:B,operatorData:z,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(z.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:W},V=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],Y=x(V),X={description:"Logical OR",aliases:["or","|","||"],parameters:V},Z={propertyAliases:Y,operatorData:X,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(X.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:W},K=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],ee=x(K),re={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:K},te={propertyAliases:ee,operatorData:re,evaluate:async(e,t)=>{const[a,s,i]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(L(re.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.every((e=>r(e,n[0]))):n.every((e=>null==e))},parseChildren:W},ae=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],se=x(ae),ie={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:ae},ne={propertyAliases:se,operatorData:ie,evaluate:async(e,t)=>{const[a,s,i]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(L(ie.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.some((e=>!r(e,n[0]))):n.some((e=>null===e&&void 0===e))},parseChildren:W},oe=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],le=x(oe),ue={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:oe},ce={propertyAliases:le,operatorData:ue,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(ue.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:W},pe=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],de=x(pe),he={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:pe},me={propertyAliases:de,operatorData:he,evaluate:async(e,r)=>{const[t,a,s]=await F([e.values,e.from,e.subtract],r);r.typeChecker(L(he.parameters,{values:t,from:a,subtract:s}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return i[0]-i[1]},parseChildren:W},fe=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],ye=x(fe),ge={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:fe},ve={propertyAliases:ye,operatorData:ge,evaluate:async(e,r)=>{const t=await F(e.values,r);if(r.typeChecker(L(ge.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:W},be=[{name:"values",description:"Array of values - 1st element will be divided by the first",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder"]},default:"quotient"}],Te=x(be),we={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:be},Ce={propertyAliases:Te,operatorData:we,evaluate:async(e,r)=>{const[t,a,s,i]=await F([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(L(we.parameters,{values:t,dividend:a,divisor:s,output:i}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===n[1])throw new Error("Division by zero!");switch(i){case"quotient":return Math.floor(n[0]/n[1]);case"remainder":return n[0]%n[1];default:return n[0]/n[1]}},parseChildren:W},Ee=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ae=x(Ee),Se={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:Ee},qe={propertyAliases:Ae,operatorData:Se,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(L(Se.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s>i},parseChildren:W},Oe=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ne=x(Oe),je={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Oe},Pe={propertyAliases:Ne,operatorData:je,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(L(je.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s<i},parseChildren:W},xe=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],Le=x(xe),ke={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:xe},Ie={propertyAliases:Le,operatorData:ke,evaluate:async(e,r)=>{r.typeChecker(L(ke.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await $(e.condition,r)?await $(e.valueIfTrue,r):await $(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},Ue=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Re=x(Ue),De={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:Ue},Qe={propertyAliases:Re,operatorData:De,evaluate:async(e,r)=>{const[t,a]=await F([e.testString,e.pattern],r);r.typeChecker(L(De.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},_e=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],$e=x(_e),Fe={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:_e},He={propertyAliases:$e,operatorData:Fe,evaluate:async(r,t)=>{const[a,s={}]=await F([r.property,r.additionalData],t);t.typeChecker(L(Fe.parameters,{property:a,additionalData:s}));const i={...t.options?.data??{},...s};return e(i,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},Me=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],Ge=x(Me),Be={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:Me},ze={propertyAliases:Ge,operatorData:Be,evaluate:async(e,r)=>{const[t,a={},s=!0,i="%",n={}]=await F([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(L(Be.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:i,numberMapping:n})),Array.isArray(a)){const e="$"===i?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),n=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(n),l=k(Array.from(o),a.map((e=>s?String(e).trim():e)));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(`\\${e}`,e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace("\\{{","{{"));continue}const t=await We(e,a,n,r);l.push(s?String(t).trim():t)}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},We=async(r,t,a,s)=>{const i=s.options?.data??{},n=r.replace(/{{(.+)}}/,"$1"),o=await $(e(t,n,e(i,n,"")),s);if("number"!=typeof o)return o;if(!(n in a))return o;const l=a[n];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[n]),c=u.find((e=>e.startsWith(">")));if(c){if(o>Number(c.slice(1)))return l?.[c]}const p=u.find((e=>e.startsWith("<")));if(p){if(o<Number(p.slice(1)))return l?.[p]}return l.other?l.other.replace("{}",String(o)):o},Je=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],Ve=x(Je),Ye={description:"Count elements in an array",aliases:["count","length"],parameters:Je},Xe={propertyAliases:Ve,operatorData:Ye,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(Ye.parameters,{values:t})),t.length},parseChildren:W},Ze=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],Ke=x(Ze),er={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Ze},rr=" ",tr={propertyAliases:Ke,operatorData:er,evaluate:async(e,r)=>{const[t,a,s,i]=await F([e.value,e.delimiter??rr,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(L(er.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:i}));let n=t.split(a);return s&&(n=n.map((e=>e.trim()))),i&&""===n[n.length-1]&&n.pop(),n},parseChildren:e=>{const[r,t=rr]=e.children;return{...e,value:r,delimiter:t}}},ar=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],sr=x(ar),ir={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:ar},nr={propertyAliases:sr,operatorData:ir,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,i,n,o,l]=await F([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(L(ir.parameters,{query:a,single:i,flatten:n,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,i)=>{const n=await t.query({query:e,values:r})||[];["array","string","number"].includes(i??"")&&(s=!0);const o=s?n.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):n;return a?o[0]:o}),a,s,i,n,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},or=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],lr=x(or),ur={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:or},cr={propertyAliases:lr,operatorData:ur,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,i,n,o,l]=await F([e.query,e.url,await M(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:c}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...L(ur.parameters,{url:u,query:a,variables:i,returnNode:n,headers:o,useCache:l}),{name:"headers",value:c,expectedType:["object","null"]}]);const p=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=D(p)?p:Q(d,p),m={query:a,variables:i},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const i=await _(t,{url:e,method:"post",data:r,headers:a});return R(i?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...c,...o},n);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,i=Array.isArray(a)?a:[a],n=s.slice(0,i.length),o=k(i,n),l={...e,query:r,url:t,variables:o};return s.length>i.length&&(l.returnNode=s.pop()),l}},pr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],dr=x(pr),hr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:pr},mr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],i=a.slice(0,s.length),n=k(s,i),o={...e,url:r,parameters:n};return a.length>s.length&&(o.returnProperty=a.pop()),o},fr=mr,yr={propertyAliases:dr,operatorData:hr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await F([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...L(hr.parameters,{url:l,returnProperty:i,headers:n,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...n},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await _(t,{url:e,params:r,headers:a});return R(i,s)}),D(l)?l:Q(c,l),s,p,i);return h},parseChildren:mr},gr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],vr=x(gr),br={description:"HTTP POST Request",aliases:["POST","post"],parameters:gr},Tr={propertyAliases:vr,operatorData:br,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await F([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...L(br.parameters,{url:l,headers:n,data:s,returnProperty:i,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...n},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await _(t,{url:e,data:r,headers:a,method:"post"});return R(i,s)}),D(l)?l:Q(c,l),s,p,i);return h},parseChildren:fr},wr=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],Cr=x(wr),Er={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:wr},Ar=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},Sr={propertyAliases:Cr,operatorData:Er,evaluate:async(e,r)=>{const t=await F(e.properties,r);r.typeChecker(L(Er.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Ar({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await F(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Ar},qr=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],Or={propertyAliases:x(qr),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:qr},evaluate:async(e,r)=>{const a=await $(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?I(e.branches):e.branches??{},i=t(s)?await $(s,r):s;if(!f(i))throw new Error("Branches don't evaluate to an object");if(a in i)return await $(i[a],r);if("fallback"in i)return await $(i.fallback,r);if(a in e)return await $(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=I(t);return{...e,matchExpression:r,branches:a}}},Nr=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],jr=x(Nr),Pr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:Nr},xr={propertyAliases:jr,operatorData:Pr,evaluate:async(r,t)=>{const[a,s=[],i,n]=await F([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(L(Pr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const c=n??t.options.useCache??!1,p=[...void 0===i?[]:[await M(i,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(c,(async(e,...r)=>await u(...r)),a,...p)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Lr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],kr=x(Lr),Ir={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Lr},Ur={propertyAliases:kr,operatorData:Ir,evaluate:async(e,r)=>(r.typeChecker(L(Ir.parameters,{value:e.value})),await $(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Rr=Object.freeze({__proto__:null,AND:J,BUILD_OBJECT:Sr,CONDITIONAL:Ie,COUNT:Xe,CUSTOM_FUNCTIONS:xr,DIVIDE:Ce,EQUAL:te,GET:yr,GRAPHQL:cr,GREATER_THAN:qe,LESS_THAN:Pe,MATCH:Or,MULTIPLY:ve,NOT_EQUAL:ne,OBJECT_PROPERTIES:He,OR:Z,PASSTHRU:Ur,PLUS:ce,POST:Tr,REGEX:Qe,SPLIT:tr,SQL:nr,STRING_SUBSTITUTION:ze,SUBTRACT:me});class Dr{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Qr(t),s=a in this.store,i=Date.now(),n=s&&i-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=i,n&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:i},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Qr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),_r=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?Fr(window.fetch):void 0),$r=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),Fr=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,i=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",n=await e(t+i,{headers:a,method:"GET"}),o=await n.json();if(!n.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:n.status,error:n.statusText,url:n.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:i}=r,n=new URLSearchParams(s),o=n.size>0?`?${n.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(i),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class Hr{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=O(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.22.0",this.options=Gr(e),this.operators=n(Rr,this.options?.excludeOperators??[],g),this.operatorAliases=g,this.cache=new Dr({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=_r(e.graphQLConnection?.httpClient),this.httpClient=_r(e.httpClient)}async evaluate(e,r={}){const t=p(this.options,Gr(r),!0);return r.httpClient&&(this.httpClient=_r(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=_r(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await $(e,{options:t,operators:r.excludeOperators?n(Rr,r.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}getOptions(){return this.options}updateOptions(e){this.options=p(this.options,Gr(e),!1),this.options.excludeOperators&&(this.operators=n(Rr,this.options.excludeOperators,g))}getOperators(){const e=this.options.excludeOperators?n(Rr,this.options.excludeOperators,g):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(g))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:i,backgroundColor:n}=r;return e&&(a.description=e),t&&(a.argsDefault=t),s&&(a.inputDefault=s),i&&(a.textColor=i),n&&(a.backgroundColor=n),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?n(Rr,this.options.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Mr=(e,r)=>new Hr(r).evaluate(e),Gr=e=>"objects"in e?{...e,data:e.objects}:e,Br=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),zr=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),Wr=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const i=Jr(e)?(()=>{const{operator:a}=e,i=s(a),n=t.find((e=>e.name===i||e.aliases.includes(i)));if(n){const t=n.parseChildren(e,r.getConfig());delete t.children;const a=n.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,n={};for(const[e,r]of Object.entries(i)){const t="type"===e?"outputType":e;Array.isArray(r)?n[t]=r.map((e=>a(e))):n[t]=a(r)}return n};return a(e)},Jr=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Vr=(e,r,t=2)=>{const a=r.getOperators(),i=r.getFragments(),n=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=i.map((e=>e.name)),c=n.map((e=>e.name)),p=new Set([...l,...u,...c]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:r,fragment:i,...n}=e;if(!r&&!i)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));const l=c.includes(r);i&&n?.parameters&&(Object.entries(n.parameters).forEach((([e,r])=>{n[e]=r})),delete n.parameters);const u=l?r:Kr(r,a),h=`$${u??i}`,m=i?et(i,o):[],y=Object.keys(n).filter((e=>Zr(e,p)&&!m.includes(e))),g=Object.entries(n).filter((([e])=>!y.includes(e)&&!m.includes(e))).map((([e,r])=>[e,d(r)])),v=Object.fromEntries(y.map((e=>[e,d(n[e])]))),b=Object.fromEntries(m.map((e=>[e,d(n[e])])));switch(!0){case Object.keys(b).length>0:return{[h]:b,...v};case l:return 1!==g.length||"input"in n?{[h]:Object.fromEntries(g),...v}:{[h]:g[0][1]};case"values"in n:return 1===g.length?{[h]:g[0][1]}:{[h]:Object.fromEntries(g),...v};case"match"===u:return{[h]:Object.fromEntries(g),...v};case g.length>t||!!i||g.some((([e])=>"useCache"===e||"outputType"===e))||g.some((e=>Array.isArray(e[1]))):return{[h]:Object.fromEntries(g),...v};case 1===g.length:return{[h]:g[0][1],...v};default:return{[h]:Yr(s(r),g,a),...v}}};return d(e)},Yr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(Xr("additionalData",r,a.parameters))return Object.fromEntries(r);const e=Xr("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:i,aliases:n,required:o}of a.parameters){const a=[i,...n],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${i}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Xr=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},Zr=(e,r)=>u(e)&&!r.has(e),Kr=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},et=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},rt=(e,r)=>{const i=r.getOperators(),n=r.getFragments(),o=r.getCustomFunctions(),l=n.map((e=>e.name)),u=o.map((e=>e.name)),c=e=>{if(Array.isArray(e))return e.map((e=>c(e)));if(!f(e))return e;const n=Object.entries(e);if(0===n.length)return e;const o=n[0][0].replace("$",""),d=s(o),h=i.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=n[0][1];if(Array.isArray(s)){const t=s.map((e=>c(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...p(n)}}const i=c(s);if(!f(i)||!tt(i,h)||t(i)||a(i)){return{operator:e,[h.parameters[0].name]:i}}return{operator:e,...i,...p(n)}}if(m){const r=c(e[n[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...p(n)}}if(y){const e=o,r=n[0][1],s=c(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...p(n)}}return Object.fromEntries(n.map((([e,r])=>[e,c(r)])))},p=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,c(r)])))};return c(e)},tt=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};export{$r as AxiosClient,Fr as FetchClient,C as FigTreeError,Hr as FigTreeEvaluator,Br as SQLNodePostgres,zr as SQLite,rt as convertFromShorthand,Vr as convertToShorthand,Wr as convertV1ToV2,Mr as evaluateExpression,u as isAliasString,E as isFigTreeError,y as isFigTreeExpression,a as isFragmentNode,f as isObject,t as isOperatorNode,Jr as isV1Node,b as preProcessShorthand,s as standardiseOperatorName,o as truncateString};
1
+ import e from"object-property-extractor";import{dequal as r}from"dequal/lite";export{dequal}from"dequal/lite";const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},i=(e,r)=>r[s(e)],n=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),c=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,p=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),g={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},v=g,b=(e,r={},t,a=!0)=>a&&f(e)?T(e,r,t):e,T=(e,r,s)=>{if(t(e)||a(e))return e;const i=Object.entries(e),n=i.filter((([e])=>u(e))),o=i.filter((([e])=>!u(e)));return{...n.reduce(((e,[t,a])=>e={...e,...w(t,a,r,s)}),{}),...Object.fromEntries(o)}},w=(e,r,t,a)=>{const s=e.slice(1),n=i(s,v);return n?Array.isArray(r)?{operator:n,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:n,...r}:{operator:n,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class C extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),i=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===i?"":i}`}}const E=e=>e instanceof C,A=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:i=!1})=>{if(void 0!==e)return e;if(a instanceof C){if(!i)throw a;return a.prettyPrint}const n=new C("string"==typeof a?new Error(a):a,r,t,s);if(i)return n.prettyPrint;throw n},S=e=>f(e)&&"literal"in e,q=({value:e,name:r,expectedType:t})=>{if(S(t)){const{literal:a}=t;return!!a.includes(e)||j(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===q({value:e,name:r,expectedType:t})))||j(r,e,t.join("|"));return!!(0,N[t])(e)||j(r,e,t)},O=(...e)=>{const r=[];return e.forEach((e=>{const t=q(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},N={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},j=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${P(r)}) is not of type: ${t}`:`- ${P(r)} is not of type: ${t}`,P=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},x=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},L=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(S(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const i=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:i}})),k=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},I=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=O(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},U=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,R=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>U(e))):t?null===s?null:U(s):s},D=e=>/^https?:\/\/.+/.test(e),Q=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,i=r.slice(a,s);return""===i?e:e+(0===t?"":"/")+i}),""),_=async(e,r)=>{const{url:t,params:a={},data:s={},headers:i={},method:n="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[n]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...i},params:a,data:s})}catch(r){e.throwError(r)}},$=async(e,r)=>{const{options:s,operators:n,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const p=Object.keys(r.options?.functions??{});u=b(u,r.options?.fragments,p,!s.noShorthand),Array.isArray(u)&&(u=await F(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:i,useCache:n,input:o,args:l,...u}=e,c={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(c.fallback=a),void 0!==s&&(c.outputType=s),void 0!==i&&(c.type=i),void 0!==n&&(c.useCache=n),void 0!==l&&(c.args=l),void 0!==o?c.input=o:Object.keys(u).length>0&&(c.input=u),c})(u,r)),s.evaluateFullObject&&!h&&!m)return c(await M(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:c(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[i,n]=await F([e.fragment,e.parameters],r),o=b(s?.fragments?.[i],s.fragments,p,!s.noShorthand);if(void 0===o)return A({fallback:await $(y,r),error:`Fragment not defined: ${i}`,expression:u,returnErrorAsString:g});if(!t(o))return c(o,r);u={...e,...o,...n},delete u.fragment}const v=u,T=i(v.operator,o);if(!T)return A({fallback:await $(y,r),error:`Invalid operator: ${v.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return A({fallback:await $(y,r),error:`Excluded operator: ${v.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:C,parseChildren:E}=n[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,v);const q=await H(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await $(S.children,O)),!Array.isArray(S.children))return A({fallback:await $(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=E(S,O),delete S.children}catch(e){return A({fallback:await $(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let N;try{N=await C(S,O)}catch(e){return A({fallback:await $(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const j=S?.outputType??S?.type;if(!j)return N;const P=await $(j,r);return P in d?d[P](N):A({fallback:await $(y,r),operator:T,error:`- Invalid output type: ${P}`,expression:S,returnErrorAsString:g})},F=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>$(e,r)))):await $(e,r),H=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push($(e[t],r))));const s=await Promise.all(a),i=k(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(i[t[e]]=i?.[r]??r);return i},M=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=b(e,r.options?.fragments,t);if(!f(a))return e;const s=[],i=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(i.push(e,$(t,r)),delete a[e])}));const n=await Promise.all(i);r.resolvedAliasNodes={...r.resolvedAliasNodes,...I(n)},Object.entries(a).forEach((([e,t])=>{s.push(e,$(t,r))}));const o=await Promise.all(s);return c(I(o),r)},G=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],B=x(G),z={description:"Logical AND",aliases:["and","&","&&"],parameters:G},W=e=>{const r=e.children;return{...e,values:r}},J={propertyAliases:B,operatorData:z,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(z.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:W},V=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],Y=x(V),X={description:"Logical OR",aliases:["or","|","||"],parameters:V},Z={propertyAliases:Y,operatorData:X,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(X.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:W},K=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],ee=x(K),re={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:K},te={propertyAliases:ee,operatorData:re,evaluate:async(e,t)=>{const[a,s,i]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(L(re.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.every((e=>r(e,n[0]))):n.every((e=>null==e))},parseChildren:W},ae=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],se=x(ae),ie={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:ae},ne={propertyAliases:se,operatorData:ie,evaluate:async(e,t)=>{const[a,s,i]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(L(ie.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:i}));const n=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==i?i:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==n[0]&&void 0!==n[0]?n.some((e=>!r(e,n[0]))):n.some((e=>null===e&&void 0===e))},parseChildren:W},oe=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],le=x(oe),ue={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:oe},ce={propertyAliases:le,operatorData:ue,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(ue.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:W},pe=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],de=x(pe),he={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:pe},me={propertyAliases:de,operatorData:he,evaluate:async(e,r)=>{const[t,a,s]=await F([e.values,e.from,e.subtract],r);r.typeChecker(L(he.parameters,{values:t,from:a,subtract:s}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return i[0]-i[1]},parseChildren:W},fe=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],ye=x(fe),ge={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:fe},ve={propertyAliases:ye,operatorData:ge,evaluate:async(e,r)=>{const t=await F(e.values,r);if(r.typeChecker(L(ge.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:W},be=[{name:"values",description:"Array of values - 1st element will be divided by the first",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder"]},default:"quotient"}],Te=x(be),we={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:be},Ce={propertyAliases:Te,operatorData:we,evaluate:async(e,r)=>{const[t,a,s,i]=await F([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(L(we.parameters,{values:t,dividend:a,divisor:s,output:i}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===n[1])throw new Error("Division by zero!");switch(i){case"quotient":return Math.floor(n[0]/n[1]);case"remainder":return n[0]%n[1];default:return n[0]/n[1]}},parseChildren:W},Ee=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ae=x(Ee),Se={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:Ee},qe={propertyAliases:Ae,operatorData:Se,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(L(Se.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s>i},parseChildren:W},Oe=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ne=x(Oe),je={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Oe},Pe={propertyAliases:Ne,operatorData:je,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(L(je.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,i]=t;return s===i&&!a||s<i},parseChildren:W},xe=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],Le=x(xe),ke={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:xe},Ie={propertyAliases:Le,operatorData:ke,evaluate:async(e,r)=>{r.typeChecker(L(ke.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await $(e.condition,r)?await $(e.valueIfTrue,r):await $(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},Ue=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Re=x(Ue),De={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:Ue},Qe={propertyAliases:Re,operatorData:De,evaluate:async(e,r)=>{const[t,a]=await F([e.testString,e.pattern],r);r.typeChecker(L(De.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},_e=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],$e=x(_e),Fe={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:_e},He={propertyAliases:$e,operatorData:Fe,evaluate:async(r,t)=>{const[a,s={}]=await F([r.property,r.additionalData],t);t.typeChecker(L(Fe.parameters,{property:a,additionalData:s}));const i={...t.options?.data??{},...s};return e(i,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},Me=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],Ge=x(Me),Be={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:Me},ze={propertyAliases:Ge,operatorData:Be,evaluate:async(e,r)=>{const[t,a={},s=!0,i="%",n={}]=await F([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(L(Be.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:i,numberMapping:n})),Array.isArray(a)){const e="$"===i?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),n=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(n),l=k(Array.from(o),a.map((e=>s?String(e).trim():e)));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(`\\${e}`,e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace("\\{{","{{"));continue}const t=await We(e,a,n,r);l.push(s?String(t).trim():t)}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},We=async(r,t,a,s)=>{const i=s.options?.data??{},n=r.replace(/{{(.+)}}/,"$1"),o=await $(e(t,n,e(i,n,"")),s);if("number"!=typeof o)return o;if(!(n in a))return o;const l=a[n];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[n]),c=u.find((e=>e.startsWith(">")));if(c){if(o>Number(c.slice(1)))return l?.[c]}const p=u.find((e=>e.startsWith("<")));if(p){if(o<Number(p.slice(1)))return l?.[p]}return l.other?l.other.replace("{}",String(o)):o},Je=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],Ve=x(Je),Ye={description:"Count elements in an array",aliases:["count","length"],parameters:Je},Xe={propertyAliases:Ve,operatorData:Ye,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(L(Ye.parameters,{values:t})),t.length},parseChildren:W},Ze=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],Ke=x(Ze),er={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Ze},rr=" ",tr={propertyAliases:Ke,operatorData:er,evaluate:async(e,r)=>{const[t,a,s,i]=await F([e.value,e.delimiter??rr,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(L(er.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:i}));let n=t.split(a);return s&&(n=n.map((e=>e.trim()))),i&&""===n[n.length-1]&&n.pop(),n},parseChildren:e=>{const[r,t=rr]=e.children;return{...e,value:r,delimiter:t}}},ar=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],sr=x(ar),ir={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:ar},nr={propertyAliases:sr,operatorData:ir,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,i,n,o,l]=await F([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(L(ir.parameters,{query:a,single:i,flatten:n,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,i)=>{const n=await t.query({query:e,values:r})||[];["array","string","number"].includes(i??"")&&(s=!0);const o=s?n.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):n;return a?o[0]:o}),a,s,i,n,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},or=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],lr=x(or),ur={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:or},cr={propertyAliases:lr,operatorData:ur,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,i,n,o,l]=await F([e.query,e.url,await M(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:c}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...L(ur.parameters,{url:u,query:a,variables:i,returnNode:n,headers:o,useCache:l}),{name:"headers",value:c,expectedType:["object","null"]}]);const p=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=D(p)?p:Q(d,p),m={query:a,variables:i},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const i=await _(t,{url:e,method:"post",data:r,headers:a});return R(i?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...c,...o},n);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,i=Array.isArray(a)?a:[a],n=s.slice(0,i.length),o=k(i,n),l={...e,query:r,url:t,variables:o};return s.length>i.length&&(l.returnNode=s.pop()),l}},pr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],dr=x(pr),hr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:pr},mr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],i=a.slice(0,s.length),n=k(s,i),o={...e,url:r,parameters:n};return a.length>s.length&&(o.returnProperty=a.pop()),o},fr=mr,yr={propertyAliases:dr,operatorData:hr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await F([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...L(hr.parameters,{url:l,returnProperty:i,headers:n,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...n},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await _(t,{url:e,params:r,headers:a});return R(i,s)}),D(l)?l:Q(c,l),s,p,i);return h},parseChildren:mr},gr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],vr=x(gr),br={description:"HTTP POST Request",aliases:["POST","post"],parameters:gr},Tr={propertyAliases:vr,operatorData:br,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,i,n,o]=await F([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...L(br.parameters,{url:l,headers:n,data:s,returnProperty:i,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...n},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const i=await _(t,{url:e,data:r,headers:a,method:"post"});return R(i,s)}),D(l)?l:Q(c,l),s,p,i);return h},parseChildren:fr},wr=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],Cr=x(wr),Er={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:wr},Ar=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},Sr={propertyAliases:Cr,operatorData:Er,evaluate:async(e,r)=>{const t=await F(e.properties,r);r.typeChecker(L(Er.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Ar({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await F(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Ar},qr=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],Or={propertyAliases:x(qr),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:qr},evaluate:async(e,r)=>{const a=await $(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?I(e.branches):e.branches??{},i=t(s)?await $(s,r):s;if(!f(i))throw new Error("Branches don't evaluate to an object");if(a in i)return await $(i[a],r);if("fallback"in i)return await $(i.fallback,r);if(a in e)return await $(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=I(t);return{...e,matchExpression:r,branches:a}}},Nr=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],jr=x(Nr),Pr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:Nr},xr={propertyAliases:jr,operatorData:Pr,evaluate:async(r,t)=>{const[a,s=[],i,n]=await F([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(L(Pr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const c=n??t.options.useCache??!1,p=[...void 0===i?[]:[await M(i,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(c,(async(e,...r)=>await u(...r)),a,...p)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Lr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],kr=x(Lr),Ir={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Lr},Ur={propertyAliases:kr,operatorData:Ir,evaluate:async(e,r)=>(r.typeChecker(L(Ir.parameters,{value:e.value})),await $(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Rr=Object.freeze({__proto__:null,AND:J,BUILD_OBJECT:Sr,CONDITIONAL:Ie,COUNT:Xe,CUSTOM_FUNCTIONS:xr,DIVIDE:Ce,EQUAL:te,GET:yr,GRAPHQL:cr,GREATER_THAN:qe,LESS_THAN:Pe,MATCH:Or,MULTIPLY:ve,NOT_EQUAL:ne,OBJECT_PROPERTIES:He,OR:Z,PASSTHRU:Ur,PLUS:ce,POST:Tr,REGEX:Qe,SPLIT:tr,SQL:nr,STRING_SUBSTITUTION:ze,SUBTRACT:me});class Dr{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Qr(t),s=a in this.store,i=Date.now(),n=s&&i-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=i,n&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:i},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Qr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),_r=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?Fr(window.fetch):void 0),$r=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),Fr=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,i=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",n=await e(t+i,{headers:a,method:"GET"}),o=await n.json();if(!n.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:n.status,error:n.statusText,url:n.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:i}=r,n=new URLSearchParams(s),o=n.size>0?`?${n.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(i),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class Hr{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=O(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.22.1",this.options=Gr(e),this.operators=n(Rr,this.options?.excludeOperators??[],g),this.operatorAliases=g,this.cache=new Dr({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=_r(e.graphQLConnection?.httpClient),this.httpClient=_r(e.httpClient)}async evaluate(e,r={}){const t=p(this.options,Gr(r),!0);return r.httpClient&&(this.httpClient=_r(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=_r(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await $(e,{options:t,operators:r.excludeOperators?n(Rr,r.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}getOptions(){return this.options}updateOptions(e){this.options=p(this.options,Gr(e),!1),this.options.excludeOperators&&(this.operators=n(Rr,this.options.excludeOperators,g))}getOperators(){const e=this.options.excludeOperators?n(Rr,this.options.excludeOperators,g):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(g))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:i,backgroundColor:n}=r;return e&&(a.description=e),t&&(a.argsDefault=t),s&&(a.inputDefault=s),i&&(a.textColor=i),n&&(a.backgroundColor=n),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?n(Rr,this.options.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Mr=(e,r)=>new Hr(r).evaluate(e),Gr=e=>"objects"in e?{...e,data:e.objects}:e,Br=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),zr=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),Wr=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const i=Jr(e)?(()=>{const{operator:a}=e,i=s(a),n=t.find((e=>e.name===i||e.aliases.includes(i)));if(n){const t=n.parseChildren(e,r.getConfig());delete t.children;const a=n.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,n={};for(const[e,r]of Object.entries(i)){const t="type"===e?"outputType":e;Array.isArray(r)?n[t]=r.map((e=>a(e))):n[t]=a(r)}return n};return a(e)},Jr=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Vr=(e,r,t=2)=>{const a=r.getOperators(),i=r.getFragments(),n=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=i.map((e=>e.name)),c=n.map((e=>e.name)),p=new Set([...l,...u,...c]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:i,fragment:n,...l}=e;if(!i&&!n)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));if(i&&Array.isArray(l.children)){const e=s(i),t=a.find((r=>r.name===e||r.aliases.includes(e)));if(t){const e=t.parseChildren({...l,operator:i},r.getConfig());return delete e.children,d(e)}}const u=c.includes(i);n&&l?.parameters&&(Object.entries(l.parameters).forEach((([e,r])=>{l[e]=r})),delete l.parameters);const h=u?i:et(i,a),m=`$${h??n}`,y=n?rt(n,o):[],g=Object.keys(l).filter((e=>Kr(e,p)&&!y.includes(e))),v=Object.entries(l).filter((([e])=>!g.includes(e)&&!y.includes(e))).map((([e,r])=>[e,d(r)])),b=Object.fromEntries(g.map((e=>[e,d(l[e])]))),T=Object.fromEntries(y.map((e=>[e,d(l[e])])));switch(!0){case Object.keys(T).length>0:return{[m]:T,...b};case u:return 1!==v.length||"input"in l?{[m]:Object.fromEntries(v),...b}:{[m]:v[0][1]};case Xr(i,l,a):return 1===v.length?{[m]:v[0][1]}:{[m]:Object.fromEntries(v),...b};case"match"===h:return{[m]:Object.fromEntries(v),...b};case v.length>t||!!n||v.some((([e])=>"useCache"===e||"outputType"===e))||v.some((e=>Array.isArray(e[1]))):return{[m]:Object.fromEntries(v),...b};case 1===v.length:return{[m]:v[0][1],...b};default:return{[m]:Yr(s(i),v,a),...b}}};return d(e)},Yr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(Zr("additionalData",r,a.parameters))return Object.fromEntries(r);const e=Zr("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:i,aliases:n,required:o}of a.parameters){const a=[i,...n],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${i}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Xr=(e,r,t)=>{if(!e)return!1;const a=s(e),i=t.find((e=>e.name===a||e.aliases.includes(a)))?.parameters[0];if(!i)return!1;return!!("array"===i.type||Array.isArray(i.type)&&i.type.includes("array"))&&[i.name,...i.aliases].some((e=>e in r))},Zr=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},Kr=(e,r)=>u(e)&&!r.has(e),et=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},rt=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},tt=(e,r)=>{const i=r.getOperators(),n=r.getFragments(),o=r.getCustomFunctions(),l=n.map((e=>e.name)),u=o.map((e=>e.name)),c=e=>{if(Array.isArray(e))return e.map((e=>c(e)));if(!f(e))return e;const n=Object.entries(e);if(0===n.length)return e;const o=n[0][0].replace("$",""),d=s(o),h=i.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=n[0][1];if(Array.isArray(s)){const t=s.map((e=>c(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...p(n)}}const i=c(s);if(!f(i)||!at(i,h)||t(i)||a(i)){return{operator:e,[h.parameters[0].name]:i}}return{operator:e,...i,...p(n)}}if(m){const r=c(e[n[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...p(n)}}if(y){const e=o,r=n[0][1],s=c(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...p(n)}}return Object.fromEntries(n.map((([e,r])=>[e,c(r)])))},p=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,c(r)])))};return c(e)},at=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};export{$r as AxiosClient,Fr as FetchClient,C as FigTreeError,Hr as FigTreeEvaluator,Br as SQLNodePostgres,zr as SQLite,tt as convertFromShorthand,Vr as convertToShorthand,Wr as convertV1ToV2,Mr as evaluateExpression,u as isAliasString,E as isFigTreeError,y as isFigTreeExpression,a as isFragmentNode,f as isObject,t as isOperatorNode,Jr as isV1Node,b as preProcessShorthand,s as standardiseOperatorName,o as truncateString};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fig-tree-evaluator",
3
- "version": "2.22.0",
3
+ "version": "2.22.1",
4
4
  "description": "Module to evaluate JSON-structured expression trees",
5
5
  "main": "build/index.cjs.js",
6
6
  "module": "build/index.esm.js",