Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jsonpath-plus

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jsonpath-plus - npm Package Compare versions

Comparing version 9.0.0 to 10.0.0

src/Safe-Script.js

12

CHANGES.md
# CHANGES for jsonpath-plus
## 10.0.0
BREAKING CHANGES:
- Require Node 18+
- fix(security): use safe vm by default in Node
- chore: bump jsep, devDeps. and lint
## 9.0.0

@@ -9,4 +17,4 @@

- feat: add safe eval for browser and `eval` option (#185)
- feat: add `ignoreEvalErrors` property.
- feat: add safe eval for browser and `eval` option (#185) (@80avin)
- feat: add `ignoreEvalErrors` property (@80avin)

@@ -13,0 +21,0 @@ ## 8.1.0

2

dist/index-browser-esm.min.js

@@ -1,2 +0,2 @@

function e(e,t,n){return t=l(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,r()?Reflect.construct(t,n||[],l(e).constructor):t.apply(e,n))}function t(e,t,n){if(r())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var o=new(e.bind.apply(e,i));return n&&h(o,n.prototype),o}function r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(r=function(){return!!e})()}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,i(n.key),n)}}function u(e,t,r){return t&&s(e.prototype,t),r&&s(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function c(e,t,r){return(t=i(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function p(e){var r="function"==typeof Map?new Map:void 0;return p=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,n)}function n(){return t(e,arguments,l(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},p(e)}function f(e){return function(e){if(Array.isArray(e))return y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return y(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var b=function(){return u((function e(){a(this,e)}),[{key:"add",value:function(e,t,r){if("string"!=typeof arguments[0])for(var n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(e)?e:[e]).forEach((function(e){this[e]=this[e]||[],t&&this[e][r?"unshift":"push"](t)}),this)}},{key:"run",value:function(e,t){this[e]=this[e]||[],this[e].forEach((function(e){e.call(t&&t.context?t.context:t,t)}))}}])}(),v=function(){return u((function e(t){a(this,e),this.jsep=t,this.registered={}}),[{key:"register",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];r.forEach((function(t){if("object"!==o(t)||!t.name||!t.init)throw new Error("Invalid JSEP plugin format");e.registered[t.name]||(t.init(e.jsep),e.registered[t.name]=t)}))}}])}(),E=function(){function e(t){a(this,e),this.expr=t,this.index=0}return u(e,[{key:"char",get:function(){return this.expr.charAt(this.index)}},{key:"code",get:function(){return this.expr.charCodeAt(this.index)}},{key:"throwError",value:function(e){var t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}},{key:"runHook",value:function(t,r){if(e.hooks[t]){var n={context:this,node:r};return e.hooks.run(t,n),n.node}return r}},{key:"searchHook",value:function(t){if(e.hooks[t]){var r={context:this};return e.hooks[t].find((function(e){return e.call(r.context,r),r.node})),r.node}}},{key:"gobbleSpaces",value:function(){for(var t=this.code;t===e.SPACE_CODE||t===e.TAB_CODE||t===e.LF_CODE||t===e.CR_CODE;)t=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}},{key:"parse",value:function(){this.runHook("before-all");var t=this.gobbleExpressions(),r=1===t.length?t[0]:{type:e.COMPOUND,body:t};return this.runHook("after-all",r)}},{key:"gobbleExpressions",value:function(t){for(var r,n,i=[];this.index<this.expr.length;)if((r=this.code)===e.SEMCOL_CODE||r===e.COMMA_CODE)this.index++;else if(n=this.gobbleExpression())i.push(n);else if(this.index<this.expr.length){if(r===t)break;this.throwError('Unexpected "'+this.char+'"')}return i}},{key:"gobbleExpression",value:function(){var e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}},{key:"gobbleBinaryOp",value:function(){this.gobbleSpaces();for(var t=this.expr.substr(this.index,e.max_binop_len),r=t.length;r>0;){if(e.binary_ops.hasOwnProperty(t)&&(!e.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!e.isIdentifierPart(this.expr.charCodeAt(this.index+t.length))))return this.index+=r,t;t=t.substr(0,--r)}return!1}},{key:"gobbleBinaryExpression",value:function(){var t,r,n,i,o,a,s,u,c,l;if(!(a=this.gobbleToken()))return a;if(!(r=this.gobbleBinaryOp()))return a;for(o={value:r,prec:e.binaryPrecedence(r),right_a:e.right_associative.has(r)},(s=this.gobbleToken())||this.throwError("Expected expression after "+r),i=[a,o,s];r=this.gobbleBinaryOp();){if(0===(n=e.binaryPrecedence(r))){this.index-=r.length;break}o={value:r,prec:n,right_a:e.right_associative.has(r)},c=r;for(;i.length>2&&(l=i[i.length-2],o.right_a&&l.right_a?n>l.prec:n<=l.prec);)s=i.pop(),r=i.pop().value,a=i.pop(),t={type:e.BINARY_EXP,operator:r,left:a,right:s},i.push(t);(t=this.gobbleToken())||this.throwError("Expected expression after "+c),i.push(o,t)}for(t=i[u=i.length-1];u>1;)t={type:e.BINARY_EXP,operator:i[u-1].value,left:i[u-2],right:t},u-=2;return t}},{key:"gobbleToken",value:function(){var t,r,n,i;if(this.gobbleSpaces(),i=this.searchHook("gobble-token"))return this.runHook("after-token",i);if(t=this.code,e.isDecimalDigit(t)||t===e.PERIOD_CODE)return this.gobbleNumericLiteral();if(t===e.SQUOTE_CODE||t===e.DQUOTE_CODE)i=this.gobbleStringLiteral();else if(t===e.OBRACK_CODE)i=this.gobbleArray();else{for(n=(r=this.expr.substr(this.index,e.max_unop_len)).length;n>0;){if(e.unary_ops.hasOwnProperty(r)&&(!e.isIdentifierStart(this.code)||this.index+r.length<this.expr.length&&!e.isIdentifierPart(this.expr.charCodeAt(this.index+r.length)))){this.index+=n;var o=this.gobbleToken();return o||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:e.UNARY_EXP,operator:r,argument:o,prefix:!0})}r=r.substr(0,--n)}e.isIdentifierStart(t)?(i=this.gobbleIdentifier(),e.literals.hasOwnProperty(i.name)?i={type:e.LITERAL,value:e.literals[i.name],raw:i.name}:i.name===e.this_str&&(i={type:e.THIS_EXP})):t===e.OPAREN_CODE&&(i=this.gobbleGroup())}return i?(i=this.gobbleTokenProperty(i),this.runHook("after-token",i)):this.runHook("after-token",!1)}},{key:"gobbleTokenProperty",value:function(t){this.gobbleSpaces();for(var r=this.code;r===e.PERIOD_CODE||r===e.OBRACK_CODE||r===e.OPAREN_CODE||r===e.QUMARK_CODE;){var n=void 0;if(r===e.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==e.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),r=this.code}this.index++,r===e.OBRACK_CODE?(t={type:e.MEMBER_EXP,computed:!0,object:t,property:this.gobbleExpression()},this.gobbleSpaces(),(r=this.code)!==e.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):r===e.OPAREN_CODE?t={type:e.CALL_EXP,arguments:this.gobbleArguments(e.CPAREN_CODE),callee:t}:(r===e.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),t={type:e.MEMBER_EXP,computed:!1,object:t,property:this.gobbleIdentifier()}),n&&(t.optional=!0),this.gobbleSpaces(),r=this.code}return t}},{key:"gobbleNumericLiteral",value:function(){for(var t,r,n="";e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);if(this.code===e.PERIOD_CODE)for(n+=this.expr.charAt(this.index++);e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);if("e"===(t=this.char)||"E"===t){for(n+=this.expr.charAt(this.index++),"+"!==(t=this.char)&&"-"!==t||(n+=this.expr.charAt(this.index++));e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);e.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+n+this.char+")")}return r=this.code,e.isIdentifierStart(r)?this.throwError("Variable names cannot start with a number ("+n+this.char+")"):(r===e.PERIOD_CODE||1===n.length&&n.charCodeAt(0)===e.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:e.LITERAL,value:parseFloat(n),raw:n}}},{key:"gobbleStringLiteral",value:function(){for(var t="",r=this.index,n=this.expr.charAt(this.index++),i=!1;this.index<this.expr.length;){var o=this.expr.charAt(this.index++);if(o===n){i=!0;break}if("\\"===o)switch(o=this.expr.charAt(this.index++)){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+="\t";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;default:t+=o}else t+=o}return i||this.throwError('Unclosed quote after "'+t+'"'),{type:e.LITERAL,value:t,raw:this.expr.substring(r,this.index)}}},{key:"gobbleIdentifier",value:function(){var t=this.code,r=this.index;for(e.isIdentifierStart(t)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(t=this.code,e.isIdentifierPart(t));)this.index++;return{type:e.IDENTIFIER,name:this.expr.slice(r,this.index)}}},{key:"gobbleArguments",value:function(t){for(var r=[],n=!1,i=0;this.index<this.expr.length;){this.gobbleSpaces();var o=this.code;if(o===t){n=!0,this.index++,t===e.CPAREN_CODE&&i&&i>=r.length&&this.throwError("Unexpected token "+String.fromCharCode(t));break}if(o===e.COMMA_CODE){if(this.index++,++i!==r.length)if(t===e.CPAREN_CODE)this.throwError("Unexpected token ,");else if(t===e.CBRACK_CODE)for(var a=r.length;a<i;a++)r.push(null)}else if(r.length!==i&&0!==i)this.throwError("Expected comma");else{var s=this.gobbleExpression();s&&s.type!==e.COMPOUND||this.throwError("Expected comma"),r.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(t)),r}},{key:"gobbleGroup",value:function(){this.index++;var t=this.gobbleExpressions(e.CPAREN_CODE);if(this.code===e.CPAREN_CODE)return this.index++,1===t.length?t[0]:!!t.length&&{type:e.SEQUENCE_EXP,expressions:t};this.throwError("Unclosed (")}},{key:"gobbleArray",value:function(){return this.index++,{type:e.ARRAY_EXP,elements:this.gobbleArguments(e.CBRACK_CODE)}}}],[{key:"version",get:function(){return"1.3.8"}},{key:"toString",value:function(){return"JavaScript Expression Parser (JSEP) v"+e.version}},{key:"addUnaryOp",value:function(t){return e.max_unop_len=Math.max(t.length,e.max_unop_len),e.unary_ops[t]=1,e}},{key:"addBinaryOp",value:function(t,r,n){return e.max_binop_len=Math.max(t.length,e.max_binop_len),e.binary_ops[t]=r,n?e.right_associative.add(t):e.right_associative.delete(t),e}},{key:"addIdentifierChar",value:function(t){return e.additional_identifier_chars.add(t),e}},{key:"addLiteral",value:function(t,r){return e.literals[t]=r,e}},{key:"removeUnaryOp",value:function(t){return delete e.unary_ops[t],t.length===e.max_unop_len&&(e.max_unop_len=e.getMaxKeyLen(e.unary_ops)),e}},{key:"removeAllUnaryOps",value:function(){return e.unary_ops={},e.max_unop_len=0,e}},{key:"removeIdentifierChar",value:function(t){return e.additional_identifier_chars.delete(t),e}},{key:"removeBinaryOp",value:function(t){return delete e.binary_ops[t],t.length===e.max_binop_len&&(e.max_binop_len=e.getMaxKeyLen(e.binary_ops)),e.right_associative.delete(t),e}},{key:"removeAllBinaryOps",value:function(){return e.binary_ops={},e.max_binop_len=0,e}},{key:"removeLiteral",value:function(t){return delete e.literals[t],e}},{key:"removeAllLiterals",value:function(){return e.literals={},e}},{key:"parse",value:function(t){return new e(t).parse()}},{key:"getMaxKeyLen",value:function(e){return Math.max.apply(Math,[0].concat(f(Object.keys(e).map((function(e){return e.length})))))}},{key:"isDecimalDigit",value:function(e){return e>=48&&e<=57}},{key:"binaryPrecedence",value:function(t){return e.binary_ops[t]||0}},{key:"isIdentifierStart",value:function(t){return t>=65&&t<=90||t>=97&&t<=122||t>=128&&!e.binary_ops[String.fromCharCode(t)]||e.additional_identifier_chars.has(String.fromCharCode(t))}},{key:"isIdentifierPart",value:function(t){return e.isIdentifierStart(t)||e.isDecimalDigit(t)}}])}(),g=new b;Object.assign(E,{hooks:g,plugins:new v(E),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},right_associative:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"}),E.max_unop_len=E.getMaxKeyLen(E.unary_ops),E.max_binop_len=E.getMaxKeyLen(E.binary_ops);var x=function(e){return new E(e).parse()};Object.getOwnPropertyNames(E).forEach((function(e){void 0===x[e]&&"prototype"!==e&&(x[e]=E[e])})),x.Jsep=E;var F={name:"ternary",init:function(e){e.hooks.add("after-expression",(function(t){if(t.node&&this.code===e.QUMARK_CODE){this.index++;var r=t.node,n=this.gobbleExpression();if(n||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;var i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:"ConditionalExpression",test:r,consequent:n,alternate:i},r.operator&&e.binary_ops[r.operator]<=.9){for(var o=r;o.right.operator&&e.binary_ops[o.right.operator]<=.9;)o=o.right;t.node.test=o.right,o.right=t.node,t.node=r}}else this.throwError("Expected :")}}))}};x.plugins.register(F);var D={name:"regex",init:function(e){e.hooks.add("gobble-token",(function(t){if(47===this.code){for(var r=++this.index,n=!1;this.index<this.expr.length;){if(47===this.code&&!n){for(var i=this.expr.slice(r,this.index),o="";++this.index<this.expr.length;){var a=this.code;if(!(a>=97&&a<=122||a>=65&&a<=90||a>=48&&a<=57))break;o+=this.char}var s=void 0;try{s=new RegExp(i,o)}catch(e){this.throwError(e.message)}return t.node={type:e.LITERAL,value:s,raw:this.expr.slice(r-1,this.index)},t.node=this.gobbleTokenProperty(t.node),t.node}this.code===e.OBRACK_CODE?n=!0:n&&this.code===e.CBRACK_CODE&&(n=!1),this.index+=92===this.code?2:1}this.throwError("Unclosed Regex")}}))}},_={name:"assignment",assignmentOperators:new Set(["=","*=","**=","/=","%=","+=","-=","<<=",">>=",">>>=","&=","^=","|="]),updateOperators:[43,45],assignmentPrecedence:.9,init:function(e){var t=[e.IDENTIFIER,e.MEMBER_EXP];function r(e){_.assignmentOperators.has(e.operator)?(e.type="AssignmentExpression",r(e.left),r(e.right)):e.operator||Object.values(e).forEach((function(e){e&&"object"===o(e)&&r(e)}))}_.assignmentOperators.forEach((function(t){return e.addBinaryOp(t,_.assignmentPrecedence,!0)})),e.hooks.add("gobble-token",(function(e){var r=this,n=this.code;_.updateOperators.some((function(e){return e===n&&e===r.expr.charCodeAt(r.index+1)}))&&(this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:this.gobbleTokenProperty(this.gobbleIdentifier()),prefix:!0},e.node.argument&&t.includes(e.node.argument.type)||this.throwError("Unexpected ".concat(e.node.operator)))})),e.hooks.add("after-token",(function(e){var r=this;if(e.node){var n=this.code;_.updateOperators.some((function(e){return e===n&&e===r.expr.charCodeAt(r.index+1)}))&&(t.includes(e.node.type)||this.throwError("Unexpected ".concat(e.node.operator)),this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:e.node,prefix:!1})}})),e.hooks.add("after-expression",(function(e){e.node&&r(e.node)}))}},m=Object.prototype.hasOwnProperty;function C(e,t){return(e=e.slice()).push(t),e}function O(e,t){return(t=t.slice()).unshift(e),t}var A=function(t){function r(t){var n;return a(this,r),(n=e(this,r,['JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'])).avoidNew=!0,n.value=t,n.name="NewError",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(r,p(Error)),u(r)}();function w(e,t,r,n,i){if(!(this instanceof w))try{return new w(e,t,r,n,i)}catch(e){if(!e.avoidNew)throw e;return e.value}"string"==typeof e&&(i=n,n=r,r=t,t=e,e=null);var a=e&&"object"===o(e);if(e=e||{},this.json=e.json||r,this.path=e.path||t,this.resultType=e.resultType||"value",this.flatten=e.flatten||!1,this.wrap=!m.call(e,"wrap")||e.wrap,this.sandbox=e.sandbox||{},this.eval=void 0===e.eval?"safe":e.eval,this.ignoreEvalErrors=void 0!==e.ignoreEvalErrors&&e.ignoreEvalErrors,this.parent=e.parent||null,this.parentProperty=e.parentProperty||null,this.callback=e.callback||n||null,this.otherTypeCallback=e.otherTypeCallback||i||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==e.autostart){var s={path:a?e.path:t};a?"json"in e&&(s.json=e.json):s.json=r;var u=this.evaluate(s);if(!u||"object"!==o(u))throw new A(u);return u}}w.prototype.evaluate=function(e,t,r,n){var i=this,a=this.parent,s=this.parentProperty,u=this.flatten,c=this.wrap;if(this.currResultType=this.resultType,this.currEval=this.eval,this.currSandbox=this.sandbox,r=r||this.callback,this.currOtherTypeCallback=n||this.otherTypeCallback,t=t||this.json,(e=e||this.path)&&"object"===o(e)&&!Array.isArray(e)){if(!e.path&&""!==e.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!m.call(e,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');t=e.json,u=m.call(e,"flatten")?e.flatten:u,this.currResultType=m.call(e,"resultType")?e.resultType:this.currResultType,this.currSandbox=m.call(e,"sandbox")?e.sandbox:this.currSandbox,c=m.call(e,"wrap")?e.wrap:c,this.currEval=m.call(e,"eval")?e.eval:this.currEval,r=m.call(e,"callback")?e.callback:r,this.currOtherTypeCallback=m.call(e,"otherTypeCallback")?e.otherTypeCallback:this.currOtherTypeCallback,a=m.call(e,"parent")?e.parent:a,s=m.call(e,"parentProperty")?e.parentProperty:s,e=e.path}if(a=a||null,s=s||null,Array.isArray(e)&&(e=w.toPathString(e)),(e||""===e)&&t){var l=w.toPathArray(e);"$"===l[0]&&l.length>1&&l.shift(),this._hasParentSelector=null;var h=this._trace(l,t,["$"],a,s,r).filter((function(e){return e&&!e.isParentSelector}));return h.length?c||1!==h.length||h[0].hasArrExpr?h.reduce((function(e,t){var r=i._getPreferredOutput(t);return u&&Array.isArray(r)?e=e.concat(r):e.push(r),e}),[]):this._getPreferredOutput(h[0]):c?[]:void 0}},w.prototype._getPreferredOutput=function(e){var t=this.currResultType;switch(t){case"all":var r=Array.isArray(e.path)?e.path:w.toPathArray(e.path);return e.pointer=w.toPointer(r),e.path="string"==typeof e.path?e.path:w.toPathString(e.path),e;case"value":case"parent":case"parentProperty":return e[t];case"path":return w.toPathString(e[t]);case"pointer":return w.toPointer(e.path);default:throw new TypeError("Unknown result type")}},w.prototype._handleCallback=function(e,t,r){if(t){var n=this._getPreferredOutput(e);e.path="string"==typeof e.path?e.path:w.toPathString(e.path),t(n,r,e)}},w.prototype._trace=function(e,t,r,n,i,a,s,u){var c,l=this;if(!e.length)return c={path:r,value:t,parent:n,parentProperty:i,hasArrExpr:s},this._handleCallback(c,a,"value"),c;var h=e[0],p=e.slice(1),f=[];function y(e){Array.isArray(e)?e.forEach((function(e){f.push(e)})):f.push(e)}if(("string"!=typeof h||u)&&t&&m.call(t,h))y(this._trace(p,t[h],C(r,h),t,h,a,s));else if("*"===h)this._walk(t,(function(e){y(l._trace(p,t[e],C(r,e),t,e,a,!0,!0))}));else if(".."===h)y(this._trace(p,t,r,n,i,a,s)),this._walk(t,(function(n){"object"===o(t[n])&&y(l._trace(e.slice(),t[n],C(r,n),t,n,a,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:r.slice(0,-1),expr:p,isParentSelector:!0};if("~"===h)return c={path:C(r,h),value:i,parent:n,parentProperty:null},this._handleCallback(c,a,"property"),c;if("$"===h)y(this._trace(p,t,r,null,null,a,s));else if(/^(\x2D?[0-9]*):(\x2D?[0-9]*):?([0-9]*)$/.test(h))y(this._slice(h,p,t,r,n,i,a));else if(0===h.indexOf("?(")){if(!1===this.currEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");var b=h.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/,"$1"),v=/@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])?((?:[\0->@-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))(?!(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])\)\])['\]]/g.exec(b);v?this._walk(t,(function(e){var o=[v[2]],s=v[1]?t[e][v[1]]:t[e];l._trace(o,s,r,n,i,a,!0).length>0&&y(l._trace(p,t[e],C(r,e),t,e,a,!0))})):this._walk(t,(function(e){l._eval(b,t[e],e,r,n,i)&&y(l._trace(p,t[e],C(r,e),t,e,a,!0))}))}else if("("===h[0]){if(!1===this.currEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");y(this._trace(O(this._eval(h,t,r[r.length-1],r.slice(0,-1),n,i),p),t,r,n,i,a,s))}else if("@"===h[0]){var E=!1,g=h.slice(1,-2);switch(g){case"scalar":t&&["object","function"].includes(o(t))||(E=!0);break;case"boolean":case"string":case"undefined":case"function":o(t)===g&&(E=!0);break;case"integer":!Number.isFinite(t)||t%1||(E=!0);break;case"number":Number.isFinite(t)&&(E=!0);break;case"nonFinite":"number"!=typeof t||Number.isFinite(t)||(E=!0);break;case"object":t&&o(t)===g&&(E=!0);break;case"array":Array.isArray(t)&&(E=!0);break;case"other":E=this.currOtherTypeCallback(t,r,n,i);break;case"null":null===t&&(E=!0);break;default:throw new TypeError("Unknown value type "+g)}if(E)return c={path:r,value:t,parent:n,parentProperty:i},this._handleCallback(c,a,"value"),c}else if("`"===h[0]&&t&&m.call(t,h.slice(1))){var x=h.slice(1);y(this._trace(p,t[x],C(r,x),t,x,a,s,!0))}else if(h.includes(",")){var F,D=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=d(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}(h.split(","));try{for(D.s();!(F=D.n()).done;){var _=F.value;y(this._trace(O(_,p),t,r,n,i,a,!0))}}catch(e){D.e(e)}finally{D.f()}}else!u&&t&&m.call(t,h)&&y(this._trace(p,t[h],C(r,h),t,h,a,s,!0))}if(this._hasParentSelector)for(var A=0;A<f.length;A++){var w=f[A];if(w&&w.isParentSelector){var k=this._trace(w.expr,t,w.path,n,i,a,s);if(Array.isArray(k)){f[A]=k[0];for(var P=k.length,S=1;S<P;S++)A++,f.splice(A,0,k[S])}else f[A]=k}}return f},w.prototype._walk=function(e,t){if(Array.isArray(e))for(var r=e.length,n=0;n<r;n++)t(n);else e&&"object"===o(e)&&Object.keys(e).forEach((function(e){t(e)}))},w.prototype._slice=function(e,t,r,n,i,o,a){if(Array.isArray(r)){var s=r.length,u=e.split(":"),c=u[2]&&Number.parseInt(u[2])||1,l=u[0]&&Number.parseInt(u[0])||0,h=u[1]&&Number.parseInt(u[1])||s;l=l<0?Math.max(0,l+s):Math.min(s,l),h=h<0?Math.max(0,h+s):Math.min(s,h);for(var p=[],f=l;f<h;f+=c){this._trace(O(f,t),r,n,i,o,a,!0).forEach((function(e){p.push(e)}))}return p}},w.prototype._eval=function(e,t,r,n,i,o){var a=this;this.currSandbox._$_parentProperty=o,this.currSandbox._$_parent=i,this.currSandbox._$_property=r,this.currSandbox._$_root=this.json,this.currSandbox._$_v=t;var s=e.includes("@path");s&&(this.currSandbox._$_path=w.toPathString(n.concat([r])));var u=this.currEval+"Script:"+e;if(!w.cache[u]){var c=e.replace(/@parentProperty/g,"_$_parentProperty").replace(/@parent/g,"_$_parent").replace(/@property/g,"_$_property").replace(/@root/g,"_$_root").replace(/@([\t-\r \)\.\[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF])/g,"_$_v$1");if(s&&(c=c.replace(/@path/g,"_$_path")),"safe"===this.currEval||!0===this.currEval||void 0===this.currEval)w.cache[u]=new this.safeVm.Script(c);else if("native"===this.currEval)w.cache[u]=new this.vm.Script(c);else if("function"==typeof this.currEval&&this.currEval.prototype&&m.call(this.currEval.prototype,"runInNewContext")){var l=this.currEval;w.cache[u]=new l(c)}else{if("function"!=typeof this.currEval)throw new TypeError('Unknown "eval" property "'.concat(this.currEval,'"'));w.cache[u]={runInNewContext:function(e){return a.currEval(c,e)}}}}try{return w.cache[u].runInNewContext(this.currSandbox)}catch(t){if(this.ignoreEvalErrors)return!1;throw new Error("jsonPath: "+t.message+": "+e)}},w.cache={},w.toPathString=function(e){for(var t=e,r=t.length,n="$",i=1;i<r;i++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(t[i])||(n+=/^[\*0-9]+$/.test(t[i])?"["+t[i]+"]":"['"+t[i]+"']");return n},w.toPointer=function(e){for(var t=e,r=t.length,n="",i=1;i<r;i++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(t[i])||(n+="/"+t[i].toString().replace(/~/g,"~0").replace(/\//g,"~1"));return n},w.toPathArray=function(e){var t=w.cache;if(t[e])return t[e].concat();var r=[],n=e.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g,";$&;").replace(/['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))['\]](?!(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])\])/g,(function(e,t){return"[#"+(r.push(t)-1)+"]"})).replace(/\[["']((?:[\0-&\(-\\\^-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)["']\]/g,(function(e,t){return"['"+t.replace(/\./g,"%@%").replace(/~/g,"%%@@%%")+"']"})).replace(/~/g,";~;").replace(/["']?\.["']?(?!(?:[\0-Z\\-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*\])|\[["']?/g,";").replace(/%@%/g,".").replace(/%%@@%%/g,"~").replace(/(?:;)?(\^+)(?:;)?/g,(function(e,t){return";"+t.split("").join(";")+";"})).replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").split(";").map((function(e){var t=e.match(/#([0-9]+)/);return t&&t[1]?r[t[1]]:e}));return t[e]=n,t[e].concat()};x.plugins.register(D,_);var k={evalAst:function(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":return k.evalBinaryExpression(e,t);case"Compound":return k.evalCompound(e,t);case"ConditionalExpression":return k.evalConditionalExpression(e,t);case"Identifier":return k.evalIdentifier(e,t);case"Literal":return k.evalLiteral(e,t);case"MemberExpression":return k.evalMemberExpression(e,t);case"UnaryExpression":return k.evalUnaryExpression(e,t);case"ArrayExpression":return k.evalArrayExpression(e,t);case"CallExpression":return k.evalCallExpression(e,t);case"AssignmentExpression":return k.evalAssignmentExpression(e,t);default:throw SyntaxError("Unexpected expression",e)}},evalBinaryExpression:function(e,t){return{"||":function(e,t){return e||t()},"&&":function(e,t){return e&&t()},"|":function(e,t){return e|t()},"^":function(e,t){return e^t()},"&":function(e,t){return e&t()},"==":function(e,t){return e==t()},"!=":function(e,t){return e!=t()},"===":function(e,t){return e===t()},"!==":function(e,t){return e!==t()},"<":function(e,t){return e<t()},">":function(e,t){return e>t()},"<=":function(e,t){return e<=t()},">=":function(e,t){return e>=t()},"<<":function(e,t){return e<<t()},">>":function(e,t){return e>>t()},">>>":function(e,t){return e>>>t()},"+":function(e,t){return e+t()},"-":function(e,t){return e-t()},"*":function(e,t){return e*t()},"/":function(e,t){return e/t()},"%":function(e,t){return e%t()}}[e.operator](k.evalAst(e.left,t),(function(){return k.evalAst(e.right,t)}))},evalCompound:function(e,t){for(var r,n=0;n<e.body.length;n++){"Identifier"===e.body[n].type&&["var","let","const"].includes(e.body[n].name)&&e.body[n+1]&&"AssignmentExpression"===e.body[n+1].type&&(n+=1);var i=e.body[n];r=k.evalAst(i,t)}return r},evalConditionalExpression:function(e,t){return k.evalAst(e.test,t)?k.evalAst(e.consequent,t):k.evalAst(e.alternate,t)},evalIdentifier:function(e,t){if(e.name in t)return t[e.name];throw ReferenceError("".concat(e.name," is not defined"))},evalLiteral:function(e){return e.value},evalMemberExpression:function(e,t){var r=e.computed?k.evalAst(e.property):e.property.name,n=k.evalAst(e.object,t),i=n[r];return"function"==typeof i?i.bind(n):i},evalUnaryExpression:function(e,t){return{"-":function(e){return-k.evalAst(e,t)},"!":function(e){return!k.evalAst(e,t)},"~":function(e){return~k.evalAst(e,t)},"+":function(e){return+k.evalAst(e,t)}}[e.operator](e.argument)},evalArrayExpression:function(e,t){return e.elements.map((function(e){return k.evalAst(e,t)}))},evalCallExpression:function(e,t){var r=e.arguments.map((function(e){return k.evalAst(e,t)}));return k.evalAst(e.callee,t).apply(void 0,f(r))},evalAssignmentExpression:function(e,t){if("Identifier"!==e.left.type)throw SyntaxError("Invalid left-hand side in assignment");var r=e.left.name,n=k.evalAst(e.right,t);return t[r]=n,t[r]}},P=function(){return u((function e(t){a(this,e),this.code=t,this.ast=x(this.code)}),[{key:"runInNewContext",value:function(e){var t=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach((function(t){c(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({},e);return k.evalAst(this.ast,t)}}])}(),S=function(){return u((function e(t){a(this,e),this.code=t}),[{key:"runInNewContext",value:function(e){var r=this.code,n=Object.keys(e),i=[];!function(e,t,r){for(var n=e.length,i=0;i<n;i++)r(e[i])&&t.push(e.splice(i--,1)[0])}(n,i,(function(t){return"function"==typeof e[t]}));var o=n.map((function(t){return e[t]})),a=i.reduce((function(t,r){var n=e[r].toString();return/function/.test(n)||(n="function "+n),"var "+r+"="+n+";"+t}),"");/(["'])use strict\1/.test(r=a+r)||n.includes("arguments")||(r="var arguments = undefined;"+r);var s=(r=r.replace(/;[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/,"")).lastIndexOf(";"),u=s>-1?r.slice(0,s+1)+" return "+r.slice(s+1):" return "+r;return t(Function,n.concat([u])).apply(void 0,f(o))}}])}();w.prototype.vm={Script:S},w.prototype.safeVm={Script:P};export{w as JSONPath,P as SafeScript};
function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function t(e,t,r){return t=s(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,u()?Reflect.construct(t,r||[],s(e).constructor):t.apply(e,r))}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t,r){if(u())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&h(i,r.prototype),i}function i(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,p(n.key),n)}}function o(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function a(e,t,r){return(t=p(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function u(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(u=function(){return!!e})()}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function l(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||d(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function f(e){return f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f(e)}function d(t,r){if(t){if("string"==typeof t)return e(t,r);var n={}.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e(t,r):void 0}}function y(e){var t="function"==typeof Map?new Map:void 0;return y=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return n(e,arguments,s(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),h(r,e)},y(e)}var b=function(){return o((function e(){r(this,e)}),[{key:"add",value:function(e,t,r){if("string"!=typeof arguments[0])for(var n in arguments[0])this.add(n,arguments[0][n],arguments[1]);else(Array.isArray(e)?e:[e]).forEach((function(e){this[e]=this[e]||[],t&&this[e][r?"unshift":"push"](t)}),this)}},{key:"run",value:function(e,t){this[e]=this[e]||[],this[e].forEach((function(e){e.call(t&&t.context?t.context:t,t)}))}}])}(),v=function(){return o((function e(t){r(this,e),this.jsep=t,this.registered={}}),[{key:"register",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];r.forEach((function(t){if("object"!==f(t)||!t.name||!t.init)throw new Error("Invalid JSEP plugin format");e.registered[t.name]||(t.init(e.jsep),e.registered[t.name]=t)}))}}])}(),E=function(){function e(t){r(this,e),this.expr=t,this.index=0}return o(e,[{key:"char",get:function(){return this.expr.charAt(this.index)}},{key:"code",get:function(){return this.expr.charCodeAt(this.index)}},{key:"throwError",value:function(e){var t=new Error(e+" at character "+this.index);throw t.index=this.index,t.description=e,t}},{key:"runHook",value:function(t,r){if(e.hooks[t]){var n={context:this,node:r};return e.hooks.run(t,n),n.node}return r}},{key:"searchHook",value:function(t){if(e.hooks[t]){var r={context:this};return e.hooks[t].find((function(e){return e.call(r.context,r),r.node})),r.node}}},{key:"gobbleSpaces",value:function(){for(var t=this.code;t===e.SPACE_CODE||t===e.TAB_CODE||t===e.LF_CODE||t===e.CR_CODE;)t=this.expr.charCodeAt(++this.index);this.runHook("gobble-spaces")}},{key:"parse",value:function(){this.runHook("before-all");var t=this.gobbleExpressions(),r=1===t.length?t[0]:{type:e.COMPOUND,body:t};return this.runHook("after-all",r)}},{key:"gobbleExpressions",value:function(t){for(var r,n,i=[];this.index<this.expr.length;)if((r=this.code)===e.SEMCOL_CODE||r===e.COMMA_CODE)this.index++;else if(n=this.gobbleExpression())i.push(n);else if(this.index<this.expr.length){if(r===t)break;this.throwError('Unexpected "'+this.char+'"')}return i}},{key:"gobbleExpression",value:function(){var e=this.searchHook("gobble-expression")||this.gobbleBinaryExpression();return this.gobbleSpaces(),this.runHook("after-expression",e)}},{key:"gobbleBinaryOp",value:function(){this.gobbleSpaces();for(var t=this.expr.substr(this.index,e.max_binop_len),r=t.length;r>0;){if(e.binary_ops.hasOwnProperty(t)&&(!e.isIdentifierStart(this.code)||this.index+t.length<this.expr.length&&!e.isIdentifierPart(this.expr.charCodeAt(this.index+t.length))))return this.index+=r,t;t=t.substr(0,--r)}return!1}},{key:"gobbleBinaryExpression",value:function(){var t,r,n,i,o,a,s,u,c,h;if(!(a=this.gobbleToken()))return a;if(!(r=this.gobbleBinaryOp()))return a;for(o={value:r,prec:e.binaryPrecedence(r),right_a:e.right_associative.has(r)},(s=this.gobbleToken())||this.throwError("Expected expression after "+r),i=[a,o,s];r=this.gobbleBinaryOp();){if(0===(n=e.binaryPrecedence(r))){this.index-=r.length;break}o={value:r,prec:n,right_a:e.right_associative.has(r)},c=r;for(;i.length>2&&(h=i[i.length-2],o.right_a&&h.right_a?n>h.prec:n<=h.prec);)s=i.pop(),r=i.pop().value,a=i.pop(),t={type:e.BINARY_EXP,operator:r,left:a,right:s},i.push(t);(t=this.gobbleToken())||this.throwError("Expected expression after "+c),i.push(o,t)}for(t=i[u=i.length-1];u>1;)t={type:e.BINARY_EXP,operator:i[u-1].value,left:i[u-2],right:t},u-=2;return t}},{key:"gobbleToken",value:function(){var t,r,n,i;if(this.gobbleSpaces(),i=this.searchHook("gobble-token"))return this.runHook("after-token",i);if(t=this.code,e.isDecimalDigit(t)||t===e.PERIOD_CODE)return this.gobbleNumericLiteral();if(t===e.SQUOTE_CODE||t===e.DQUOTE_CODE)i=this.gobbleStringLiteral();else if(t===e.OBRACK_CODE)i=this.gobbleArray();else{for(n=(r=this.expr.substr(this.index,e.max_unop_len)).length;n>0;){if(e.unary_ops.hasOwnProperty(r)&&(!e.isIdentifierStart(this.code)||this.index+r.length<this.expr.length&&!e.isIdentifierPart(this.expr.charCodeAt(this.index+r.length)))){this.index+=n;var o=this.gobbleToken();return o||this.throwError("missing unaryOp argument"),this.runHook("after-token",{type:e.UNARY_EXP,operator:r,argument:o,prefix:!0})}r=r.substr(0,--n)}e.isIdentifierStart(t)?(i=this.gobbleIdentifier(),e.literals.hasOwnProperty(i.name)?i={type:e.LITERAL,value:e.literals[i.name],raw:i.name}:i.name===e.this_str&&(i={type:e.THIS_EXP})):t===e.OPAREN_CODE&&(i=this.gobbleGroup())}return i?(i=this.gobbleTokenProperty(i),this.runHook("after-token",i)):this.runHook("after-token",!1)}},{key:"gobbleTokenProperty",value:function(t){this.gobbleSpaces();for(var r=this.code;r===e.PERIOD_CODE||r===e.OBRACK_CODE||r===e.OPAREN_CODE||r===e.QUMARK_CODE;){var n=void 0;if(r===e.QUMARK_CODE){if(this.expr.charCodeAt(this.index+1)!==e.PERIOD_CODE)break;n=!0,this.index+=2,this.gobbleSpaces(),r=this.code}this.index++,r===e.OBRACK_CODE?((t={type:e.MEMBER_EXP,computed:!0,object:t,property:this.gobbleExpression()}).property||this.throwError('Unexpected "'+this.char+'"'),this.gobbleSpaces(),(r=this.code)!==e.CBRACK_CODE&&this.throwError("Unclosed ["),this.index++):r===e.OPAREN_CODE?t={type:e.CALL_EXP,arguments:this.gobbleArguments(e.CPAREN_CODE),callee:t}:(r===e.PERIOD_CODE||n)&&(n&&this.index--,this.gobbleSpaces(),t={type:e.MEMBER_EXP,computed:!1,object:t,property:this.gobbleIdentifier()}),n&&(t.optional=!0),this.gobbleSpaces(),r=this.code}return t}},{key:"gobbleNumericLiteral",value:function(){for(var t,r,n="";e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);if(this.code===e.PERIOD_CODE)for(n+=this.expr.charAt(this.index++);e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);if("e"===(t=this.char)||"E"===t){for(n+=this.expr.charAt(this.index++),"+"!==(t=this.char)&&"-"!==t||(n+=this.expr.charAt(this.index++));e.isDecimalDigit(this.code);)n+=this.expr.charAt(this.index++);e.isDecimalDigit(this.expr.charCodeAt(this.index-1))||this.throwError("Expected exponent ("+n+this.char+")")}return r=this.code,e.isIdentifierStart(r)?this.throwError("Variable names cannot start with a number ("+n+this.char+")"):(r===e.PERIOD_CODE||1===n.length&&n.charCodeAt(0)===e.PERIOD_CODE)&&this.throwError("Unexpected period"),{type:e.LITERAL,value:parseFloat(n),raw:n}}},{key:"gobbleStringLiteral",value:function(){for(var t="",r=this.index,n=this.expr.charAt(this.index++),i=!1;this.index<this.expr.length;){var o=this.expr.charAt(this.index++);if(o===n){i=!0;break}if("\\"===o)switch(o=this.expr.charAt(this.index++)){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+="\t";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;default:t+=o}else t+=o}return i||this.throwError('Unclosed quote after "'+t+'"'),{type:e.LITERAL,value:t,raw:this.expr.substring(r,this.index)}}},{key:"gobbleIdentifier",value:function(){var t=this.code,r=this.index;for(e.isIdentifierStart(t)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(t=this.code,e.isIdentifierPart(t));)this.index++;return{type:e.IDENTIFIER,name:this.expr.slice(r,this.index)}}},{key:"gobbleArguments",value:function(t){for(var r=[],n=!1,i=0;this.index<this.expr.length;){this.gobbleSpaces();var o=this.code;if(o===t){n=!0,this.index++,t===e.CPAREN_CODE&&i&&i>=r.length&&this.throwError("Unexpected token "+String.fromCharCode(t));break}if(o===e.COMMA_CODE){if(this.index++,++i!==r.length)if(t===e.CPAREN_CODE)this.throwError("Unexpected token ,");else if(t===e.CBRACK_CODE)for(var a=r.length;a<i;a++)r.push(null)}else if(r.length!==i&&0!==i)this.throwError("Expected comma");else{var s=this.gobbleExpression();s&&s.type!==e.COMPOUND||this.throwError("Expected comma"),r.push(s)}}return n||this.throwError("Expected "+String.fromCharCode(t)),r}},{key:"gobbleGroup",value:function(){this.index++;var t=this.gobbleExpressions(e.CPAREN_CODE);if(this.code===e.CPAREN_CODE)return this.index++,1===t.length?t[0]:!!t.length&&{type:e.SEQUENCE_EXP,expressions:t};this.throwError("Unclosed (")}},{key:"gobbleArray",value:function(){return this.index++,{type:e.ARRAY_EXP,elements:this.gobbleArguments(e.CBRACK_CODE)}}}],[{key:"version",get:function(){return"1.3.9"}},{key:"toString",value:function(){return"JavaScript Expression Parser (JSEP) v"+e.version}},{key:"addUnaryOp",value:function(t){return e.max_unop_len=Math.max(t.length,e.max_unop_len),e.unary_ops[t]=1,e}},{key:"addBinaryOp",value:function(t,r,n){return e.max_binop_len=Math.max(t.length,e.max_binop_len),e.binary_ops[t]=r,n?e.right_associative.add(t):e.right_associative.delete(t),e}},{key:"addIdentifierChar",value:function(t){return e.additional_identifier_chars.add(t),e}},{key:"addLiteral",value:function(t,r){return e.literals[t]=r,e}},{key:"removeUnaryOp",value:function(t){return delete e.unary_ops[t],t.length===e.max_unop_len&&(e.max_unop_len=e.getMaxKeyLen(e.unary_ops)),e}},{key:"removeAllUnaryOps",value:function(){return e.unary_ops={},e.max_unop_len=0,e}},{key:"removeIdentifierChar",value:function(t){return e.additional_identifier_chars.delete(t),e}},{key:"removeBinaryOp",value:function(t){return delete e.binary_ops[t],t.length===e.max_binop_len&&(e.max_binop_len=e.getMaxKeyLen(e.binary_ops)),e.right_associative.delete(t),e}},{key:"removeAllBinaryOps",value:function(){return e.binary_ops={},e.max_binop_len=0,e}},{key:"removeLiteral",value:function(t){return delete e.literals[t],e}},{key:"removeAllLiterals",value:function(){return e.literals={},e}},{key:"parse",value:function(t){return new e(t).parse()}},{key:"getMaxKeyLen",value:function(e){return Math.max.apply(Math,[0].concat(l(Object.keys(e).map((function(e){return e.length})))))}},{key:"isDecimalDigit",value:function(e){return e>=48&&e<=57}},{key:"binaryPrecedence",value:function(t){return e.binary_ops[t]||0}},{key:"isIdentifierStart",value:function(t){return t>=65&&t<=90||t>=97&&t<=122||t>=128&&!e.binary_ops[String.fromCharCode(t)]||e.additional_identifier_chars.has(String.fromCharCode(t))}},{key:"isIdentifierPart",value:function(t){return e.isIdentifierStart(t)||e.isDecimalDigit(t)}}])}(),g=new b;Object.assign(E,{hooks:g,plugins:new v(E),COMPOUND:"Compound",SEQUENCE_EXP:"SequenceExpression",IDENTIFIER:"Identifier",MEMBER_EXP:"MemberExpression",LITERAL:"Literal",THIS_EXP:"ThisExpression",CALL_EXP:"CallExpression",UNARY_EXP:"UnaryExpression",BINARY_EXP:"BinaryExpression",ARRAY_EXP:"ArrayExpression",TAB_CODE:9,LF_CODE:10,CR_CODE:13,SPACE_CODE:32,PERIOD_CODE:46,COMMA_CODE:44,SQUOTE_CODE:39,DQUOTE_CODE:34,OPAREN_CODE:40,CPAREN_CODE:41,OBRACK_CODE:91,CBRACK_CODE:93,QUMARK_CODE:63,SEMCOL_CODE:59,COLON_CODE:58,unary_ops:{"-":1,"!":1,"~":1,"+":1},binary_ops:{"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10},right_associative:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"}),E.max_unop_len=E.getMaxKeyLen(E.unary_ops),E.max_binop_len=E.getMaxKeyLen(E.binary_ops);var x=function(e){return new E(e).parse()},F=Object.getOwnPropertyNames(o((function e(){r(this,e)})));Object.getOwnPropertyNames(E).filter((function(e){return!F.includes(e)&&void 0===x[e]})).forEach((function(e){x[e]=E[e]})),x.Jsep=E;var D={name:"ternary",init:function(e){e.hooks.add("after-expression",(function(t){if(t.node&&this.code===e.QUMARK_CODE){this.index++;var r=t.node,n=this.gobbleExpression();if(n||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;var i=this.gobbleExpression();if(i||this.throwError("Expected expression"),t.node={type:"ConditionalExpression",test:r,consequent:n,alternate:i},r.operator&&e.binary_ops[r.operator]<=.9){for(var o=r;o.right.operator&&e.binary_ops[o.right.operator]<=.9;)o=o.right;t.node.test=o.right,o.right=t.node,t.node=r}}else this.throwError("Expected :")}}))}};x.plugins.register(D);var _={name:"regex",init:function(e){e.hooks.add("gobble-token",(function(t){if(47===this.code){for(var r=++this.index,n=!1;this.index<this.expr.length;){if(47===this.code&&!n){for(var i=this.expr.slice(r,this.index),o="";++this.index<this.expr.length;){var a=this.code;if(!(a>=97&&a<=122||a>=65&&a<=90||a>=48&&a<=57))break;o+=this.char}var s=void 0;try{s=new RegExp(i,o)}catch(e){this.throwError(e.message)}return t.node={type:e.LITERAL,value:s,raw:this.expr.slice(r-1,this.index)},t.node=this.gobbleTokenProperty(t.node),t.node}this.code===e.OBRACK_CODE?n=!0:n&&this.code===e.CBRACK_CODE&&(n=!1),this.index+=92===this.code?2:1}this.throwError("Unclosed Regex")}}))}},O={name:"assignment",assignmentOperators:new Set(["=","*=","**=","/=","%=","+=","-=","<<=",">>=",">>>=","&=","^=","|="]),updateOperators:[43,45],assignmentPrecedence:.9,init:function(e){var t=[e.IDENTIFIER,e.MEMBER_EXP];function r(e){O.assignmentOperators.has(e.operator)?(e.type="AssignmentExpression",r(e.left),r(e.right)):e.operator||Object.values(e).forEach((function(e){e&&"object"===f(e)&&r(e)}))}O.assignmentOperators.forEach((function(t){return e.addBinaryOp(t,O.assignmentPrecedence,!0)})),e.hooks.add("gobble-token",(function(e){var r=this,n=this.code;O.updateOperators.some((function(e){return e===n&&e===r.expr.charCodeAt(r.index+1)}))&&(this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:this.gobbleTokenProperty(this.gobbleIdentifier()),prefix:!0},e.node.argument&&t.includes(e.node.argument.type)||this.throwError("Unexpected ".concat(e.node.operator)))})),e.hooks.add("after-token",(function(e){var r=this;if(e.node){var n=this.code;O.updateOperators.some((function(e){return e===n&&e===r.expr.charCodeAt(r.index+1)}))&&(t.includes(e.node.type)||this.throwError("Unexpected ".concat(e.node.operator)),this.index+=2,e.node={type:"UpdateExpression",operator:43===n?"++":"--",argument:e.node,prefix:!1})}})),e.hooks.add("after-expression",(function(e){e.node&&r(e.node)}))}};x.plugins.register(_,O);var m={evalAst:function(e,t){switch(e.type){case"BinaryExpression":case"LogicalExpression":return m.evalBinaryExpression(e,t);case"Compound":return m.evalCompound(e,t);case"ConditionalExpression":return m.evalConditionalExpression(e,t);case"Identifier":return m.evalIdentifier(e,t);case"Literal":return m.evalLiteral(e,t);case"MemberExpression":return m.evalMemberExpression(e,t);case"UnaryExpression":return m.evalUnaryExpression(e,t);case"ArrayExpression":return m.evalArrayExpression(e,t);case"CallExpression":return m.evalCallExpression(e,t);case"AssignmentExpression":return m.evalAssignmentExpression(e,t);default:throw SyntaxError("Unexpected expression",e)}},evalBinaryExpression:function(e,t){return{"||":function(e,t){return e||t()},"&&":function(e,t){return e&&t()},"|":function(e,t){return e|t()},"^":function(e,t){return e^t()},"&":function(e,t){return e&t()},"==":function(e,t){return e==t()},"!=":function(e,t){return e!=t()},"===":function(e,t){return e===t()},"!==":function(e,t){return e!==t()},"<":function(e,t){return e<t()},">":function(e,t){return e>t()},"<=":function(e,t){return e<=t()},">=":function(e,t){return e>=t()},"<<":function(e,t){return e<<t()},">>":function(e,t){return e>>t()},">>>":function(e,t){return e>>>t()},"+":function(e,t){return e+t()},"-":function(e,t){return e-t()},"*":function(e,t){return e*t()},"/":function(e,t){return e/t()},"%":function(e,t){return e%t()}}[e.operator](m.evalAst(e.left,t),(function(){return m.evalAst(e.right,t)}))},evalCompound:function(e,t){for(var r,n=0;n<e.body.length;n++){"Identifier"===e.body[n].type&&["var","let","const"].includes(e.body[n].name)&&e.body[n+1]&&"AssignmentExpression"===e.body[n+1].type&&(n+=1);var i=e.body[n];r=m.evalAst(i,t)}return r},evalConditionalExpression:function(e,t){return m.evalAst(e.test,t)?m.evalAst(e.consequent,t):m.evalAst(e.alternate,t)},evalIdentifier:function(e,t){if(e.name in t)return t[e.name];throw ReferenceError("".concat(e.name," is not defined"))},evalLiteral:function(e){return e.value},evalMemberExpression:function(e,t){var r=e.computed?m.evalAst(e.property):e.property.name,n=m.evalAst(e.object,t),i=n[r];return"function"==typeof i?i.bind(n):i},evalUnaryExpression:function(e,t){return{"-":function(e){return-m.evalAst(e,t)},"!":function(e){return!m.evalAst(e,t)},"~":function(e){return~m.evalAst(e,t)},"+":function(e){return+m.evalAst(e,t)}}[e.operator](e.argument)},evalArrayExpression:function(e,t){return e.elements.map((function(e){return m.evalAst(e,t)}))},evalCallExpression:function(e,t){var r=e.arguments.map((function(e){return m.evalAst(e,t)}));return m.evalAst(e.callee,t).apply(void 0,l(r))},evalAssignmentExpression:function(e,t){if("Identifier"!==e.left.type)throw SyntaxError("Invalid left-hand side in assignment");var r=e.left.name,n=m.evalAst(e.right,t);return t[r]=n,t[r]}},C=function(){return o((function e(t){r(this,e),this.code=t,this.ast=x(this.code)}),[{key:"runInNewContext",value:function(e){var t=function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?c(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):c(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}({},e);return m.evalAst(this.ast,t)}}])}();function w(e,t){return(e=e.slice()).push(t),e}function A(e,t){return(t=t.slice()).unshift(e),t}var k=function(){function e(n){var i;return r(this,e),(i=t(this,e,['JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'])).avoidNew=!0,i.value=n,i.name="NewError",i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(e,y(Error)),o(e)}();function P(e,t,r,n,i){if(!(this instanceof P))try{return new P(e,t,r,n,i)}catch(e){if(!e.avoidNew)throw e;return e.value}"string"==typeof e&&(i=n,n=r,r=t,t=e,e=null);var o=e&&"object"===f(e);if(e=e||{},this.json=e.json||r,this.path=e.path||t,this.resultType=e.resultType||"value",this.flatten=e.flatten||!1,this.wrap=!Object.hasOwn(e,"wrap")||e.wrap,this.sandbox=e.sandbox||{},this.eval=void 0===e.eval?"safe":e.eval,this.ignoreEvalErrors=void 0!==e.ignoreEvalErrors&&e.ignoreEvalErrors,this.parent=e.parent||null,this.parentProperty=e.parentProperty||null,this.callback=e.callback||n||null,this.otherTypeCallback=e.otherTypeCallback||i||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==e.autostart){var a={path:o?e.path:t};o?"json"in e&&(a.json=e.json):a.json=r;var s=this.evaluate(a);if(!s||"object"!==f(s))throw new k(s);return s}}P.prototype.evaluate=function(e,t,r,n){var i=this,o=this.parent,a=this.parentProperty,s=this.flatten,u=this.wrap;if(this.currResultType=this.resultType,this.currEval=this.eval,this.currSandbox=this.sandbox,r=r||this.callback,this.currOtherTypeCallback=n||this.otherTypeCallback,t=t||this.json,(e=e||this.path)&&"object"===f(e)&&!Array.isArray(e)){if(!e.path&&""!==e.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!Object.hasOwn(e,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');t=e.json,s=Object.hasOwn(e,"flatten")?e.flatten:s,this.currResultType=Object.hasOwn(e,"resultType")?e.resultType:this.currResultType,this.currSandbox=Object.hasOwn(e,"sandbox")?e.sandbox:this.currSandbox,u=Object.hasOwn(e,"wrap")?e.wrap:u,this.currEval=Object.hasOwn(e,"eval")?e.eval:this.currEval,r=Object.hasOwn(e,"callback")?e.callback:r,this.currOtherTypeCallback=Object.hasOwn(e,"otherTypeCallback")?e.otherTypeCallback:this.currOtherTypeCallback,o=Object.hasOwn(e,"parent")?e.parent:o,a=Object.hasOwn(e,"parentProperty")?e.parentProperty:a,e=e.path}if(o=o||null,a=a||null,Array.isArray(e)&&(e=P.toPathString(e)),(e||""===e)&&t){var c=P.toPathArray(e);"$"===c[0]&&c.length>1&&c.shift(),this._hasParentSelector=null;var h=this._trace(c,t,["$"],o,a,r).filter((function(e){return e&&!e.isParentSelector}));return h.length?u||1!==h.length||h[0].hasArrExpr?h.reduce((function(e,t){var r=i._getPreferredOutput(t);return s&&Array.isArray(r)?e=e.concat(r):e.push(r),e}),[]):this._getPreferredOutput(h[0]):u?[]:void 0}},P.prototype._getPreferredOutput=function(e){var t=this.currResultType;switch(t){case"all":var r=Array.isArray(e.path)?e.path:P.toPathArray(e.path);return e.pointer=P.toPointer(r),e.path="string"==typeof e.path?e.path:P.toPathString(e.path),e;case"value":case"parent":case"parentProperty":return e[t];case"path":return P.toPathString(e[t]);case"pointer":return P.toPointer(e.path);default:throw new TypeError("Unknown result type")}},P.prototype._handleCallback=function(e,t,r){if(t){var n=this._getPreferredOutput(e);e.path="string"==typeof e.path?e.path:P.toPathString(e.path),t(n,r,e)}},P.prototype._trace=function(e,t,r,n,i,o,a,s){var u,c=this;if(!e.length)return u={path:r,value:t,parent:n,parentProperty:i,hasArrExpr:a},this._handleCallback(u,o,"value"),u;var h=e[0],l=e.slice(1),p=[];function y(e){Array.isArray(e)?e.forEach((function(e){p.push(e)})):p.push(e)}if(("string"!=typeof h||s)&&t&&Object.hasOwn(t,h))y(this._trace(l,t[h],w(r,h),t,h,o,a));else if("*"===h)this._walk(t,(function(e){y(c._trace(l,t[e],w(r,e),t,e,o,!0,!0))}));else if(".."===h)y(this._trace(l,t,r,n,i,o,a)),this._walk(t,(function(n){"object"===f(t[n])&&y(c._trace(e.slice(),t[n],w(r,n),t,n,o,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:r.slice(0,-1),expr:l,isParentSelector:!0};if("~"===h)return u={path:w(r,h),value:i,parent:n,parentProperty:null},this._handleCallback(u,o,"property"),u;if("$"===h)y(this._trace(l,t,r,null,null,o,a));else if(/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(h))y(this._slice(h,l,t,r,n,i,o));else if(0===h.indexOf("?(")){if(!1===this.currEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");var b=h.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/,"$1"),v=/@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])?((?:[\0->@-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))(?!(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])\)\])['\]]/g.exec(b);v?this._walk(t,(function(e){var a=[v[2]],s=v[1]?t[e][v[1]]:t[e];c._trace(a,s,r,n,i,o,!0).length>0&&y(c._trace(l,t[e],w(r,e),t,e,o,!0))})):this._walk(t,(function(e){c._eval(b,t[e],e,r,n,i)&&y(c._trace(l,t[e],w(r,e),t,e,o,!0))}))}else if("("===h[0]){if(!1===this.currEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");y(this._trace(A(this._eval(h,t,r[r.length-1],r.slice(0,-1),n,i),l),t,r,n,i,o,a))}else if("@"===h[0]){var E=!1,g=h.slice(1,-2);switch(g){case"scalar":t&&["object","function"].includes(f(t))||(E=!0);break;case"boolean":case"string":case"undefined":case"function":f(t)===g&&(E=!0);break;case"integer":!Number.isFinite(t)||t%1||(E=!0);break;case"number":Number.isFinite(t)&&(E=!0);break;case"nonFinite":"number"!=typeof t||Number.isFinite(t)||(E=!0);break;case"object":t&&f(t)===g&&(E=!0);break;case"array":Array.isArray(t)&&(E=!0);break;case"other":E=this.currOtherTypeCallback(t,r,n,i);break;case"null":null===t&&(E=!0);break;default:throw new TypeError("Unknown value type "+g)}if(E)return u={path:r,value:t,parent:n,parentProperty:i},this._handleCallback(u,o,"value"),u}else if("`"===h[0]&&t&&Object.hasOwn(t,h.slice(1))){var x=h.slice(1);y(this._trace(l,t[x],w(r,x),t,x,o,a,!0))}else if(h.includes(",")){var F,D=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=d(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}(h.split(","));try{for(D.s();!(F=D.n()).done;){var _=F.value;y(this._trace(A(_,l),t,r,n,i,o,!0))}}catch(e){D.e(e)}finally{D.f()}}else!s&&t&&Object.hasOwn(t,h)&&y(this._trace(l,t[h],w(r,h),t,h,o,a,!0))}if(this._hasParentSelector)for(var O=0;O<p.length;O++){var m=p[O];if(m&&m.isParentSelector){var C=this._trace(m.expr,t,m.path,n,i,o,a);if(Array.isArray(C)){p[O]=C[0];for(var k=C.length,P=1;P<k;P++)O++,p.splice(O,0,C[P])}else p[O]=C}}return p},P.prototype._walk=function(e,t){if(Array.isArray(e))for(var r=e.length,n=0;n<r;n++)t(n);else e&&"object"===f(e)&&Object.keys(e).forEach((function(e){t(e)}))},P.prototype._slice=function(e,t,r,n,i,o,a){if(Array.isArray(r)){var s=r.length,u=e.split(":"),c=u[2]&&Number.parseInt(u[2])||1,h=u[0]&&Number.parseInt(u[0])||0,l=u[1]&&Number.parseInt(u[1])||s;h=h<0?Math.max(0,h+s):Math.min(s,h),l=l<0?Math.max(0,l+s):Math.min(s,l);for(var p=[],f=h;f<l;f+=c){this._trace(A(f,t),r,n,i,o,a,!0).forEach((function(e){p.push(e)}))}return p}},P.prototype._eval=function(e,t,r,n,i,o){var a=this;this.currSandbox._$_parentProperty=o,this.currSandbox._$_parent=i,this.currSandbox._$_property=r,this.currSandbox._$_root=this.json,this.currSandbox._$_v=t;var s=e.includes("@path");s&&(this.currSandbox._$_path=P.toPathString(n.concat([r])));var u=this.currEval+"Script:"+e;if(!P.cache[u]){var c=e.replace(/@parentProperty/g,"_$_parentProperty").replace(/@parent/g,"_$_parent").replace(/@property/g,"_$_property").replace(/@root/g,"_$_root").replace(/@([\t-\r \)\.\[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF])/g,"_$_v$1");if(s&&(c=c.replace(/@path/g,"_$_path")),"safe"===this.currEval||!0===this.currEval||void 0===this.currEval)P.cache[u]=new this.safeVm.Script(c);else if("native"===this.currEval)P.cache[u]=new this.vm.Script(c);else if("function"==typeof this.currEval&&this.currEval.prototype&&Object.hasOwn(this.currEval.prototype,"runInNewContext")){var h=this.currEval;P.cache[u]=new h(c)}else{if("function"!=typeof this.currEval)throw new TypeError('Unknown "eval" property "'.concat(this.currEval,'"'));P.cache[u]={runInNewContext:function(e){return a.currEval(c,e)}}}}try{return P.cache[u].runInNewContext(this.currSandbox)}catch(t){if(this.ignoreEvalErrors)return!1;throw new Error("jsonPath: "+t.message+": "+e)}},P.cache={},P.toPathString=function(e){for(var t=e,r=t.length,n="$",i=1;i<r;i++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(t[i])||(n+=/^[\*0-9]+$/.test(t[i])?"["+t[i]+"]":"['"+t[i]+"']");return n},P.toPointer=function(e){for(var t=e,r=t.length,n="",i=1;i<r;i++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(t[i])||(n+="/"+t[i].toString().replace(/~/g,"~0").replace(/\//g,"~1"));return n},P.toPathArray=function(e){var t=P.cache;if(t[e])return t[e].concat();var r=[],n=e.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g,";$&;").replace(/['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))['\]](?!(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])\])/g,(function(e,t){return"[#"+(r.push(t)-1)+"]"})).replace(/\[["']((?:[\0-&\(-\\\^-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)["']\]/g,(function(e,t){return"['"+t.replace(/\./g,"%@%").replace(/~/g,"%%@@%%")+"']"})).replace(/~/g,";~;").replace(/["']?\.["']?(?!(?:[\0-Z\\-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*\])|\[["']?/g,";").replace(/%@%/g,".").replace(/%%@@%%/g,"~").replace(/(?:;)?(\^+)(?:;)?/g,(function(e,t){return";"+t.split("").join(";")+";"})).replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").split(";").map((function(e){var t=e.match(/#([0-9]+)/);return t&&t[1]?r[t[1]]:e}));return t[e]=n,t[e].concat()},P.prototype.safeVm={Script:C};var S=function(){return o((function e(t){r(this,e),this.code=t}),[{key:"runInNewContext",value:function(e){var t=this.code,r=Object.keys(e),i=[];!function(e,t,r){for(var n=e.length,i=0;i<n;i++)r(e[i])&&t.push(e.splice(i--,1)[0])}(r,i,(function(t){return"function"==typeof e[t]}));var o=r.map((function(t){return e[t]})),a=i.reduce((function(t,r){var n=e[r].toString();return/function/.test(n)||(n="function "+n),"var "+r+"="+n+";"+t}),"");/(["'])use strict\1/.test(t=a+t)||r.includes("arguments")||(t="var arguments = undefined;"+t);var s=(t=t.replace(/;[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/,"")).lastIndexOf(";"),u=s>-1?t.slice(0,s+1)+" return "+t.slice(s+1):" return "+t;return n(Function,r.concat([u])).apply(void 0,l(o))}}])}();P.prototype.vm={Script:S};export{P as JSONPath};
//# sourceMappingURL=index-browser-esm.min.js.map
import vm from 'vm';
/**
* @implements {IHooks}
*/
class Hooks {
/**
* @callback HookCallback
* @this {*|Jsep} this
* @param {Jsep} env
* @returns: void
*/
/**
* Adds the given callback to the list of callbacks for the given hook.
*
* The callback will be invoked when the hook it is registered for is run.
*
* One callback function can be registered to multiple hooks and the same hook multiple times.
*
* @param {string|object} name The name of the hook, or an object of callbacks keyed by name
* @param {HookCallback|boolean} callback The callback function which is given environment variables.
* @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
* @public
*/
add(name, callback, first) {
if (typeof arguments[0] != 'string') {
// Multiple hook callbacks, keyed by name
for (let name in arguments[0]) {
this.add(name, arguments[0][name], arguments[1]);
}
} else {
(Array.isArray(name) ? name : [name]).forEach(function (name) {
this[name] = this[name] || [];
if (callback) {
this[name][first ? 'unshift' : 'push'](callback);
}
}, this);
}
}
/**
* Runs a hook invoking all registered callbacks with the given environment variables.
*
* Callbacks will be invoked synchronously and in the order in which they were registered.
*
* @param {string} name The name of the hook.
* @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
* @public
*/
run(name, env) {
this[name] = this[name] || [];
this[name].forEach(function (callback) {
callback.call(env && env.context ? env.context : env, env);
});
}
}
/**
* @implements {IPlugins}
*/
class Plugins {
constructor(jsep) {
this.jsep = jsep;
this.registered = {};
}
/**
* @callback PluginSetup
* @this {Jsep} jsep
* @returns: void
*/
/**
* Adds the given plugin(s) to the registry
*
* @param {object} plugins
* @param {string} plugins.name The name of the plugin
* @param {PluginSetup} plugins.init The init function
* @public
*/
register(...plugins) {
plugins.forEach(plugin => {
if (typeof plugin !== 'object' || !plugin.name || !plugin.init) {
throw new Error('Invalid JSEP plugin format');
}
if (this.registered[plugin.name]) {
// already registered. Ignore.
return;
}
plugin.init(this.jsep);
this.registered[plugin.name] = plugin;
});
}
}
// JavaScript Expression Parser (JSEP) 1.3.9
class Jsep {
/**
* @returns {string}
*/
static get version() {
// To be filled in by the template
return '1.3.9';
}
/**
* @returns {string}
*/
static toString() {
return 'JavaScript Expression Parser (JSEP) v' + Jsep.version;
}
// ==================== CONFIG ================================
/**
* @method addUnaryOp
* @param {string} op_name The name of the unary op to add
* @returns {Jsep}
*/
static addUnaryOp(op_name) {
Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
Jsep.unary_ops[op_name] = 1;
return Jsep;
}
/**
* @method jsep.addBinaryOp
* @param {string} op_name The name of the binary op to add
* @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
* @param {boolean} [isRightAssociative=false] whether operator is right-associative
* @returns {Jsep}
*/
static addBinaryOp(op_name, precedence, isRightAssociative) {
Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
Jsep.binary_ops[op_name] = precedence;
if (isRightAssociative) {
Jsep.right_associative.add(op_name);
} else {
Jsep.right_associative.delete(op_name);
}
return Jsep;
}
/**
* @method addIdentifierChar
* @param {string} char The additional character to treat as a valid part of an identifier
* @returns {Jsep}
*/
static addIdentifierChar(char) {
Jsep.additional_identifier_chars.add(char);
return Jsep;
}
/**
* @method addLiteral
* @param {string} literal_name The name of the literal to add
* @param {*} literal_value The value of the literal
* @returns {Jsep}
*/
static addLiteral(literal_name, literal_value) {
Jsep.literals[literal_name] = literal_value;
return Jsep;
}
/**
* @method removeUnaryOp
* @param {string} op_name The name of the unary op to remove
* @returns {Jsep}
*/
static removeUnaryOp(op_name) {
delete Jsep.unary_ops[op_name];
if (op_name.length === Jsep.max_unop_len) {
Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
}
return Jsep;
}
/**
* @method removeAllUnaryOps
* @returns {Jsep}
*/
static removeAllUnaryOps() {
Jsep.unary_ops = {};
Jsep.max_unop_len = 0;
return Jsep;
}
/**
* @method removeIdentifierChar
* @param {string} char The additional character to stop treating as a valid part of an identifier
* @returns {Jsep}
*/
static removeIdentifierChar(char) {
Jsep.additional_identifier_chars.delete(char);
return Jsep;
}
/**
* @method removeBinaryOp
* @param {string} op_name The name of the binary op to remove
* @returns {Jsep}
*/
static removeBinaryOp(op_name) {
delete Jsep.binary_ops[op_name];
if (op_name.length === Jsep.max_binop_len) {
Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
}
Jsep.right_associative.delete(op_name);
return Jsep;
}
/**
* @method removeAllBinaryOps
* @returns {Jsep}
*/
static removeAllBinaryOps() {
Jsep.binary_ops = {};
Jsep.max_binop_len = 0;
return Jsep;
}
/**
* @method removeLiteral
* @param {string} literal_name The name of the literal to remove
* @returns {Jsep}
*/
static removeLiteral(literal_name) {
delete Jsep.literals[literal_name];
return Jsep;
}
/**
* @method removeAllLiterals
* @returns {Jsep}
*/
static removeAllLiterals() {
Jsep.literals = {};
return Jsep;
}
// ==================== END CONFIG ============================
/**
* @returns {string}
*/
get char() {
return this.expr.charAt(this.index);
}
/**
* @returns {number}
*/
get code() {
return this.expr.charCodeAt(this.index);
}
/**
* @param {string} expr a string with the passed in express
* @returns Jsep
*/
constructor(expr) {
// `index` stores the character number we are currently at
// All of the gobbles below will modify `index` as we move along
this.expr = expr;
this.index = 0;
}
/**
* static top-level parser
* @returns {jsep.Expression}
*/
static parse(expr) {
return new Jsep(expr).parse();
}
/**
* Get the longest key length of any object
* @param {object} obj
* @returns {number}
*/
static getMaxKeyLen(obj) {
return Math.max(0, ...Object.keys(obj).map(k => k.length));
}
/**
* `ch` is a character code in the next three functions
* @param {number} ch
* @returns {boolean}
*/
static isDecimalDigit(ch) {
return ch >= 48 && ch <= 57; // 0...9
}
/**
* Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
* @param {string} op_val
* @returns {number}
*/
static binaryPrecedence(op_val) {
return Jsep.binary_ops[op_val] || 0;
}
/**
* Looks for start of identifier
* @param {number} ch
* @returns {boolean}
*/
static isIdentifierStart(ch) {
return ch >= 65 && ch <= 90 ||
// A...Z
ch >= 97 && ch <= 122 ||
// a...z
ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] ||
// any non-ASCII that is not an operator
Jsep.additional_identifier_chars.has(String.fromCharCode(ch)); // additional characters
}
/**
* @param {number} ch
* @returns {boolean}
*/
static isIdentifierPart(ch) {
return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
}
/**
* throw error at index of the expression
* @param {string} message
* @throws
*/
throwError(message) {
const error = new Error(message + ' at character ' + this.index);
error.index = this.index;
error.description = message;
throw error;
}
/**
* Run a given hook
* @param {string} name
* @param {jsep.Expression|false} [node]
* @returns {?jsep.Expression}
*/
runHook(name, node) {
if (Jsep.hooks[name]) {
const env = {
context: this,
node
};
Jsep.hooks.run(name, env);
return env.node;
}
return node;
}
/**
* Runs a given hook until one returns a node
* @param {string} name
* @returns {?jsep.Expression}
*/
searchHook(name) {
if (Jsep.hooks[name]) {
const env = {
context: this
};
Jsep.hooks[name].find(function (callback) {
callback.call(env.context, env);
return env.node;
});
return env.node;
}
}
/**
* Push `index` up to the next non-space character
*/
gobbleSpaces() {
let ch = this.code;
// Whitespace
while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
ch = this.expr.charCodeAt(++this.index);
}
this.runHook('gobble-spaces');
}
/**
* Top-level method to parse all expressions and returns compound or single node
* @returns {jsep.Expression}
*/
parse() {
this.runHook('before-all');
const nodes = this.gobbleExpressions();
// If there's only one expression just try returning the expression
const node = nodes.length === 1 ? nodes[0] : {
type: Jsep.COMPOUND,
body: nodes
};
return this.runHook('after-all', node);
}
/**
* top-level parser (but can be reused within as well)
* @param {number} [untilICode]
* @returns {jsep.Expression[]}
*/
gobbleExpressions(untilICode) {
let nodes = [],
ch_i,
node;
while (this.index < this.expr.length) {
ch_i = this.code;
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
this.index++; // ignore separators
} else {
// Try to gobble each expression individually
if (node = this.gobbleExpression()) {
nodes.push(node);
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
} else if (this.index < this.expr.length) {
if (ch_i === untilICode) {
break;
}
this.throwError('Unexpected "' + this.char + '"');
}
}
}
return nodes;
}
/**
* The main parsing function.
* @returns {?jsep.Expression}
*/
gobbleExpression() {
const node = this.searchHook('gobble-expression') || this.gobbleBinaryExpression();
this.gobbleSpaces();
return this.runHook('after-expression', node);
}
/**
* Search for the operation portion of the string (e.g. `+`, `===`)
* Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
* and move down from 3 to 2 to 1 character until a matching binary operation is found
* then, return that binary operation
* @returns {string|boolean}
*/
gobbleBinaryOp() {
this.gobbleSpaces();
let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
let tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept a binary op when it is an identifier.
// Binary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
this.index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
}
/**
* This function is responsible for gobbling an individual expression,
* e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
* @returns {?jsep.BinaryExpression}
*/
gobbleBinaryExpression() {
let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
// First, try to get the leftmost thing
// Then, check to see if there's a binary operator operating on that leftmost thing
// Don't gobbleBinaryOp without a left-hand-side
left = this.gobbleToken();
if (!left) {
return left;
}
biop = this.gobbleBinaryOp();
// If there wasn't a binary operator, just return the leftmost node
if (!biop) {
return left;
}
// Otherwise, we need to start a stack to properly place the binary operations in their
// precedence structure
biop_info = {
value: biop,
prec: Jsep.binaryPrecedence(biop),
right_a: Jsep.right_associative.has(biop)
};
right = this.gobbleToken();
if (!right) {
this.throwError("Expected expression after " + biop);
}
stack = [left, biop_info, right];
// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
while (biop = this.gobbleBinaryOp()) {
prec = Jsep.binaryPrecedence(biop);
if (prec === 0) {
this.index -= biop.length;
break;
}
biop_info = {
value: biop,
prec,
right_a: Jsep.right_associative.has(biop)
};
cur_biop = biop;
// Reduce: make a binary expression from the three topmost entries.
const comparePrev = prev => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
right = stack.pop();
biop = stack.pop().value;
left = stack.pop();
node = {
type: Jsep.BINARY_EXP,
operator: biop,
left,
right
};
stack.push(node);
}
node = this.gobbleToken();
if (!node) {
this.throwError("Expected expression after " + cur_biop);
}
stack.push(biop_info, node);
}
i = stack.length - 1;
node = stack[i];
while (i > 1) {
node = {
type: Jsep.BINARY_EXP,
operator: stack[i - 1].value,
left: stack[i - 2],
right: node
};
i -= 2;
}
return node;
}
/**
* An individual part of a binary expression:
* e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
* @returns {boolean|jsep.Expression}
*/
gobbleToken() {
let ch, to_check, tc_len, node;
this.gobbleSpaces();
node = this.searchHook('gobble-token');
if (node) {
return this.runHook('after-token', node);
}
ch = this.code;
if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return this.gobbleNumericLiteral();
}
if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
// Single or double quotes
node = this.gobbleStringLiteral();
} else if (ch === Jsep.OBRACK_CODE) {
node = this.gobbleArray();
} else {
to_check = this.expr.substr(this.index, Jsep.max_unop_len);
tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept an unary op when it is an identifier.
// Unary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
this.index += tc_len;
const argument = this.gobbleToken();
if (!argument) {
this.throwError('missing unaryOp argument');
}
return this.runHook('after-token', {
type: Jsep.UNARY_EXP,
operator: to_check,
argument,
prefix: true
});
}
to_check = to_check.substr(0, --tc_len);
}
if (Jsep.isIdentifierStart(ch)) {
node = this.gobbleIdentifier();
if (Jsep.literals.hasOwnProperty(node.name)) {
node = {
type: Jsep.LITERAL,
value: Jsep.literals[node.name],
raw: node.name
};
} else if (node.name === Jsep.this_str) {
node = {
type: Jsep.THIS_EXP
};
}
} else if (ch === Jsep.OPAREN_CODE) {
// open parenthesis
node = this.gobbleGroup();
}
}
if (!node) {
return this.runHook('after-token', false);
}
node = this.gobbleTokenProperty(node);
return this.runHook('after-token', node);
}
/**
* Gobble properties of of identifiers/strings/arrays/groups.
* e.g. `foo`, `bar.baz`, `foo['bar'].baz`
* It also gobbles function calls:
* e.g. `Math.acos(obj.angle)`
* @param {jsep.Expression} node
* @returns {jsep.Expression}
*/
gobbleTokenProperty(node) {
this.gobbleSpaces();
let ch = this.code;
while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
let optional;
if (ch === Jsep.QUMARK_CODE) {
if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
break;
}
optional = true;
this.index += 2;
this.gobbleSpaces();
ch = this.code;
}
this.index++;
if (ch === Jsep.OBRACK_CODE) {
node = {
type: Jsep.MEMBER_EXP,
computed: true,
object: node,
property: this.gobbleExpression()
};
if (!node.property) {
this.throwError('Unexpected "' + this.char + '"');
}
this.gobbleSpaces();
ch = this.code;
if (ch !== Jsep.CBRACK_CODE) {
this.throwError('Unclosed [');
}
this.index++;
} else if (ch === Jsep.OPAREN_CODE) {
// A function call is being made; gobble all the arguments
node = {
type: Jsep.CALL_EXP,
'arguments': this.gobbleArguments(Jsep.CPAREN_CODE),
callee: node
};
} else if (ch === Jsep.PERIOD_CODE || optional) {
if (optional) {
this.index--;
}
this.gobbleSpaces();
node = {
type: Jsep.MEMBER_EXP,
computed: false,
object: node,
property: this.gobbleIdentifier()
};
}
if (optional) {
node.optional = true;
} // else leave undefined for compatibility with esprima
this.gobbleSpaces();
ch = this.code;
}
return node;
}
/**
* Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
* keep track of everything in the numeric literal and then calling `parseFloat` on that string
* @returns {jsep.Literal}
*/
gobbleNumericLiteral() {
let number = '',
ch,
chCode;
while (Jsep.isDecimalDigit(this.code)) {
number += this.expr.charAt(this.index++);
}
if (this.code === Jsep.PERIOD_CODE) {
// can start with a decimal marker
number += this.expr.charAt(this.index++);
while (Jsep.isDecimalDigit(this.code)) {
number += this.expr.charAt(this.index++);
}
}
ch = this.char;
if (ch === 'e' || ch === 'E') {
// exponent marker
number += this.expr.charAt(this.index++);
ch = this.char;
if (ch === '+' || ch === '-') {
// exponent sign
number += this.expr.charAt(this.index++);
}
while (Jsep.isDecimalDigit(this.code)) {
// exponent itself
number += this.expr.charAt(this.index++);
}
if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
this.throwError('Expected exponent (' + number + this.char + ')');
}
}
chCode = this.code;
// Check to make sure this isn't a variable name that start with a number (123abc)
if (Jsep.isIdentifierStart(chCode)) {
this.throwError('Variable names cannot start with a number (' + number + this.char + ')');
} else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
this.throwError('Unexpected period');
}
return {
type: Jsep.LITERAL,
value: parseFloat(number),
raw: number
};
}
/**
* Parses a string literal, staring with single or double quotes with basic support for escape codes
* e.g. `"hello world"`, `'this is\nJSEP'`
* @returns {jsep.Literal}
*/
gobbleStringLiteral() {
let str = '';
const startIndex = this.index;
const quote = this.expr.charAt(this.index++);
let closed = false;
while (this.index < this.expr.length) {
let ch = this.expr.charAt(this.index++);
if (ch === quote) {
closed = true;
break;
} else if (ch === '\\') {
// Check for all of the common escape codes
ch = this.expr.charAt(this.index++);
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
str += ch;
}
} else {
str += ch;
}
}
if (!closed) {
this.throwError('Unclosed quote after "' + str + '"');
}
return {
type: Jsep.LITERAL,
value: str,
raw: this.expr.substring(startIndex, this.index)
};
}
/**
* Gobbles only identifiers
* e.g.: `foo`, `_value`, `$x1`
* Also, this function checks if that identifier is a literal:
* (e.g. `true`, `false`, `null`) or `this`
* @returns {jsep.Identifier}
*/
gobbleIdentifier() {
let ch = this.code,
start = this.index;
if (Jsep.isIdentifierStart(ch)) {
this.index++;
} else {
this.throwError('Unexpected ' + this.char);
}
while (this.index < this.expr.length) {
ch = this.code;
if (Jsep.isIdentifierPart(ch)) {
this.index++;
} else {
break;
}
}
return {
type: Jsep.IDENTIFIER,
name: this.expr.slice(start, this.index)
};
}
/**
* Gobbles a list of arguments within the context of a function call
* or array literal. This function also assumes that the opening character
* `(` or `[` has already been gobbled, and gobbles expressions and commas
* until the terminator character `)` or `]` is encountered.
* e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
* @param {number} termination
* @returns {jsep.Expression[]}
*/
gobbleArguments(termination) {
const args = [];
let closed = false;
let separator_count = 0;
while (this.index < this.expr.length) {
this.gobbleSpaces();
let ch_i = this.code;
if (ch_i === termination) {
// done parsing
closed = true;
this.index++;
if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
this.throwError('Unexpected token ' + String.fromCharCode(termination));
}
break;
} else if (ch_i === Jsep.COMMA_CODE) {
// between expressions
this.index++;
separator_count++;
if (separator_count !== args.length) {
// missing argument
if (termination === Jsep.CPAREN_CODE) {
this.throwError('Unexpected token ,');
} else if (termination === Jsep.CBRACK_CODE) {
for (let arg = args.length; arg < separator_count; arg++) {
args.push(null);
}
}
}
} else if (args.length !== separator_count && separator_count !== 0) {
// NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments
this.throwError('Expected comma');
} else {
const node = this.gobbleExpression();
if (!node || node.type === Jsep.COMPOUND) {
this.throwError('Expected comma');
}
args.push(node);
}
}
if (!closed) {
this.throwError('Expected ' + String.fromCharCode(termination));
}
return args;
}
/**
* Responsible for parsing a group of things within parentheses `()`
* that have no identifier in front (so not a function call)
* This function assumes that it needs to gobble the opening parenthesis
* and then tries to gobble everything within that parenthesis, assuming
* that the next thing it should see is the close parenthesis. If not,
* then the expression probably doesn't have a `)`
* @returns {boolean|jsep.Expression}
*/
gobbleGroup() {
this.index++;
let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
if (this.code === Jsep.CPAREN_CODE) {
this.index++;
if (nodes.length === 1) {
return nodes[0];
} else if (!nodes.length) {
return false;
} else {
return {
type: Jsep.SEQUENCE_EXP,
expressions: nodes
};
}
} else {
this.throwError('Unclosed (');
}
}
/**
* Responsible for parsing Array literals `[1, 2, 3]`
* This function assumes that it needs to gobble the opening bracket
* and then tries to gobble the expressions as arguments.
* @returns {jsep.ArrayExpression}
*/
gobbleArray() {
this.index++;
return {
type: Jsep.ARRAY_EXP,
elements: this.gobbleArguments(Jsep.CBRACK_CODE)
};
}
}
// Static fields:
const hooks = new Hooks();
Object.assign(Jsep, {
hooks,
plugins: new Plugins(Jsep),
// Node Types
// ----------
// This is the full set of types that any JSEP node can be.
// Store them here to save space when minified
COMPOUND: 'Compound',
SEQUENCE_EXP: 'SequenceExpression',
IDENTIFIER: 'Identifier',
MEMBER_EXP: 'MemberExpression',
LITERAL: 'Literal',
THIS_EXP: 'ThisExpression',
CALL_EXP: 'CallExpression',
UNARY_EXP: 'UnaryExpression',
BINARY_EXP: 'BinaryExpression',
ARRAY_EXP: 'ArrayExpression',
TAB_CODE: 9,
LF_CODE: 10,
CR_CODE: 13,
SPACE_CODE: 32,
PERIOD_CODE: 46,
// '.'
COMMA_CODE: 44,
// ','
SQUOTE_CODE: 39,
// single quote
DQUOTE_CODE: 34,
// double quotes
OPAREN_CODE: 40,
// (
CPAREN_CODE: 41,
// )
OBRACK_CODE: 91,
// [
CBRACK_CODE: 93,
// ]
QUMARK_CODE: 63,
// ?
SEMCOL_CODE: 59,
// ;
COLON_CODE: 58,
// :
// Operations
// ----------
// Use a quickly-accessible map to store all of the unary operators
// Values are set to `1` (it really doesn't matter)
unary_ops: {
'-': 1,
'!': 1,
'~': 1,
'+': 1
},
// Also use a map for the binary operations but set their values to their
// binary precedence for quick reference (higher number = higher precedence)
// see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
binary_ops: {
'||': 1,
'&&': 2,
'|': 3,
'^': 4,
'&': 5,
'==': 6,
'!=': 6,
'===': 6,
'!==': 6,
'<': 7,
'>': 7,
'<=': 7,
'>=': 7,
'<<': 8,
'>>': 8,
'>>>': 8,
'+': 9,
'-': 9,
'*': 10,
'/': 10,
'%': 10
},
// sets specific binary_ops as right-associative
right_associative: new Set(),
// Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
additional_identifier_chars: new Set(['$', '_']),
// Literals
// ----------
// Store the values to return for the various literals we may encounter
literals: {
'true': true,
'false': false,
'null': null
},
// Except for `this`, which is special. This could be changed to something like `'self'` as well
this_str: 'this'
});
Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
// Backward Compatibility:
const jsep = expr => new Jsep(expr).parse();
const stdClassProps = Object.getOwnPropertyNames(class Test {});
Object.getOwnPropertyNames(Jsep).filter(prop => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach(m => {
jsep[m] = Jsep[m];
});
jsep.Jsep = Jsep; // allows for const { Jsep } = require('jsep');
const CONDITIONAL_EXP = 'ConditionalExpression';
var ternary = {
name: 'ternary',
init(jsep) {
// Ternary expression: test ? consequent : alternate
jsep.hooks.add('after-expression', function gobbleTernary(env) {
if (env.node && this.code === jsep.QUMARK_CODE) {
this.index++;
const test = env.node;
const consequent = this.gobbleExpression();
if (!consequent) {
this.throwError('Expected expression');
}
this.gobbleSpaces();
if (this.code === jsep.COLON_CODE) {
this.index++;
const alternate = this.gobbleExpression();
if (!alternate) {
this.throwError('Expected expression');
}
env.node = {
type: CONDITIONAL_EXP,
test,
consequent,
alternate
};
// check for operators of higher priority than ternary (i.e. assignment)
// jsep sets || at 1, and assignment at 0.9, and conditional should be between them
if (test.operator && jsep.binary_ops[test.operator] <= 0.9) {
let newTest = test;
while (newTest.right.operator && jsep.binary_ops[newTest.right.operator] <= 0.9) {
newTest = newTest.right;
}
env.node.test = newTest.right;
newTest.right = env.node;
env.node = test;
}
} else {
this.throwError('Expected :');
}
}
});
}
};
// Add default plugins:
jsep.plugins.register(ternary);
const FSLASH_CODE = 47; // '/'
const BSLASH_CODE = 92; // '\\'
var index = {
name: 'regex',
init(jsep) {
// Regex literal: /abc123/ig
jsep.hooks.add('gobble-token', function gobbleRegexLiteral(env) {
if (this.code === FSLASH_CODE) {
const patternIndex = ++this.index;
let inCharSet = false;
while (this.index < this.expr.length) {
if (this.code === FSLASH_CODE && !inCharSet) {
const pattern = this.expr.slice(patternIndex, this.index);
let flags = '';
while (++this.index < this.expr.length) {
const code = this.code;
if (code >= 97 && code <= 122 // a...z
|| code >= 65 && code <= 90 // A...Z
|| code >= 48 && code <= 57) {
// 0-9
flags += this.char;
} else {
break;
}
}
let value;
try {
value = new RegExp(pattern, flags);
} catch (e) {
this.throwError(e.message);
}
env.node = {
type: jsep.LITERAL,
value,
raw: this.expr.slice(patternIndex - 1, this.index)
};
// allow . [] and () after regex: /regex/.test(a)
env.node = this.gobbleTokenProperty(env.node);
return env.node;
}
if (this.code === jsep.OBRACK_CODE) {
inCharSet = true;
} else if (inCharSet && this.code === jsep.CBRACK_CODE) {
inCharSet = false;
}
this.index += this.code === BSLASH_CODE ? 2 : 1;
}
this.throwError('Unclosed Regex');
}
});
}
};
const PLUS_CODE = 43; // +
const MINUS_CODE = 45; // -
const plugin = {
name: 'assignment',
assignmentOperators: new Set(['=', '*=', '**=', '/=', '%=', '+=', '-=', '<<=', '>>=', '>>>=', '&=', '^=', '|=']),
updateOperators: [PLUS_CODE, MINUS_CODE],
assignmentPrecedence: 0.9,
init(jsep) {
const updateNodeTypes = [jsep.IDENTIFIER, jsep.MEMBER_EXP];
plugin.assignmentOperators.forEach(op => jsep.addBinaryOp(op, plugin.assignmentPrecedence, true));
jsep.hooks.add('gobble-token', function gobbleUpdatePrefix(env) {
const code = this.code;
if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {
this.index += 2;
env.node = {
type: 'UpdateExpression',
operator: code === PLUS_CODE ? '++' : '--',
argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
prefix: true
};
if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
this.throwError(`Unexpected ${env.node.operator}`);
}
}
});
jsep.hooks.add('after-token', function gobbleUpdatePostfix(env) {
if (env.node) {
const code = this.code;
if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {
if (!updateNodeTypes.includes(env.node.type)) {
this.throwError(`Unexpected ${env.node.operator}`);
}
this.index += 2;
env.node = {
type: 'UpdateExpression',
operator: code === PLUS_CODE ? '++' : '--',
argument: env.node,
prefix: false
};
}
}
});
jsep.hooks.add('after-expression', function gobbleAssignment(env) {
if (env.node) {
// Note: Binaries can be chained in a single expression to respect
// operator precedence (i.e. a = b = 1 + 2 + 3)
// Update all binary assignment nodes in the tree
updateBinariesToAssignments(env.node);
}
});
function updateBinariesToAssignments(node) {
if (plugin.assignmentOperators.has(node.operator)) {
node.type = 'AssignmentExpression';
updateBinariesToAssignments(node.left);
updateBinariesToAssignments(node.right);
} else if (!node.operator) {
Object.values(node).forEach(val => {
if (val && typeof val === 'object') {
updateBinariesToAssignments(val);
}
});
}
}
}
};
/* eslint-disable no-bitwise */
// register plugins
jsep.plugins.register(index, plugin);
const SafeEval = {
/**
* @param {jsep.Expression} ast
* @param {Record<string, any>} subs
*/
evalAst(ast, subs) {
switch (ast.type) {
case 'BinaryExpression':
case 'LogicalExpression':
return SafeEval.evalBinaryExpression(ast, subs);
case 'Compound':
return SafeEval.evalCompound(ast, subs);
case 'ConditionalExpression':
return SafeEval.evalConditionalExpression(ast, subs);
case 'Identifier':
return SafeEval.evalIdentifier(ast, subs);
case 'Literal':
return SafeEval.evalLiteral(ast, subs);
case 'MemberExpression':
return SafeEval.evalMemberExpression(ast, subs);
case 'UnaryExpression':
return SafeEval.evalUnaryExpression(ast, subs);
case 'ArrayExpression':
return SafeEval.evalArrayExpression(ast, subs);
case 'CallExpression':
return SafeEval.evalCallExpression(ast, subs);
case 'AssignmentExpression':
return SafeEval.evalAssignmentExpression(ast, subs);
default:
throw SyntaxError('Unexpected expression', ast);
}
},
evalBinaryExpression(ast, subs) {
const result = {
'||': (a, b) => a || b(),
'&&': (a, b) => a && b(),
'|': (a, b) => a | b(),
'^': (a, b) => a ^ b(),
'&': (a, b) => a & b(),
// eslint-disable-next-line eqeqeq
'==': (a, b) => a == b(),
// eslint-disable-next-line eqeqeq
'!=': (a, b) => a != b(),
'===': (a, b) => a === b(),
'!==': (a, b) => a !== b(),
'<': (a, b) => a < b(),
'>': (a, b) => a > b(),
'<=': (a, b) => a <= b(),
'>=': (a, b) => a >= b(),
'<<': (a, b) => a << b(),
'>>': (a, b) => a >> b(),
'>>>': (a, b) => a >>> b(),
'+': (a, b) => a + b(),
'-': (a, b) => a - b(),
'*': (a, b) => a * b(),
'/': (a, b) => a / b(),
'%': (a, b) => a % b()
}[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
return result;
},
evalCompound(ast, subs) {
let last;
for (let i = 0; i < ast.body.length; i++) {
if (ast.body[i].type === 'Identifier' && ['var', 'let', 'const'].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === 'AssignmentExpression') {
// var x=2; is detected as
// [{Identifier var}, {AssignmentExpression x=2}]
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
i += 1;
}
const expr = ast.body[i];
last = SafeEval.evalAst(expr, subs);
}
return last;
},
evalConditionalExpression(ast, subs) {
if (SafeEval.evalAst(ast.test, subs)) {
return SafeEval.evalAst(ast.consequent, subs);
}
return SafeEval.evalAst(ast.alternate, subs);
},
evalIdentifier(ast, subs) {
if (ast.name in subs) {
return subs[ast.name];
}
throw ReferenceError(`${ast.name} is not defined`);
},
evalLiteral(ast) {
return ast.value;
},
evalMemberExpression(ast, subs) {
const prop = ast.computed ? SafeEval.evalAst(ast.property) // `object[property]`
: ast.property.name; // `object.property` property is Identifier
const obj = SafeEval.evalAst(ast.object, subs);
const result = obj[prop];
if (typeof result === 'function') {
return result.bind(obj); // arrow functions aren't affected by bind.
}
return result;
},
evalUnaryExpression(ast, subs) {
const result = {
'-': a => -SafeEval.evalAst(a, subs),
'!': a => !SafeEval.evalAst(a, subs),
'~': a => ~SafeEval.evalAst(a, subs),
// eslint-disable-next-line no-implicit-coercion
'+': a => +SafeEval.evalAst(a, subs)
}[ast.operator](ast.argument);
return result;
},
evalArrayExpression(ast, subs) {
return ast.elements.map(el => SafeEval.evalAst(el, subs));
},
evalCallExpression(ast, subs) {
const args = ast.arguments.map(arg => SafeEval.evalAst(arg, subs));
const func = SafeEval.evalAst(ast.callee, subs);
return func(...args);
},
evalAssignmentExpression(ast, subs) {
if (ast.left.type !== 'Identifier') {
throw SyntaxError('Invalid left-hand side in assignment');
}
const id = ast.left.name;
const value = SafeEval.evalAst(ast.right, subs);
subs[id] = value;
return subs[id];
}
};
/**
* A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.
*/
class SafeScript {
/**
* @param {string} expr Expression to evaluate
*/
constructor(expr) {
this.code = expr;
this.ast = jsep(this.code);
}
/**
* @param {object} context Object whose items will be added
* to evaluation
* @returns {EvaluatedResult} Result of evaluated code
*/
runInNewContext(context) {
const keyMap = {
...context
};
return SafeEval.evalAst(this.ast, keyMap);
}
}
/* eslint-disable camelcase, unicorn/prefer-string-replace-all,
unicorn/prefer-at */
const {
hasOwnProperty: hasOwnProp
} = Object.prototype;
/**
* @typedef {null|boolean|number|string|PlainObject|GenericArray} JSONObject
* @typedef {null|boolean|number|string|object|GenericArray} JSONObject
*/

@@ -61,6 +1412,6 @@

/**
* @typedef {PlainObject} ReturnObject
* @typedef {object} ReturnObject
* @property {string} path
* @property {JSONObject} value
* @property {PlainObject|GenericArray} parent
* @property {object|GenericArray} parent
* @property {string} parentProperty

@@ -71,3 +1422,3 @@ */

* @callback JSONPathCallback
* @param {string|PlainObject} preferredOutput
* @param {string|object} preferredOutput
* @param {"value"|"property"} type

@@ -82,3 +1433,3 @@ * @param {ReturnObject} fullRetObj

* @param {string} path
* @param {PlainObject|GenericArray} parent
* @param {object|GenericArray} parent
* @param {string} parentPropName

@@ -104,7 +1455,7 @@ * @returns {boolean}

/**
* @typedef {typeof import('./jsonpath-browser').SafeScript} EvalClass
* @typedef {typeof SafeScript} EvalClass
*/
/**
* @typedef {PlainObject} JSONPathOptions
* @typedef {object} JSONPathOptions
* @property {JSON} json

@@ -116,6 +1467,6 @@ * @property {string|string[]} path

* @property {boolean} [wrap=true]
* @property {PlainObject} [sandbox={}]
* @property {object} [sandbox={}]
* @property {EvalCallback|EvalClass|'safe'|'native'|
* boolean} [eval = 'safe']
* @property {PlainObject|GenericArray|null} [parent=null]
* @property {object|GenericArray|null} [parent=null]
* @property {string|null} [parentProperty=null]

@@ -168,3 +1519,3 @@ * @property {JSONPathCallback} [callback]

this.flatten = opts.flatten || false;
this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true;
this.wrap = Object.hasOwn(opts, 'wrap') ? opts.wrap : true;
this.sandbox = opts.sandbox || {};

@@ -215,3 +1566,3 @@ this.eval = opts.eval === undefined ? 'safe' : opts.eval;

}
if (!hasOwnProp.call(expr, 'json')) {
if (!Object.hasOwn(expr, 'json')) {
throw new TypeError('You must supply a "json" property when providing an object ' + 'argument to JSONPath.evaluate().');

@@ -222,11 +1573,11 @@ }

} = expr);
flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten;
this.currResultType = hasOwnProp.call(expr, 'resultType') ? expr.resultType : this.currResultType;
this.currSandbox = hasOwnProp.call(expr, 'sandbox') ? expr.sandbox : this.currSandbox;
wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap;
this.currEval = hasOwnProp.call(expr, 'eval') ? expr.eval : this.currEval;
callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback;
this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback;
currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent;
currParentProperty = hasOwnProp.call(expr, 'parentProperty') ? expr.parentProperty : currParentProperty;
flatten = Object.hasOwn(expr, 'flatten') ? expr.flatten : flatten;
this.currResultType = Object.hasOwn(expr, 'resultType') ? expr.resultType : this.currResultType;
this.currSandbox = Object.hasOwn(expr, 'sandbox') ? expr.sandbox : this.currSandbox;
wrap = Object.hasOwn(expr, 'wrap') ? expr.wrap : wrap;
this.currEval = Object.hasOwn(expr, 'eval') ? expr.eval : this.currEval;
callback = Object.hasOwn(expr, 'callback') ? expr.callback : callback;
this.currOtherTypeCallback = Object.hasOwn(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback;
currParent = Object.hasOwn(expr, 'parent') ? expr.parent : currParent;
currParentProperty = Object.hasOwn(expr, 'parentProperty') ? expr.parentProperty : currParentProperty;
expr = expr.path;

@@ -305,3 +1656,3 @@ }

* @param {string} path
* @param {PlainObject|GenericArray} parent
* @param {object|GenericArray} parent
* @param {string} parentPropName

@@ -351,3 +1702,3 @@ * @param {JSONPathCallback} callback

}
if ((typeof loc !== 'string' || literalPriority) && val && hasOwnProp.call(val, loc)) {
if ((typeof loc !== 'string' || literalPriority) && val && Object.hasOwn(val, loc)) {
// simple case--directly follow property

@@ -501,3 +1852,3 @@ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr));

// `-escaped property
} else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) {
} else if (loc[0] === '`' && val && Object.hasOwn(val, loc.slice(1))) {
const locProp = loc.slice(1);

@@ -512,3 +1863,3 @@ addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));

// simple case--directly follow property
} else if (!literalPriority && val && hasOwnProp.call(val, loc)) {
} else if (!literalPriority && val && Object.hasOwn(val, loc)) {
addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true));

@@ -529,2 +1880,4 @@ }

for (let tt = 1; tt < tl; tt++) {
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
t++;

@@ -598,3 +1951,3 @@ ret.splice(t, 0, tmp[tt]);

JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
} else if (typeof this.currEval === 'function' && this.currEval.prototype && hasOwnProp.call(this.currEval.prototype, 'runInNewContext')) {
} else if (typeof this.currEval === 'function' && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, 'runInNewContext')) {
const CurrEval = this.currEval;

@@ -704,7 +2057,8 @@ JSONPath.cache[scriptCacheKey] = new CurrEval(script);

};
JSONPath.prototype.safeVm = {
Script: SafeScript
};
JSONPath.prototype.vm = vm;
JSONPath.prototype.safeVm = vm;
const SafeScript = vm.Script;
export { JSONPath, SafeScript };
export { JSONPath };
{
"author": "Stefan Goessner",
"name": "jsonpath-plus",
"version": "9.0.0",
"version": "10.0.0",
"type": "module",

@@ -60,3 +60,3 @@ "bin": {

"engines": {
"node": ">=14.0.0"
"node": ">=18.0.0"
},

@@ -69,42 +69,24 @@ "react-native": {

"@jsep-plugin/regex": "^1.0.3",
"jsep": "^1.3.8"
"jsep": "^1.3.9"
},
"devDependencies": {
"@babel/core": "^7.24.0",
"@babel/preset-env": "^7.24.0",
"@brettz9/eslint-plugin": "^1.0.4",
"@babel/core": "^7.25.7",
"@babel/preset-env": "^7.25.7",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-node-resolve": "^15.3.0",
"@rollup/plugin-terser": "^0.4.4",
"c8": "^9.1.0",
"chai": "^5.1.0",
"c8": "^10.1.2",
"chai": "^5.1.1",
"coveradge": "^0.8.2",
"eslint": "^8.57.0",
"eslint-config-ash-nazg": "^35.3.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-array-func": "^4.0.0",
"eslint-plugin-chai-expect": "^3.0.0",
"eslint-plugin-chai-friendly": "^0.7.4",
"eslint-plugin-compat": "^4.2.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-html": "^7.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jsdoc": "^48.2.0",
"eslint-plugin-markdown": "^3.0.1",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-no-unsanitized": "^4.0.2",
"eslint-plugin-no-use-extend-native": "^0.5.0",
"eslint-plugin-promise": "^6.1.1",
"eslint-plugin-sonarjs": "^0.23.0",
"eslint-plugin-standard": "^4.1.0",
"eslint-plugin-unicorn": "^50.0.1",
"eslint": "^9.12.0",
"eslint-config-ash-nazg": "^36.19.0",
"http-server": "^14.1.1",
"license-badger": "^0.21.1",
"mocha": "^10.3.0",
"mocha": "^10.7.3",
"mocha-badge-generator": "^0.11.0",
"mocha-multi-reporters": "^1.5.1",
"open-cli": "^8.0.0",
"rollup": "4.12.0",
"typedoc": "^0.25.10",
"typescript": "^5.3.3"
"rollup": "4.24.0",
"typedoc": "^0.26.8",
"typescript": "^5.6.2"
},

@@ -126,3 +108,3 @@ "keywords": [

".mocharc.cjs",
".eslintrc.cjs",
"eslint.config.js",
"src/jsonpath.d.ts",

@@ -156,3 +138,3 @@ "rollup.config.js",

"rollup": "rollup -c",
"eslint": "eslint --ext js,cjs,md,html .",
"eslint": "eslint .",
"lint": "npm run eslint",

@@ -159,0 +141,0 @@ "test": "npm run eslint && npm run rollup && npm run c8 && npm run typescript",

@@ -1,5 +0,1 @@

/* eslint-disable no-bitwise */
import jsep from 'jsep';
import jsepRegex from '@jsep-plugin/regex';
import jsepAssignment from '@jsep-plugin/assignment';
import {JSONPath} from './jsonpath.js';

@@ -34,2 +30,4 @@

if (conditionCb(item)) {
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
target.push(source.splice(i--, 1)[0]);

@@ -40,165 +38,3 @@ }

// register plugins
jsep.plugins.register(jsepRegex, jsepAssignment);
const SafeEval = {
/**
* @param {jsep.Expression} ast
* @param {Record<string, any>} subs
*/
evalAst (ast, subs) {
switch (ast.type) {
case 'BinaryExpression':
case 'LogicalExpression':
return SafeEval.evalBinaryExpression(ast, subs);
case 'Compound':
return SafeEval.evalCompound(ast, subs);
case 'ConditionalExpression':
return SafeEval.evalConditionalExpression(ast, subs);
case 'Identifier':
return SafeEval.evalIdentifier(ast, subs);
case 'Literal':
return SafeEval.evalLiteral(ast, subs);
case 'MemberExpression':
return SafeEval.evalMemberExpression(ast, subs);
case 'UnaryExpression':
return SafeEval.evalUnaryExpression(ast, subs);
case 'ArrayExpression':
return SafeEval.evalArrayExpression(ast, subs);
case 'CallExpression':
return SafeEval.evalCallExpression(ast, subs);
case 'AssignmentExpression':
return SafeEval.evalAssignmentExpression(ast, subs);
default:
throw SyntaxError('Unexpected expression', ast);
}
},
evalBinaryExpression (ast, subs) {
const result = {
'||': (a, b) => a || b(),
'&&': (a, b) => a && b(),
'|': (a, b) => a | b(),
'^': (a, b) => a ^ b(),
'&': (a, b) => a & b(),
// eslint-disable-next-line eqeqeq
'==': (a, b) => a == b(),
// eslint-disable-next-line eqeqeq
'!=': (a, b) => a != b(),
'===': (a, b) => a === b(),
'!==': (a, b) => a !== b(),
'<': (a, b) => a < b(),
'>': (a, b) => a > b(),
'<=': (a, b) => a <= b(),
'>=': (a, b) => a >= b(),
'<<': (a, b) => a << b(),
'>>': (a, b) => a >> b(),
'>>>': (a, b) => a >>> b(),
'+': (a, b) => a + b(),
'-': (a, b) => a - b(),
'*': (a, b) => a * b(),
'/': (a, b) => a / b(),
'%': (a, b) => a % b()
}[ast.operator](
SafeEval.evalAst(ast.left, subs),
() => SafeEval.evalAst(ast.right, subs)
);
return result;
},
evalCompound (ast, subs) {
let last;
for (let i = 0; i < ast.body.length; i++) {
if (
ast.body[i].type === 'Identifier' &&
['var', 'let', 'const'].includes(ast.body[i].name) &&
ast.body[i + 1] &&
ast.body[i + 1].type === 'AssignmentExpression'
) {
// var x=2; is detected as
// [{Identifier var}, {AssignmentExpression x=2}]
i += 1;
}
const expr = ast.body[i];
last = SafeEval.evalAst(expr, subs);
}
return last;
},
evalConditionalExpression (ast, subs) {
if (SafeEval.evalAst(ast.test, subs)) {
return SafeEval.evalAst(ast.consequent, subs);
}
return SafeEval.evalAst(ast.alternate, subs);
},
evalIdentifier (ast, subs) {
if (ast.name in subs) {
return subs[ast.name];
}
throw ReferenceError(`${ast.name} is not defined`);
},
evalLiteral (ast) {
return ast.value;
},
evalMemberExpression (ast, subs) {
const prop = ast.computed
? SafeEval.evalAst(ast.property) // `object[property]`
: ast.property.name; // `object.property` property is Identifier
const obj = SafeEval.evalAst(ast.object, subs);
const result = obj[prop];
if (typeof result === 'function') {
return result.bind(obj); // arrow functions aren't affected by bind.
}
return result;
},
evalUnaryExpression (ast, subs) {
const result = {
'-': (a) => -SafeEval.evalAst(a, subs),
'!': (a) => !SafeEval.evalAst(a, subs),
'~': (a) => ~SafeEval.evalAst(a, subs),
// eslint-disable-next-line no-implicit-coercion
'+': (a) => +SafeEval.evalAst(a, subs)
}[ast.operator](ast.argument);
return result;
},
evalArrayExpression (ast, subs) {
return ast.elements.map((el) => SafeEval.evalAst(el, subs));
},
evalCallExpression (ast, subs) {
const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
const func = SafeEval.evalAst(ast.callee, subs);
return func(...args);
},
evalAssignmentExpression (ast, subs) {
if (ast.left.type !== 'Identifier') {
throw SyntaxError('Invalid left-hand side in assignment');
}
const id = ast.left.name;
const value = SafeEval.evalAst(ast.right, subs);
subs[id] = value;
return subs[id];
}
};
/**
* A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.
*/
class SafeScript {
/**
* @param {string} expr Expression to evaluate
*/
constructor (expr) {
this.code = expr;
this.ast = jsep(this.code);
}
/**
* @param {PlainObject} context Object whose items will be added
* to evaluation
* @returns {EvaluatedResult} Result of evaluated code
*/
runInNewContext (context) {
const keyMap = {...context};
return SafeEval.evalAst(this.ast, keyMap);
}
}
/**
* In-browser replacement for NodeJS' VM.Script.

@@ -215,3 +51,3 @@ */

/**
* @param {PlainObject} context Object whose items will be added
* @param {object} context Object whose items will be added
* to evaluation

@@ -269,6 +105,2 @@ * @returns {EvaluatedResult} Result of evaluated code

JSONPath.prototype.safeVm = {
Script: SafeScript
};
export {JSONPath, SafeScript};
export {JSONPath};

@@ -5,9 +5,5 @@ import vm from 'vm';

JSONPath.prototype.vm = vm;
JSONPath.prototype.safeVm = vm;
const SafeScript = vm.Script;
export {
JSONPath,
SafeScript
JSONPath
};

@@ -104,2 +104,13 @@ /**

/**
* Ignore errors while evaluating JSONPath expression.
*
* `true`: Don't break entire search if an error occurs while evaluating JSONPath expression on one key/value pair.
*
* `false`: Break entire search if an error occurs while evaluating JSONPath expression on one key/value pair.
*
* @default false
*
*/
ignoreEvalErrors?: boolean
/**
* In the event that a query could be made to return the root node,

@@ -106,0 +117,0 @@ * this allows the parent of that root node to be returned within results.

/* eslint-disable camelcase, unicorn/prefer-string-replace-all,
unicorn/prefer-at */
const {hasOwnProperty: hasOwnProp} = Object.prototype;
import {SafeScript} from './Safe-Script.js';
/**
* @typedef {null|boolean|number|string|PlainObject|GenericArray} JSONObject
* @typedef {null|boolean|number|string|object|GenericArray} JSONObject
*/

@@ -60,6 +61,6 @@

/**
* @typedef {PlainObject} ReturnObject
* @typedef {object} ReturnObject
* @property {string} path
* @property {JSONObject} value
* @property {PlainObject|GenericArray} parent
* @property {object|GenericArray} parent
* @property {string} parentProperty

@@ -70,3 +71,3 @@ */

* @callback JSONPathCallback
* @param {string|PlainObject} preferredOutput
* @param {string|object} preferredOutput
* @param {"value"|"property"} type

@@ -81,3 +82,3 @@ * @param {ReturnObject} fullRetObj

* @param {string} path
* @param {PlainObject|GenericArray} parent
* @param {object|GenericArray} parent
* @param {string} parentPropName

@@ -103,7 +104,7 @@ * @returns {boolean}

/**
* @typedef {typeof import('./jsonpath-browser').SafeScript} EvalClass
* @typedef {typeof SafeScript} EvalClass
*/
/**
* @typedef {PlainObject} JSONPathOptions
* @typedef {object} JSONPathOptions
* @property {JSON} json

@@ -115,6 +116,6 @@ * @property {string|string[]} path

* @property {boolean} [wrap=true]
* @property {PlainObject} [sandbox={}]
* @property {object} [sandbox={}]
* @property {EvalCallback|EvalClass|'safe'|'native'|
* boolean} [eval = 'safe']
* @property {PlainObject|GenericArray|null} [parent=null]
* @property {object|GenericArray|null} [parent=null]
* @property {string|null} [parentProperty=null]

@@ -168,3 +169,3 @@ * @property {JSONPathCallback} [callback]

this.flatten = opts.flatten || false;
this.wrap = hasOwnProp.call(opts, 'wrap') ? opts.wrap : true;
this.wrap = Object.hasOwn(opts, 'wrap') ? opts.wrap : true;
this.sandbox = opts.sandbox || {};

@@ -227,3 +228,3 @@ this.eval = opts.eval === undefined ? 'safe' : opts.eval;

}
if (!(hasOwnProp.call(expr, 'json'))) {
if (!(Object.hasOwn(expr, 'json'))) {
throw new TypeError(

@@ -235,19 +236,19 @@ 'You must supply a "json" property when providing an object ' +

({json} = expr);
flatten = hasOwnProp.call(expr, 'flatten') ? expr.flatten : flatten;
this.currResultType = hasOwnProp.call(expr, 'resultType')
flatten = Object.hasOwn(expr, 'flatten') ? expr.flatten : flatten;
this.currResultType = Object.hasOwn(expr, 'resultType')
? expr.resultType
: this.currResultType;
this.currSandbox = hasOwnProp.call(expr, 'sandbox')
this.currSandbox = Object.hasOwn(expr, 'sandbox')
? expr.sandbox
: this.currSandbox;
wrap = hasOwnProp.call(expr, 'wrap') ? expr.wrap : wrap;
this.currEval = hasOwnProp.call(expr, 'eval')
wrap = Object.hasOwn(expr, 'wrap') ? expr.wrap : wrap;
this.currEval = Object.hasOwn(expr, 'eval')
? expr.eval
: this.currEval;
callback = hasOwnProp.call(expr, 'callback') ? expr.callback : callback;
this.currOtherTypeCallback = hasOwnProp.call(expr, 'otherTypeCallback')
callback = Object.hasOwn(expr, 'callback') ? expr.callback : callback;
this.currOtherTypeCallback = Object.hasOwn(expr, 'otherTypeCallback')
? expr.otherTypeCallback
: this.currOtherTypeCallback;
currParent = hasOwnProp.call(expr, 'parent') ? expr.parent : currParent;
currParentProperty = hasOwnProp.call(expr, 'parentProperty')
currParent = Object.hasOwn(expr, 'parent') ? expr.parent : currParent;
currParentProperty = Object.hasOwn(expr, 'parentProperty')
? expr.parentProperty

@@ -338,3 +339,3 @@ : currParentProperty;

* @param {string} path
* @param {PlainObject|GenericArray} parent
* @param {object|GenericArray} parent
* @param {string} parentPropName

@@ -388,3 +389,3 @@ * @param {JSONPathCallback} callback

if ((typeof loc !== 'string' || literalPriority) && val &&
hasOwnProp.call(val, loc)
Object.hasOwn(val, loc)
) { // simple case--directly follow property

@@ -546,3 +547,3 @@ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback,

// `-escaped property
} else if (loc[0] === '`' && val && hasOwnProp.call(val, loc.slice(1))) {
} else if (loc[0] === '`' && val && Object.hasOwn(val, loc.slice(1))) {
const locProp = loc.slice(1);

@@ -563,3 +564,3 @@ addRet(this._trace(

} else if (
!literalPriority && val && hasOwnProp.call(val, loc)
!literalPriority && val && Object.hasOwn(val, loc)
) {

@@ -587,2 +588,4 @@ addRet(

for (let tt = 1; tt < tl; tt++) {
// eslint-disable-next-line @stylistic/max-len -- Long
// eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
t++;

@@ -678,3 +681,3 @@ ret.splice(t, 0, tmp[tt]);

this.currEval.prototype &&
hasOwnProp.call(this.currEval.prototype, 'runInNewContext')
Object.hasOwn(this.currEval.prototype, 'runInNewContext')
) {

@@ -792,2 +795,6 @@ const CurrEval = this.currEval;

JSONPath.prototype.safeVm = {
Script: SafeScript
};
export {JSONPath};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc