diff --git a/README.md b/README.md index 338fb0e7..90f301fb 100644 --- a/README.md +++ b/README.md @@ -46,13 +46,8 @@ Given: Visit the [Playground](https://opensource.adobe.com/json-formula/dist/index.html) # Documentation -Specification / Reference: [HTML](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-1.1.2.html) / [PDF](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-1.1.2.pdf) +Specification / Reference: [HTML](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-2.0.0.html) / [PDF](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-2.0.0.pdf) [JavaScript API](./doc/output/JSDOCS.md) [Developer Instructions](./DEVELOPMENT.md) - -# Beta 2.0.0 Documentation -[HTML](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-2.0.0-beta.1.html) -[PDF](https://opensource.adobe.com/json-formula/doc/output/json-formula-specification-2.0.0-beta.1.pdf) - diff --git a/dist/tutorial.js.map b/dist/tutorial.js.map index 44edf8ce..48551df2 100644 --- a/dist/tutorial.js.map +++ b/dist/tutorial.js.map @@ -1 +1 @@ -{"version":3,"file":"tutorial.js","mappings":"mCACA,IAAIA,ECAqBC,IACH,oBAAXC,QAA0BA,OAAOC,aAC1CC,OAAOC,eAAeJ,EAASC,OAAOC,YAAa,CAAEG,MAAO,WAE7DF,OAAOC,eAAeJ,EAAS,aAAc,CAAEK,OAAO,GAAO,E,gBCwB9D,MAAMC,EAAY,CAChBC,YAAa,EACbC,SAAU,EACVC,YAAa,EACbC,WAAY,EACZC,YAAa,EACbC,aAAc,EACdC,YAAa,EACbC,UAAW,EACXC,kBAAmB,EACnBC,kBAAmB,EACnBC,iBAAkB,GAClBC,iBAAkB,IAGdC,EAAgB,CACpB,CAACb,EAAUC,aAAc,SACzB,CAACD,EAAUE,UAAW,MACtB,CAACF,EAAUG,aAAc,SACzB,CAACH,EAAUI,YAAa,QACxB,CAACJ,EAAUK,aAAc,SACzB,CAACL,EAAUM,cAAe,UAC1B,CAACN,EAAUO,aAAc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AU,CAAC,GACpDjiB,EAAMuiB,UAAY3B,EAAUviB,KAAK,MACjC,IAAImkB,EAAIF,EACJA,UACFE,EAAIF,EAAWxjB,QAAQH,KAAK2jB,IAG5BngB,EAAOlK,MADQ,iBAANuqB,EACM7lB,KAAKE,UAAU2lB,EAAG,KAAM,GAExBA,CAEnB,CAAE,MAAOlnB,GACP6G,EAAOlK,MAAQqD,EAAEgC,WACjB0C,EAAMuiB,UAAY3B,EAAUviB,KAAK,KACnC,CACF,CAEAoiB,EAAYD,iBAAiB,OAAQlB,GACrC9V,EAAWgX,iBAAiB,OAAQlB,GACpCoB,SAASC,eAAe,cAAcH,iBACpC,SACA,KACEC,EAAYxoB,MAAQ4oB,EAChBC,EAAOG,IAAI,YACbzX,EAAWvR,MAAQ,0CACnByoB,SAASC,eAAe,mBAAmBU,MAAMC,QAAU,OAC3DnlB,MAAMsU,KAAKiQ,SAASc,uBAAuB,aAAate,SAAQyN,GAAKA,EAAE8Q,UAAUgB,OAAO,YACxFlC,OAAOmC,QAAQC,UAAU,CAAC,EAAGjC,SAASkC,MAAO,KAC7CtD,IACF,IAGJoB,SAASC,eAAe,UAAUH,iBAAiB,UAAUllB,IAC3DkO,EAAWvR,MAAQqD,EAAEunB,OAAO5qB,MAC5BqnB,GAAK,IAEPA,IAEAwD,MAAM,2BAA2BC,MAAKP,IACpCA,EAAElR,OAAOyR,MAAKC,IAEZ,MAAMC,EAAkBD,EACrBta,QAAQ,mBAAoB,WAC5BA,QAAQ,OAAQ,IACnBgY,SAASC,eAAe,eAAe4B,UAAYU,CAAe,GAClE,GACF,G","sources":["webpack://jsonFormula/webpack/bootstrap","webpack://jsonFormula/webpack/runtime/make namespace object","webpack://jsonFormula/./src/dataTypes.js","webpack://jsonFormula/./src/tokenDefinitions.js","webpack://jsonFormula/./src/errors.js","webpack://jsonFormula/./src/matchType.js","webpack://jsonFormula/./src/utils.js","webpack://jsonFormula/./src/TreeInterpreter.js","webpack://jsonFormula/./src/Lexer.js","webpack://jsonFormula/./src/Parser.js","webpack://jsonFormula/./src/functions.js","webpack://jsonFormula/./src/interpreter.js","webpack://jsonFormula/./src/json-formula.js","webpack://jsonFormula/./tutorial/Form.js","webpack://jsonFormula/./src/stringToNumber.js","webpack://jsonFormula/./tutorial/tutorial.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n// Type constants used to define functions.\nconst dataTypes = {\n TYPE_NUMBER: 0,\n TYPE_ANY: 1,\n TYPE_STRING: 2,\n TYPE_ARRAY: 3,\n TYPE_OBJECT: 4,\n TYPE_BOOLEAN: 5,\n TYPE_EXPREF: 6,\n TYPE_NULL: 7,\n TYPE_ARRAY_NUMBER: 8,\n TYPE_ARRAY_STRING: 9,\n TYPE_ARRAY_ARRAY: 10,\n TYPE_EMPTY_ARRAY: 11,\n};\n\nconst typeNameTable = {\n [dataTypes.TYPE_NUMBER]: 'number',\n [dataTypes.TYPE_ANY]: 'any',\n [dataTypes.TYPE_STRING]: 'string',\n [dataTypes.TYPE_ARRAY]: 'array',\n [dataTypes.TYPE_OBJECT]: 'object',\n [dataTypes.TYPE_BOOLEAN]: 'boolean',\n [dataTypes.TYPE_EXPREF]: 'expression',\n [dataTypes.TYPE_NULL]: 'null',\n [dataTypes.TYPE_ARRAY_NUMBER]: 'Array',\n [dataTypes.TYPE_ARRAY_STRING]: 'Array',\n [dataTypes.TYPE_ARRAY_ARRAY]: 'Array',\n [dataTypes.TYPE_EMPTY_ARRAY]: 'array',\n};\n\nexport { dataTypes, typeNameTable };\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nexport default {\n TOK_EOF: 'EOF',\n TOK_IDENTIFIER: 'Identifier',\n TOK_QUOTEDIDENTIFIER: 'QuotedIdentifier',\n TOK_RBRACKET: 'Rbracket',\n TOK_RPAREN: 'Rparen',\n TOK_COMMA: 'Comma',\n TOK_COLON: 'Colon',\n TOK_CONCATENATE: 'Concatenate',\n TOK_RBRACE: 'Rbrace',\n TOK_NUMBER: 'Number',\n TOK_CURRENT: 'Current',\n TOK_GLOBAL: 'Global',\n TOK_EXPREF: 'Expref',\n TOK_PIPE: 'Pipe',\n TOK_OR: 'Or',\n TOK_AND: 'And',\n TOK_ADD: 'Add',\n TOK_SUBTRACT: 'Subtract',\n TOK_UNARY_MINUS: 'UnaryMinus',\n TOK_MULTIPLY: 'Multiply',\n TOK_UNION: 'Union',\n TOK_DIVIDE: 'Divide',\n TOK_COMPARATOR: 'Comparator',\n TOK_FLATTEN: 'Flatten',\n TOK_STAR: 'Star',\n TOK_FILTER: 'Filter',\n TOK_DOT: 'Dot',\n TOK_NOT: 'Not',\n TOK_LBRACE: 'Lbrace',\n TOK_LBRACKET: 'Lbracket',\n TOK_LPAREN: 'Lparen',\n TOK_JSON: 'Literal',\n TOK_STRING: 'String',\n TOK_INT: 'Integer',\n};\n","/*\nCopyright 2023 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nexport function typeError(desc) {\n return new TypeError(desc);\n}\n\nexport function syntaxError(desc) {\n const e = new Error(desc);\n e.name = 'SyntaxError';\n return e;\n}\n\nexport function functionError(desc) {\n const e = new Error(desc);\n e.name = 'FunctionError';\n return e;\n}\n\nexport function evaluationError(desc) {\n const e = new Error(desc);\n e.name = 'EvaluationError';\n return e;\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { dataTypes, typeNameTable } from './dataTypes.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { typeError } from './errors.js';\n// import { isClass } from './utils.js';\n\nconst {\n TYPE_NUMBER,\n TYPE_ANY,\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_OBJECT,\n TYPE_BOOLEAN,\n TYPE_EXPREF,\n TYPE_NULL,\n TYPE_ARRAY_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY_ARRAY,\n TYPE_EMPTY_ARRAY,\n} = dataTypes;\n\nconst {\n TOK_EXPREF,\n} = tokenDefinitions;\n\nfunction isArray(t) {\n return [\n TYPE_ARRAY, TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING, TYPE_ARRAY_ARRAY, TYPE_EMPTY_ARRAY,\n ].includes(t);\n}\n\nexport function getType(inputObj) {\n function simpleType(obj) {\n if (obj === null) return TYPE_NULL;\n const t = typeof obj;\n if (t === 'string') return TYPE_STRING;\n if (t === 'number') return TYPE_NUMBER;\n if (t === 'boolean') return TYPE_BOOLEAN;\n if (Array.isArray(obj)) {\n if (obj.length === 0) return TYPE_EMPTY_ARRAY;\n if (obj.flat(Infinity).every(a => getType(a) === TYPE_NUMBER)) return TYPE_ARRAY_NUMBER;\n if (obj.flat(Infinity).every(a => getType(a) === TYPE_STRING)) return TYPE_ARRAY_STRING;\n if (obj.every(a => isArray(getType(a)))) return TYPE_ARRAY_ARRAY;\n return TYPE_ARRAY;\n }\n // Check if it's an expref. If it has, it's been\n // tagged with a jmespathType attr of 'Expref';\n if (obj.jmespathType === TOK_EXPREF) return TYPE_EXPREF;\n return TYPE_OBJECT;\n }\n let type = simpleType(inputObj);\n if (type !== TYPE_OBJECT) return type;\n // if inputObj is a class, then convert it to its base type via JSON\n const obj = JSON.parse(JSON.stringify(inputObj));\n type = simpleType(obj);\n return type;\n}\n\nexport function isArrayType(t) {\n return [\n TYPE_ARRAY, TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING, TYPE_ARRAY_ARRAY, TYPE_EMPTY_ARRAY,\n ].includes(getType(t));\n}\n\nexport function getTypeName(arg) {\n return typeNameTable[getType(arg)];\n}\n\nfunction supportedConversion(from, to) {\n const pairs = {\n [TYPE_NUMBER]: [\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_ARRAY_NUMBER,\n TYPE_BOOLEAN,\n ],\n [TYPE_BOOLEAN]: [\n TYPE_STRING,\n TYPE_NUMBER,\n TYPE_ARRAY,\n ],\n [TYPE_ARRAY]: [TYPE_BOOLEAN, TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER],\n [TYPE_ARRAY_NUMBER]: [TYPE_BOOLEAN, TYPE_ARRAY_STRING, TYPE_ARRAY],\n [TYPE_ARRAY_STRING]: [TYPE_BOOLEAN, TYPE_ARRAY_NUMBER, TYPE_ARRAY],\n [TYPE_ARRAY_ARRAY]: [TYPE_BOOLEAN],\n [TYPE_EMPTY_ARRAY]: [TYPE_BOOLEAN],\n\n [TYPE_OBJECT]: [TYPE_BOOLEAN],\n [TYPE_NULL]: [\n TYPE_STRING,\n TYPE_NUMBER,\n TYPE_BOOLEAN,\n ],\n [TYPE_STRING]: [\n TYPE_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY,\n TYPE_BOOLEAN],\n };\n return pairs[from].includes(to);\n}\n\nexport function matchType(expectedList, argValue, context, toNumber, toString) {\n const actual = getType(argValue);\n if (argValue?.jmespathType === TOK_EXPREF && !expectedList.includes(TYPE_EXPREF)) {\n throw typeError(`${context} does not accept an expression reference argument.`);\n }\n const isObject = t => t === TYPE_OBJECT;\n const match = (expect, found) => expect === found\n || expect === TYPE_ANY\n || (expect === TYPE_ARRAY && isArray(found))\n || (isArray(expect) && found === TYPE_EMPTY_ARRAY);\n\n if (expectedList.some(type => match(type, actual))) return argValue;\n\n // if the function allows multiple types, we can't coerce the type and we need an exact match\n // Of the set of expected types, filter out the ones that can be coerced from the actual type\n const filteredList = expectedList.filter(t => supportedConversion(actual, t));\n if (filteredList.length === 0) {\n throw typeError(`${context} expected argument to be type ${typeNameTable[expectedList[0]]} but received type ${typeNameTable[actual]} instead.`);\n }\n const exactMatch = filteredList.length > 1;\n const expected = filteredList[0];\n let wrongType = false;\n\n // Can't coerce objects and arrays to any other type\n if (isArray(actual)) {\n if ([TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING].includes(expected)) {\n if (argValue.flat(Infinity).some(a => {\n const t = getType(a);\n // can't coerce arrays or objects to numbers or strings\n return isArray(t) || isObject(t);\n })) wrongType = true;\n }\n }\n // nothing coerces to an object\n if (exactMatch && expected === TYPE_OBJECT) wrongType = true;\n\n if (exactMatch) {\n throw typeError(`${context} cannot process type: ${typeNameTable[actual]}. Must be one of: ${expectedList.map(t => typeNameTable[t]).join(', ')}.`);\n }\n if (wrongType) {\n throw typeError(`${context} expected argument to be type ${typeNameTable[expected]} but received type ${typeNameTable[actual]} instead.`);\n }\n // Can't coerce Objects and arrays to anything other than boolean\n if (isObject(actual) && expected === TYPE_BOOLEAN) {\n return Object.keys(argValue).length === 0;\n }\n\n // no exact match, see if we can coerce an array type\n if (isArray(actual)) {\n const toArray = a => (Array.isArray(a) ? a : [a]);\n const coerceString = a => (Array.isArray(a) ? a.map(coerceString) : toString(a));\n const coerceNumber = a => (Array.isArray(a) ? a.map(coerceNumber) : toNumber(a));\n\n if (expected === TYPE_BOOLEAN) return argValue.length > 0;\n if (expected === TYPE_ARRAY_STRING) return argValue.map(coerceString);\n if (expected === TYPE_ARRAY_NUMBER) return argValue.map(coerceNumber);\n if (expected === TYPE_ARRAY_ARRAY) return argValue.map(toArray);\n }\n\n if (!isArray(actual) && !isObject(actual)) {\n if (expected === TYPE_ARRAY_STRING) return [toString(argValue)];\n if (expected === TYPE_ARRAY_NUMBER) return [toNumber(argValue)];\n if (expected === TYPE_ARRAY) return [argValue];\n if (expected === TYPE_NUMBER) return toNumber(argValue);\n if (expected === TYPE_STRING) return toString(argValue);\n if (expected === TYPE_BOOLEAN) return !!argValue;\n }\n\n throw typeError(`${context} expected argument to be type ${typeNameTable[expected]} but received type ${typeNameTable[actual]} instead.`);\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nexport function isArray(obj) {\n return Array.isArray(obj);\n}\n\nexport function isObject(obj) {\n if (obj !== null) {\n return Object.prototype.toString.call(obj) === '[object Object]';\n }\n return false;\n}\n\nexport function getValueOf(a) {\n if (a === null || a === undefined) return a;\n if (isArray(a)) {\n return a.map(i => getValueOf(i));\n }\n // if we have a child named 'valueOf' then we're an object,\n // and just return the object.\n if (typeof (a.valueOf) !== 'function') return a;\n return a.valueOf();\n}\n\nexport function toBoolean(param) {\n if (param === null) return false;\n // in case it's an object with a valueOf defined\n const val = getValueOf(param);\n\n // empty arrays are false\n if (Array.isArray(val)) return val.length > 0;\n // empty objects are false\n if (isObject(val)) return Object.keys(val).length > 0;\n return !!val;\n}\n\nexport function strictDeepEqual(lhs, rhs) {\n const first = getValueOf(lhs);\n const second = getValueOf(rhs);\n // Check the scalar case first.\n if (first === second) {\n return true;\n }\n\n // Check if they are the same type.\n const firstType = Object.prototype.toString.call(first);\n if (firstType !== Object.prototype.toString.call(second)) {\n return false;\n }\n // We know that first and second have the same type so we can just check the\n // first type from now on.\n if (isArray(first) === true) {\n // Short circuit if they're not the same length;\n if (first.length !== second.length) return false;\n return first.every((f, i) => strictDeepEqual(f, second[i]));\n }\n if (isObject(first) === true) {\n if (Object.keys(first).length !== Object.keys(second).length) return false;\n // An object is equal if it has the same key/value pairs.\n // eslint-disable-next-line no-restricted-syntax\n for (const key in first) {\n if (hasOwnProperty.call(first, key)) {\n if (strictDeepEqual(first[key], second[key]) === false) return false;\n }\n }\n return true;\n }\n return false;\n}\n\nexport function getProperty(obj, key) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n // if it's a regular enumerable property or if it's configured with a getter,\n // then return it.\n // if it's a built-in property such as length or toString etc. we'll want to ignore it.\n if (desc?.enumerable || !!desc?.get) {\n // for applications that want to track which properties are accessed, allow for a special\n // hook to callback and register this key/value accessor.\n obj[key]?.[Symbol.for('track')]?.(obj, key);\n return obj[key];\n }\n return undefined;\n}\n\nexport function debugAvailable(debug, obj, key, chainStart = null) {\n try {\n let available = [];\n if (isArray(obj) && obj.length > 0) {\n debug.push(`Failed to find: '${key}' on an array object.`);\n debug.push(`Did you mean to use a projection? e.g. ${chainStart || 'array'}[*].${key}`);\n return;\n }\n debug.push(`Failed to find: '${key}'`);\n if (obj !== null) {\n available = [...available, ...Object.entries(Object.getOwnPropertyDescriptors(obj, key))\n .filter(([k, desc]) => (desc?.enumerable || !!desc?.get) && !/^[0-9]+$/.test(k) && (!k.startsWith('$') || key.startsWith('$')))\n .map(([k]) => `'${k}'`)];\n }\n if (available.length) debug.push(`Available fields: ${available}`);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n}\n\nexport function isClass(obj) {\n if (obj === null) return false;\n if (Array.isArray(obj)) return false;\n return !['Object', 'Boolean', 'Number', 'String'].includes(obj.constructor.name);\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport {\n matchType, getTypeName, getType, isArrayType,\n} from './matchType.js';\nimport { dataTypes } from './dataTypes.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport {\n isArray, isObject, strictDeepEqual, getValueOf, getProperty, debugAvailable, toBoolean,\n} from './utils.js';\nimport { evaluationError, typeError } from './errors.js';\n\nconst {\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_FLATTEN,\n} = tokenDefinitions;\n\nconst {\n TYPE_STRING,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY,\n TYPE_NUMBER,\n} = dataTypes;\n\nfunction objValues(obj) {\n return Object.values(obj);\n}\n\nfunction balanceArrayOperands(opLeft, opRight) {\n if (isArray(opLeft) && isArray(opRight)) {\n // balance the size of the arrays by padding with nulls\n const shorter = opLeft.length < opRight.length ? opLeft : opRight;\n const diff = Math.abs(opLeft.length - opRight.length);\n shorter.length += diff;\n shorter.fill(null, shorter.length - diff);\n }\n}\n\nexport default class TreeInterpreter {\n constructor(runtime, globals, toNumber, toString, debug, language) {\n this.runtime = runtime;\n this.globals = globals;\n this.toNumber = toNumber;\n this.toString = toString;\n this.debug = debug;\n this.language = language;\n this.visitFunctions = this.initVisitFunctions();\n // track the identifier name that started the chain\n // so that we can use it in debug hints\n this.debugChainStart = null;\n }\n\n search(node, value) {\n return this.visit(node, value);\n }\n\n field(node, value) {\n // we used to check isObject(value) here -- but it is possible for an array-based\n // object to have properties. So we'll allow the child check on objects and arrays.\n if (value !== null && (isObject(value) || isArray(value))) {\n const field = getProperty(value, node.name);\n if (field === undefined) {\n debugAvailable(this.debug, value, node.name, this.debugChainStart);\n return null;\n }\n return field;\n }\n debugAvailable(this.debug, value, node.name, this.debugChainStart);\n return null;\n }\n\n initVisitFunctions() {\n return {\n Identifier: this.field.bind(this),\n QuotedIdentifier: this.field.bind(this),\n ChainedExpression: (node, value) => {\n let result = this.visit(node.children[0], value);\n this.debugChainStart = node.children[0].name;\n for (let i = 1; i < node.children.length; i += 1) {\n result = this.visit(node.children[1], result);\n if (result === null) return null;\n }\n return result;\n },\n\n BracketExpression: (node, value) => {\n const left = this.visit(node.children[0], value);\n return this.visit(node.children[1], left);\n },\n\n Index: (node, value) => {\n if (isArray(value)) {\n let index = node.value.value;\n if (index < 0) {\n index = value.length + index;\n }\n const result = value[index];\n if (result === undefined) {\n this.debug.push(`Index: ${index} out of range for array size: ${value.length}`);\n return null;\n }\n return result;\n }\n this.debug.push('Left side of index expression must be an array');\n this.debug.push(`Did you intend a single-element array? if so, use a JSON literal: \\`[${node.value.value}]\\``);\n return null;\n },\n\n Slice: (node, value) => {\n if (!isArray(value)) {\n this.debug.push('Slices apply to arrays only');\n return null;\n }\n const sliceParams = node.children.map(param => (param === null ? null : param.value));\n const [start, stop, step] = this.computeSliceParams(value.length, sliceParams);\n const result = [];\n if (step > 0) {\n for (let i = start; i < stop; i += step) {\n result.push(value[i]);\n }\n } else {\n for (let i = start; i > stop; i += step) {\n result.push(value[i]);\n }\n }\n return result;\n },\n\n Projection: (node, value) => {\n // Evaluate left child.\n const base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n if (node.debug === 'Wildcard') {\n this.debug.push('Bracketed wildcards apply to arrays only');\n }\n return null;\n }\n const collected = [];\n base.forEach(b => {\n const current = this.visit(node.children[1], b);\n collected.push(current);\n });\n return collected;\n },\n\n // wildcard: \".*\"\n ValueProjection: (node, value) => {\n // Evaluate left child.\n const projection = this.visit(node.children[0], value);\n if (!isObject(getValueOf(projection))) {\n this.debug.push('Chained wildcards apply to objects only');\n return null;\n }\n const collected = [];\n const values = objValues(projection);\n values.forEach(val => {\n const current = this.visit(node.children[1], val);\n collected.push(current);\n });\n return collected;\n },\n\n FilterProjection: (node, value) => {\n const base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n this.debug.push('Filter expressions apply to arrays only');\n return null;\n }\n const filtered = base.filter(b => {\n const matched = this.visit(node.children[2], b);\n return toBoolean(matched);\n });\n\n const finalResults = [];\n filtered.forEach(f => {\n const current = this.visit(node.children[1], f);\n finalResults.push(current);\n });\n return finalResults;\n },\n\n Comparator: (node, value) => {\n let first = getValueOf(this.visit(node.children[0], value));\n let second = getValueOf(this.visit(node.children[1], value));\n\n if (node.value === '==') return strictDeepEqual(first, second);\n if (node.value === '!=') return !strictDeepEqual(first, second);\n if (isObject(first) || isArray(first)) {\n this.debug.push(`Cannot use comparators with ${getTypeName(first)}`);\n return false;\n }\n if (isObject(second) || isArray(second)) {\n this.debug.push(`Cannot use comparators with ${getTypeName(second)}`);\n return false;\n }\n const type1 = getType(first);\n const type2 = getType(second);\n // if either parameter is a number, we need to do a numeric comparison\n // javascript will compare this way automatically, but if we explicitly convert\n // to numbers, we will get debug warnings for non-numeric strings\n if (type1 === TYPE_NUMBER || type2 === TYPE_NUMBER) {\n // if toNumber fails, it will populate the debug array\n // with an appropriate warning\n try {\n first = this.toNumber(first);\n second = this.toNumber(second);\n if (first === null || second === null) return false;\n } catch (_e) {\n // failing to convert to a number for comparison is not an error\n // we just return false\n return false;\n }\n }\n if (node.value === '>') return first > second;\n if (node.value === '>=') return first >= second;\n if (node.value === '<') return first < second;\n // if (node.value === '<=)\n // must be LTE\n return first <= second;\n },\n\n [TOK_FLATTEN]: (node, value) => {\n const original = this.visit(node.children[0], value);\n if (!isArray(original)) {\n this.debug.push('Flatten expressions apply to arrays only. If you want an empty array, use a JSON literal: `[]`');\n return null;\n }\n const merged = [];\n original.forEach(current => {\n if (isArray(current)) {\n merged.push(...current);\n } else {\n merged.push(current);\n }\n });\n return merged;\n },\n\n Identity: (_node, value) => value,\n\n ArrayExpression: (node, value) => node.children.map(child => this.visit(child, value)),\n\n ObjectExpression: (node, value) => {\n // at one time we used to have this:\n // if (value === null) return null;\n // BUT then an expression such as:\n // values({a: 'aa'})\n // would return null if the document were `null`\n // Removing the check means that:\n // `null`.{a: 'aa'}\n // returns: {a: 'aa'}\n // which is a bit odd, but seems correct.\n const collected = {};\n node.children.forEach(child => {\n if (collected[child.name] !== undefined) this.debug.push(`Duplicate key: '${child.name}'`);\n collected[child.name] = this.visit(child.value, value);\n });\n return collected;\n },\n\n OrExpression: (node, value) => {\n let matched = this.visit(node.children[0], value);\n if (!toBoolean(matched)) matched = this.visit(node.children[1], value);\n return matched;\n },\n\n AndExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n\n if (!toBoolean(first)) return first;\n return this.visit(node.children[1], value);\n },\n\n AddExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '+');\n },\n\n ConcatenateExpression: (node, value) => {\n let first = this.visit(node.children[0], value);\n let second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n if (isArrayType(first)) {\n first = matchType([TYPE_ARRAY_STRING], first, 'concatenate', this.toNumber, this.toString);\n } else {\n first = matchType([TYPE_STRING], first, 'concatenate', this.toNumber, this.toString);\n }\n if (isArrayType(second)) {\n second = matchType([TYPE_ARRAY_STRING], second, 'concatenate', this.toNumber, this.toString);\n } else {\n second = matchType([TYPE_STRING], second, 'concatenate', this.toNumber, this.toString);\n }\n return this.applyOperator(first, second, '&');\n },\n\n UnionExpression: (node, value) => {\n let first = this.visit(node.children[0], value);\n if (first === null) first = [null];\n let second = this.visit(node.children[1], value);\n if (second === null) second = [null];\n first = matchType([TYPE_ARRAY], first, 'union', this.toNumber, this.toString);\n second = matchType([TYPE_ARRAY], second, 'union', this.toNumber, this.toString);\n return first.concat(second);\n },\n\n SubtractExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '-');\n },\n\n MultiplyExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '*');\n },\n\n DivideExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '/');\n },\n\n NotExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n return !toBoolean(first);\n },\n\n UnaryMinusExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const minus = first * -1;\n if (Number.isNaN(minus)) throw typeError(`Failed to convert \"${first}\" to number`);\n return minus;\n },\n\n String: node => node.value,\n\n Literal: node => node.value,\n\n Number: node => node.value,\n\n Integer: node => node.value,\n\n [TOK_PIPE]: (node, value) => {\n const left = this.visit(node.children[0], value);\n return this.visit(node.children[1], left);\n },\n\n [TOK_CURRENT]: (_node, value) => value,\n\n [TOK_GLOBAL]: node => {\n const result = this.globals[node.name];\n return result === undefined ? null : result;\n },\n\n Function: (node, value) => {\n // Special case for if()\n // we need to make sure the results are called only after the condition is evaluated\n // Otherwise we end up with both results invoked -- which could include side effects\n // For \"if\", the last parameter to callFunction is false (bResolved) to indicate there's\n // no point in validating the argument type.\n if (node.name === 'if') return this.runtime.callFunction(node.name, node.children, value, this, false);\n const resolvedArgs = node.children.map(child => this.visit(child, value));\n return this.runtime.callFunction(node.name, resolvedArgs, value, this);\n },\n\n ExpressionReference: node => {\n const [refNode] = node.children;\n // Tag the node with a specific attribute so the type\n // checker verify the type.\n refNode.jmespathType = TOK_EXPREF;\n return refNode;\n },\n };\n }\n\n visit(n, v = null) {\n const fn = n && this.visitFunctions[n.type];\n return fn(n, v);\n }\n\n // eslint-disable-next-line class-methods-use-this\n computeSliceParams(arrayLength, sliceParams) {\n function capSliceRange(arrayLen, actual, stp) {\n let actualValue = actual;\n if (actualValue < 0) {\n actualValue += arrayLen;\n if (actualValue < 0) {\n actualValue = stp < 0 ? -1 : 0;\n }\n } else if (actualValue >= arrayLen) {\n actualValue = stp < 0 ? arrayLen - 1 : arrayLen;\n }\n return actualValue;\n }\n\n let [start, stop, step] = sliceParams;\n if (step === null) {\n step = 1;\n } else if (step === 0) {\n throw evaluationError('Invalid slice, step cannot be 0');\n }\n const stepValueNegative = step < 0;\n\n if (start === null) {\n start = stepValueNegative ? arrayLength - 1 : 0;\n } else {\n start = capSliceRange(arrayLength, start, step);\n }\n\n if (stop === null) {\n stop = stepValueNegative ? -1 : arrayLength;\n } else {\n stop = capSliceRange(arrayLength, stop, step);\n }\n return [start, stop, step];\n }\n\n applyOperator(first, second, operator) {\n if (isArray(first) && isArray(second)) {\n const result = [];\n for (let i = 0; i < first.length; i += 1) {\n result.push(this.applyOperator(first[i], second[i], operator));\n }\n return result;\n }\n\n if (isArray(first)) return first.map(a => this.applyOperator(a, second, operator));\n if (isArray(second)) return second.map(a => this.applyOperator(first, a, operator));\n\n if (operator === '&') return first + second;\n if (operator === '*') return this.toNumber(first) * this.toNumber(second);\n const n1 = this.toNumber(first);\n const n2 = this.toNumber(second);\n if (operator === '+') return n1 + n2;\n if (operator === '-') return n1 - n2;\n // if (operator === '/') {\n // Must be division\n const result = n1 / n2;\n if (!Number.isFinite(result)) {\n throw evaluationError(`Division by zero ${first}/${second}`);\n }\n return result;\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-underscore-dangle */\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { syntaxError } from './errors.js';\n\nconst {\n TOK_IDENTIFIER,\n TOK_QUOTEDIDENTIFIER,\n TOK_RBRACKET,\n TOK_RPAREN,\n TOK_COMMA,\n TOK_COLON,\n TOK_CONCATENATE,\n TOK_RBRACE,\n TOK_NUMBER,\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_OR,\n TOK_COMPARATOR,\n TOK_AND,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_UNARY_MINUS,\n TOK_DIVIDE,\n TOK_UNION,\n TOK_FLATTEN,\n TOK_STAR,\n TOK_FILTER,\n TOK_DOT,\n TOK_NOT,\n TOK_LBRACE,\n TOK_LBRACKET,\n TOK_LPAREN,\n TOK_JSON,\n TOK_STRING,\n TOK_INT,\n} = tokenDefinitions;\n\n// The \"&\", \"[\", \"<\", \">\" tokens\n// are not in basicToken because\n// there are two token variants\n// (\"&&\", \"[?\", \"<=\", \">=\"). This is specially handled\n// below.\n\nconst basicTokens = {\n '.': TOK_DOT,\n ',': TOK_COMMA,\n ':': TOK_COLON,\n '{': TOK_LBRACE,\n '}': TOK_RBRACE,\n ']': TOK_RBRACKET,\n '(': TOK_LPAREN,\n ')': TOK_RPAREN,\n '@': TOK_CURRENT,\n};\n\nconst globalStartToken = '$';\nconst operatorStartToken = {\n '<': true,\n '>': true,\n '=': true,\n '!': true,\n};\n\nconst skipChars = {\n ' ': true,\n '\\t': true,\n '\\n': true,\n};\n\nfunction isAlphaNum(ch) {\n return (ch >= 'a' && ch <= 'z')\n || (ch >= 'A' && ch <= 'Z')\n || (ch >= '0' && ch <= '9')\n || ch === '_';\n}\n\nfunction isIdentifier(stream, pos) {\n const ch = stream[pos];\n // $ is special -- it's allowed to be part of an identifier if it's the first character\n // return whether character 'isAlpha'\n return ch === '$'\n || (ch >= 'a' && ch <= 'z')\n || (ch >= 'A' && ch <= 'Z')\n || ch === '_';\n}\n\nexport default class Lexer {\n constructor(allowedGlobalNames = [], debug = []) {\n this._allowedGlobalNames = allowedGlobalNames;\n this.debug = debug;\n }\n\n tokenize(stream) {\n const tokens = [];\n this._current = 0;\n let start;\n let identifier;\n let token;\n while (this._current < stream.length) {\n const prev = tokens.length ? tokens.slice(-1)[0].type : null;\n\n if (this._isGlobal(prev, stream, this._current)) {\n tokens.push(this._consumeGlobal(stream));\n } else if (isIdentifier(stream, this._current)) {\n start = this._current;\n identifier = this._consumeUnquotedIdentifier(stream);\n tokens.push({\n type: TOK_IDENTIFIER,\n value: identifier,\n start,\n });\n } else if (this._isNumber(stream)) {\n token = this._consumeNumber(stream);\n tokens.push(token);\n } else if (basicTokens[stream[this._current]] !== undefined) {\n tokens.push({\n type: basicTokens[stream[this._current]],\n value: stream[this._current],\n start: this._current,\n });\n this._current += 1;\n } else if (stream[this._current] === '-' && ![TOK_GLOBAL, TOK_CURRENT, TOK_NUMBER, TOK_INT, TOK_RPAREN, TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_RBRACKET, TOK_JSON, TOK_STRING].includes(prev)) {\n token = this._consumeUnaryMinus(stream);\n tokens.push(token);\n } else if (stream[this._current] === '[') {\n // No need to increment this._current. This happens\n // in _consumeLBracket\n token = this._consumeLBracket(stream);\n tokens.push(token);\n } else if (stream[this._current] === \"'\") {\n start = this._current;\n identifier = this._consumeQuotedIdentifier(stream);\n tokens.push({\n type: TOK_QUOTEDIDENTIFIER,\n value: identifier,\n start,\n });\n } else if (stream[this._current] === '\"') {\n start = this._current;\n identifier = this._consumeRawStringLiteral(stream);\n tokens.push({\n type: TOK_STRING,\n value: identifier,\n start,\n });\n } else if (stream[this._current] === '`') {\n start = this._current;\n const json = this._consumeJson(stream);\n tokens.push({\n type: TOK_JSON,\n value: json,\n start,\n });\n } else if (operatorStartToken[stream[this._current]] !== undefined) {\n tokens.push(this._consumeOperator(stream));\n } else if (skipChars[stream[this._current]] !== undefined) {\n // Ignore whitespace.\n this._current += 1;\n } else if (stream[this._current] === '&') {\n start = this._current;\n this._current += 1;\n if (stream[this._current] === '&') {\n this._current += 1;\n tokens.push({ type: TOK_AND, value: '&&', start });\n } else if (prev === TOK_COMMA || prev === TOK_LPAREN) {\n // based on previous token we'll know if this & is a JMESPath expression-type\n // or if it's a concatenation operator\n // if we're a function arg then it's an expression-type\n tokens.push({ type: TOK_EXPREF, value: '&', start });\n } else {\n tokens.push({ type: TOK_CONCATENATE, value: '&', start });\n }\n } else if (stream[this._current] === '~') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_UNION, value: '~', start });\n } else if (stream[this._current] === '+') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_ADD, value: '+', start });\n } else if (stream[this._current] === '-') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_SUBTRACT, value: '-', start });\n } else if (stream[this._current] === '*') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_STAR, value: '*', start });\n } else if (stream[this._current] === '/') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_DIVIDE, value: '/', start });\n } else if (stream[this._current] === '|') {\n start = this._current;\n this._current += 1;\n if (stream[this._current] === '|') {\n this._current += 1;\n tokens.push({ type: TOK_OR, value: '||', start });\n } else {\n tokens.push({ type: TOK_PIPE, value: '|', start });\n }\n } else {\n throw syntaxError(`Unknown character:${stream[this._current]}`);\n }\n }\n return tokens;\n }\n\n _consumeUnquotedIdentifier(stream) {\n const start = this._current;\n this._current += 1;\n while (\n this._current < stream.length\n && (stream[this._current] === '$' || isAlphaNum(stream[this._current]))\n ) {\n this._current += 1;\n }\n return stream.slice(start, this._current);\n }\n\n _consumeQuotedIdentifier(stream) {\n const start = this._current;\n this._current += 1;\n const maxLength = stream.length;\n let foundNonAlpha = !isIdentifier(stream, start + 1);\n while (stream[this._current] !== \"'\" && this._current < maxLength) {\n // You can escape a single quote and you can escape an escape.\n let current = this._current;\n if (!isAlphaNum(stream[current])) foundNonAlpha = true;\n if (stream[current] === '\\\\' && (stream[current + 1] === '\\\\'\n || stream[current + 1] === \"'\")) {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n this._current += 1;\n const val = stream.slice(start, this._current);\n // Check for unnecessary single quotes.\n // json-formula uses single quotes to escape characters that don't belong in names.\n // e.g. \"purchase-order\".address\n // If we find a single-quoted entity with spaces or all legal characters, issue a warning\n try {\n if (!foundNonAlpha) {\n this.debug.push(`Suspicious quotes: ${val}`);\n this.debug.push(`Did you intend a literal? \"${val.replace(/'/g, '')}\"?`);\n }\n // eslint-disable-next-line no-empty\n } catch (e) { }\n // we want to do all the escape-processing that JSON does ...\n // except that JSON expects to escape double quotes, and our identifiers\n // escape single quotes.\n return JSON.parse(`\"${val.substring(1, val.length - 1).replace(/\\\\'/g, \"'\")}\"`);\n }\n\n _consumeRawStringLiteral(stream) {\n const start = this._current;\n this._current += 1;\n const maxLength = stream.length;\n while (stream[this._current] !== '\"' && this._current < maxLength) {\n // You can escape a double quote and you can escape an escape.\n let current = this._current;\n if (stream[current] === '\\\\' && (stream[current + 1] === '\\\\'\n || stream[current + 1] === '\"')) {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n this._current += 1;\n const literal = stream.slice(start + 1, this._current - 1);\n if (this._current > maxLength) {\n throw syntaxError(`Unterminated string literal at ${start}, \"${literal}`);\n }\n try {\n return JSON.parse(`\"${literal}\"`);\n } catch (_e) {\n throw syntaxError(`Invalid string literal: ${literal}`);\n }\n }\n\n _isNumber(stream) {\n // if we see the first two characters are either a digit or radix, then we have a number\n let ch = stream[this._current];\n if (ch >= '0' && ch <= '9') return true;\n if (ch !== '.') return false;\n if (this._current === stream.length) return false;\n ch = stream[this._current + 1];\n return ch >= '0' && ch <= '9';\n }\n\n _consumeNumber(stream) {\n const start = this._current;\n const num = stream.slice(start);\n const match = num.match(/^[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?/);\n if (!match) throw syntaxError(`Invalid number: ${num}`);\n const n = match[0];\n this._current += n.length;\n let value;\n if (n.includes('.') || n.toLowerCase().includes('e')) {\n value = parseFloat(n);\n return { type: TOK_NUMBER, value, start };\n }\n value = parseInt(n, 10);\n return { type: TOK_INT, value, start };\n }\n\n _consumeUnaryMinus() {\n const start = this._current;\n this._current += 1;\n return { type: TOK_UNARY_MINUS, value: '-', start };\n }\n\n _consumeLBracket(stream) {\n const start = this._current;\n this._current += 1;\n if (stream[this._current] === '?') {\n this._current += 1;\n return { type: TOK_FILTER, value: '[?', start };\n }\n if (stream[this._current] === ']') {\n this._current += 1;\n return { type: TOK_FLATTEN, value: '[]', start };\n }\n return { type: TOK_LBRACKET, value: '[', start };\n }\n\n _isGlobal(prev, stream, pos) {\n // global tokens occur only at the start of an expression\n if (prev !== null && prev === TOK_DOT) return false;\n const ch = stream[pos];\n if (ch !== globalStartToken) return false;\n // $ is special -- it's allowed to be part of an identifier if it's the first character\n let i = pos + 1;\n while (i < stream.length && (stream[i] === '$' || isAlphaNum(stream[i]))) i += 1;\n const global = stream.slice(pos, i);\n return this._allowedGlobalNames.includes(global);\n }\n\n _consumeGlobal(stream) {\n const start = this._current;\n this._current += 1;\n while (this._current < stream.length\n && (stream[this._current] === '$' || isAlphaNum(stream[this._current]))) this._current += 1;\n const global = stream.slice(start, this._current);\n\n return { type: TOK_GLOBAL, name: global, start };\n }\n\n _consumeOperator(stream) {\n const start = this._current;\n const startingChar = stream[start];\n this._current += 1;\n if (startingChar === '!') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '!=', start };\n }\n return { type: TOK_NOT, value: '!', start };\n }\n if (startingChar === '<') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '<=', start };\n }\n if (stream[this._current] === '>') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '!=', start };\n }\n return { type: TOK_COMPARATOR, value: '<', start };\n }\n if (startingChar === '>') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '>=', start };\n }\n return { type: TOK_COMPARATOR, value: '>', start };\n }\n // startingChar is '='\n if (stream[this._current] === '=') {\n this._current += 1;\n }\n return { type: TOK_COMPARATOR, value: '==', start };\n }\n\n _consumeJson(stream) {\n this._current += 1;\n const start = this._current;\n const maxLength = stream.length;\n while (stream[this._current] !== '`' && this._current < maxLength) {\n let current = this._current;\n if (stream[current] === '\\\\' && stream[current + 1] === '`') {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n let literalString = stream.slice(start, this._current).trimStart();\n literalString = literalString.replaceAll('\\\\`', '`');\n // +1 gets us to the ending \"`\", +1 to move on to the next char.\n this._current += 1;\n if (this._current > maxLength) {\n throw syntaxError(`Unterminated JSON literal at ${start}: \\`${literalString}`);\n }\n\n return JSON.parse(literalString);\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport Lexer from './Lexer.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { syntaxError } from './errors.js';\n\n/* eslint-disable no-underscore-dangle */\nconst {\n TOK_JSON,\n TOK_COLON,\n TOK_EOF,\n TOK_IDENTIFIER,\n TOK_QUOTEDIDENTIFIER,\n TOK_RBRACKET,\n TOK_RPAREN,\n TOK_COMMA,\n TOK_CONCATENATE,\n TOK_RBRACE,\n TOK_NUMBER,\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_OR,\n TOK_AND,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_UNARY_MINUS,\n TOK_MULTIPLY,\n TOK_DIVIDE,\n TOK_UNION,\n TOK_COMPARATOR,\n TOK_FLATTEN,\n TOK_STAR,\n TOK_FILTER,\n TOK_DOT,\n TOK_NOT,\n TOK_LBRACE,\n TOK_LBRACKET,\n TOK_LPAREN,\n TOK_STRING,\n TOK_INT,\n} = tokenDefinitions;\n\nconst bindingPower = {\n [TOK_EOF]: 0,\n [TOK_IDENTIFIER]: 0,\n [TOK_QUOTEDIDENTIFIER]: 0,\n [TOK_RBRACKET]: 0,\n [TOK_RPAREN]: 0,\n [TOK_COMMA]: 0,\n [TOK_RBRACE]: 0,\n [TOK_NUMBER]: 0,\n [TOK_INT]: 0,\n [TOK_CURRENT]: 0,\n [TOK_GLOBAL]: 0,\n [TOK_EXPREF]: 0,\n [TOK_PIPE]: 1,\n [TOK_OR]: 2,\n [TOK_AND]: 3,\n [TOK_COMPARATOR]: 4,\n [TOK_CONCATENATE]: 5,\n [TOK_ADD]: 6,\n [TOK_SUBTRACT]: 6,\n [TOK_UNION]: 6,\n [TOK_MULTIPLY]: 7,\n [TOK_DIVIDE]: 7,\n [TOK_NOT]: 8,\n [TOK_UNARY_MINUS]: 8,\n [TOK_FLATTEN]: 10,\n [TOK_STAR]: 20,\n [TOK_FILTER]: 21,\n [TOK_DOT]: 40,\n [TOK_LBRACE]: 50,\n [TOK_LBRACKET]: 55,\n [TOK_LPAREN]: 60,\n};\n\nexport default class Parser {\n constructor(allowedGlobalNames = []) {\n this._allowedGlobalNames = allowedGlobalNames;\n }\n\n parse(expression, debug) {\n this.debug = debug;\n this._loadTokens(expression);\n this.index = 0;\n const ast = this.expression(0);\n if (this._lookahead(0) !== TOK_EOF) {\n const t = this._lookaheadToken(0);\n throw syntaxError(`Unexpected token type: ${t.type}, value: ${t.value}`);\n }\n return ast;\n }\n\n _loadTokens(expression) {\n const lexer = new Lexer(this._allowedGlobalNames, this.debug);\n const tokens = lexer.tokenize(expression);\n tokens.push({ type: TOK_EOF, value: '', start: expression.length });\n this.tokens = tokens;\n }\n\n expression(rbp) {\n const leftToken = this._lookaheadToken(0);\n this._advance();\n let left = this.nud(leftToken);\n let currentToken = this._lookaheadToken(0, left);\n while (rbp < bindingPower[currentToken.type]) {\n this._advance();\n left = this.led(currentToken, left);\n currentToken = this._lookaheadToken(0, left);\n }\n return left;\n }\n\n _lookahead(number) {\n return this.tokens[this.index + number].type;\n }\n\n _lookaheadToken(number, previous = {}) {\n const next = this.tokens[this.index + number];\n // disambiguate multiply and star\n if (next.type === TOK_STAR) {\n if (![\n undefined,\n TOK_LBRACKET,\n TOK_DOT,\n TOK_PIPE,\n TOK_AND,\n TOK_OR,\n TOK_COMMA,\n TOK_NOT,\n TOK_MULTIPLY,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_DIVIDE,\n TOK_LPAREN,\n TOK_CONCATENATE,\n TOK_UNION,\n TOK_COMPARATOR].includes(previous.type)) {\n next.type = TOK_MULTIPLY;\n }\n }\n\n return next;\n }\n\n _advance() {\n this.index += 1;\n }\n\n _lookAheadIndex() {\n let idx = 0;\n if (this._lookahead(idx) === TOK_UNARY_MINUS) idx += 1;\n if (this._lookahead(idx) === TOK_INT) idx += 1;\n if (this._lookahead(idx) === TOK_RBRACKET\n || this._lookahead(idx) === TOK_COLON) return true;\n return false;\n }\n\n _getIndex() {\n return this.index;\n }\n\n _setIndex(index) {\n this.index = index;\n }\n\n // eslint-disable-next-line consistent-return\n nud(token) {\n let left;\n let right;\n let expression;\n let node;\n let args;\n switch (token.type) {\n case TOK_STRING:\n return { type: 'String', value: token.value };\n case TOK_JSON:\n return { type: 'Literal', value: token.value };\n case TOK_NUMBER:\n return { type: 'Number', value: token.value };\n case TOK_INT:\n return { type: 'Integer', value: token.value };\n case TOK_IDENTIFIER:\n return { type: 'Identifier', name: token.value };\n case TOK_QUOTEDIDENTIFIER:\n node = { type: 'QuotedIdentifier', name: token.value };\n return node;\n case TOK_NOT:\n right = this.expression(bindingPower.Not);\n return { type: 'NotExpression', children: [right] };\n case TOK_UNARY_MINUS:\n right = this.expression(bindingPower.UnaryMinus);\n return { type: 'UnaryMinusExpression', children: [right] };\n case TOK_STAR:\n left = { type: 'Identity' };\n if (this._lookahead(0) === TOK_RBRACKET) {\n // This can happen in a ArrayExpression,\n // [a, b, *]\n right = { type: 'Identity' };\n } else {\n right = this._parseProjectionRHS(bindingPower.Star);\n }\n return { type: 'ValueProjection', children: [left, right] };\n case TOK_FILTER:\n return this.led(token, { type: 'Identity' });\n case TOK_LBRACE:\n return this._parseObjectExpression();\n case TOK_FLATTEN:\n left = { type: TOK_FLATTEN, children: [{ type: 'Identity' }] };\n right = this._parseProjectionRHS(bindingPower.Flatten);\n return { type: 'Projection', children: [left, right] };\n case TOK_LBRACKET:\n if (this._lookAheadIndex()) {\n right = this._parseIndexExpression();\n return this._projectIfSlice({ type: 'Identity' }, right);\n }\n if (this._lookahead(0) === TOK_STAR && this._lookahead(1) === TOK_RBRACKET) {\n this._advance();\n this._advance();\n right = this._parseProjectionRHS(bindingPower.Star);\n return {\n type: 'Projection',\n children: [{ type: 'Identity' }, right],\n debug: 'Wildcard',\n };\n }\n return this._parseArrayExpression();\n\n case TOK_CURRENT:\n return { type: TOK_CURRENT };\n case TOK_GLOBAL:\n return { type: TOK_GLOBAL, name: token.name };\n case TOK_EXPREF:\n expression = this.expression(bindingPower.Expref);\n return { type: 'ExpressionReference', children: [expression] };\n case TOK_LPAREN:\n args = [];\n while (this._lookahead(0) !== TOK_RPAREN) {\n expression = this.expression(0);\n args.push(expression);\n }\n this._match(TOK_RPAREN);\n return args[0];\n default:\n this._errorToken(token);\n }\n }\n\n // eslint-disable-next-line consistent-return\n led(token, left) {\n let condition;\n let right;\n let name;\n let args;\n let node;\n let rbp;\n let leftNode;\n let rightNode;\n const tokenName = token.type;\n switch (tokenName) {\n case TOK_CONCATENATE:\n right = this.expression(bindingPower.Concatenate);\n return { type: 'ConcatenateExpression', children: [left, right] };\n case TOK_DOT:\n rbp = bindingPower.Dot;\n if (this._lookahead(0) !== TOK_STAR) {\n right = this._parseDotRHS(rbp);\n return { type: 'ChainedExpression', children: [left, right] };\n }\n // Creating a projection.\n this._advance();\n right = this._parseProjectionRHS(rbp);\n return { type: 'ValueProjection', children: [left, right] };\n case TOK_PIPE:\n right = this.expression(bindingPower.Pipe);\n return { type: TOK_PIPE, children: [left, right] };\n case TOK_OR:\n right = this.expression(bindingPower.Or);\n return { type: 'OrExpression', children: [left, right] };\n case TOK_AND:\n right = this.expression(bindingPower.And);\n return { type: 'AndExpression', children: [left, right] };\n case TOK_ADD:\n right = this.expression(bindingPower.Add);\n return { type: 'AddExpression', children: [left, right] };\n case TOK_SUBTRACT:\n right = this.expression(bindingPower.Subtract);\n return { type: 'SubtractExpression', children: [left, right] };\n case TOK_MULTIPLY:\n right = this.expression(bindingPower.Multiply);\n return { type: 'MultiplyExpression', children: [left, right] };\n case TOK_DIVIDE:\n right = this.expression(bindingPower.Divide);\n return { type: 'DivideExpression', children: [left, right] };\n case TOK_UNION:\n right = this.expression(bindingPower.Union);\n return { type: 'UnionExpression', children: [left, right] };\n case TOK_LPAREN:\n if (left.type !== TOK_IDENTIFIER) {\n throw syntaxError('Bad function syntax. Parenthesis must be preceded by an unquoted identifier');\n }\n name = left.name;\n args = this._parseFunctionArgs();\n node = { type: 'Function', name, children: args };\n return node;\n case TOK_FILTER:\n condition = this.expression(0);\n this._match(TOK_RBRACKET);\n right = this._parseProjectionRHS(bindingPower.Filter);\n return { type: 'FilterProjection', children: [left, right, condition] };\n case TOK_FLATTEN:\n leftNode = { type: TOK_FLATTEN, children: [left] };\n rightNode = this._parseProjectionRHS(bindingPower.Flatten);\n return { type: 'Projection', children: [leftNode, rightNode] };\n case TOK_COMPARATOR:\n return this._parseComparator(left, token);\n case TOK_LBRACKET:\n if (this._lookahead(0) === TOK_STAR\n && this._lookahead(1) === TOK_RBRACKET) {\n this._advance();\n this._advance();\n right = this._parseProjectionRHS(bindingPower.Star);\n return { type: 'Projection', children: [left, right], debug: 'Wildcard' };\n }\n right = this._parseIndexExpression();\n return this._projectIfSlice(left, right);\n default:\n this._errorToken(token);\n }\n }\n\n _match(tokenType) {\n const token = this._lookaheadToken(0);\n if (token.type === tokenType) {\n this._advance();\n return token;\n }\n throw syntaxError(`Expected ${tokenType}, got: ${token.type}`);\n }\n\n // eslint-disable-next-line class-methods-use-this\n _errorToken(token) {\n throw syntaxError(`Unexpected token (${\n token.type}): \"${\n token.value || token.name}\"`);\n }\n\n _parseFunctionArgs() {\n let firstExpression = true;\n const args = [];\n while (this._lookahead(0) !== TOK_RPAREN) {\n if (!firstExpression) {\n this._match(TOK_COMMA);\n }\n args.push(this.expression(0));\n firstExpression = false;\n }\n this._match(TOK_RPAREN);\n return args;\n }\n\n _parseSignedInt() {\n const first = this._lookaheadToken(0);\n if (first.type === TOK_UNARY_MINUS) {\n this._advance();\n const value = this._match(TOK_INT);\n return {\n type: 'SignedInt',\n value: -value.value,\n };\n }\n if (first.type !== TOK_INT) this._errorToken(first);\n this._advance();\n return {\n type: 'SignedInt',\n value: first.value,\n };\n }\n\n _parseIndexExpression() {\n const oldIndex = this._getIndex();\n if (this._lookahead(0) === TOK_COLON) {\n return this._parseSliceExpression();\n }\n // look ahead of the first expression to determine the type\n const first = this._parseSignedInt();\n const token = this._lookahead(0);\n if (token === TOK_COLON) {\n // now that we know the type revert back to the old position and parse\n this._setIndex(oldIndex);\n return this._parseSliceExpression();\n }\n this._match(TOK_RBRACKET);\n return {\n type: 'Index',\n value: first,\n };\n }\n\n _projectIfSlice(left, right) {\n const indexExpr = { type: 'BracketExpression', children: [left, right] };\n if (right.type === 'Slice') {\n return {\n type: 'Projection',\n children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)],\n };\n }\n return indexExpr;\n }\n\n _parseSliceExpression() {\n // [start:end:step] where each part is optional, as well as the last\n // colon.\n const parts = [null, null, null];\n let index = 0;\n let currentToken = this._lookahead(0);\n while (currentToken !== TOK_RBRACKET && index < 3) {\n if (currentToken === TOK_COLON && index < 2) { // there can't be more than 2 colons\n index += 1;\n this._advance();\n } else {\n parts[index] = this._parseSignedInt();\n // check next token to be either colon or rbracket\n const t = this._lookahead(0);\n if (t !== TOK_COLON && t !== TOK_RBRACKET) {\n throw syntaxError(`Unexpected token: ${\n t.value}(${t.type})`);\n }\n }\n currentToken = this._lookahead(0);\n }\n this._match(TOK_RBRACKET);\n return {\n type: 'Slice',\n children: parts,\n };\n }\n\n _parseComparator(left, comparator) {\n const right = this.expression(bindingPower[comparator.type]);\n return { type: 'Comparator', value: comparator.value, children: [left, right] };\n }\n\n _parseDotRHS(rbp) {\n const lookahead = this._lookahead(0);\n const exprTokens = [TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];\n if (exprTokens.indexOf(lookahead) >= 0) {\n return this.expression(rbp);\n }\n if (lookahead === TOK_LBRACKET) {\n this._match(TOK_LBRACKET);\n return this._parseArrayExpression();\n }\n if (lookahead === TOK_LBRACE) {\n this._match(TOK_LBRACE);\n return this._parseObjectExpression();\n }\n throw syntaxError('Expecting one of: \"*\", \"[\", \"{\", name or quoted name after a dot');\n }\n\n _parseProjectionRHS(rbp) {\n let right;\n const next = this._lookaheadToken(0, { type: TOK_STAR });\n if (bindingPower[next.type] <= bindingPower[TOK_FLATTEN]) {\n right = { type: 'Identity' };\n } else if (next.type === TOK_LBRACKET) {\n right = this.expression(rbp);\n } else if (next.type === TOK_FILTER) {\n right = this.expression(rbp);\n } else if (next.type === TOK_DOT) {\n this._match(TOK_DOT);\n right = this._parseDotRHS(rbp);\n } else {\n throw syntaxError(`Unexpected token: ${next.value}(${next.type})`);\n }\n return right;\n }\n\n _parseArrayExpression() {\n const expressions = [];\n while (this._lookahead(0) !== TOK_RBRACKET) {\n const expression = this.expression(0);\n expressions.push(expression);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n if (this._lookahead(0) === TOK_RBRACKET) {\n throw syntaxError('Unexpected token Rbracket');\n }\n }\n }\n this._match(TOK_RBRACKET);\n return { type: 'ArrayExpression', children: expressions };\n }\n\n _parseObjectExpression() {\n const pairs = [];\n const identifierTypes = [TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER];\n let keyToken; let keyName; let value; let\n node;\n if (this._lookahead(0) === TOK_RBRACE) {\n this.debug.push('To create an empty object, use a JSON literal: `{}`');\n throw syntaxError('An empty object expression is not allowed');\n }\n for (;;) {\n keyToken = this._lookaheadToken(0);\n if (identifierTypes.indexOf(keyToken.type) < 0) {\n throw syntaxError(`Expecting an identifier token, got: ${\n keyToken.type}`);\n }\n keyName = keyToken.value;\n this._advance();\n this._match(TOK_COLON);\n value = this.expression(0);\n node = { type: 'KeyValuePair', name: keyName, value };\n pairs.push(node);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n } else if (this._lookahead(0) === TOK_RBRACE) {\n this._match(TOK_RBRACE);\n break;\n }\n }\n return { type: 'ObjectExpression', children: pairs };\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-underscore-dangle */\nimport { dataTypes, typeNameTable } from './dataTypes.js';\nimport {\n getProperty, debugAvailable, toBoolean, strictDeepEqual,\n} from './utils.js';\nimport { evaluationError, functionError, typeError } from './errors.js';\n\nfunction round(num, digits) {\n const precision = 10 ** digits;\n return Math.round(num * precision) / precision;\n}\n\nconst MS_IN_DAY = 24 * 60 * 60 * 1000;\n\nfunction getDateObj(dateNum) {\n return new Date(Math.round(dateNum * MS_IN_DAY));\n}\n\nfunction getDateNum(dateObj) {\n return dateObj / MS_IN_DAY;\n}\n\nfunction validNumber(n, context) {\n if (Number.isNaN(n) || !Number.isFinite(n)) {\n throw evaluationError(`Call to \"${context}()\" resulted in an invalid number`);\n }\n return n;\n}\n\nexport default function functions(\n runtime,\n isObject,\n toNumber,\n getType,\n isArrayType,\n valueOf,\n toString,\n debug,\n) {\n const {\n TYPE_NUMBER,\n TYPE_ANY,\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_OBJECT,\n TYPE_BOOLEAN,\n TYPE_EXPREF,\n TYPE_NULL,\n TYPE_ARRAY_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY_ARRAY,\n } = dataTypes;\n\n function toInteger(num) {\n let n = valueOf(num);\n // functions that require an integer parameter will have declared\n // the parameters as a number, so any strings will have already been\n // converted to number before the function call.\n // However, a few functions accept a string | integer. Attempt to convert\n // to integer in these cases, but failure isn't an error.\n if (getType(n) === TYPE_STRING) n = toNumber(n);\n n = Math.trunc(num);\n if (Number.isNaN(n)) return num;\n return n;\n }\n\n function toJSON(arg, indent) {\n const value = valueOf(arg);\n if (getType(value) === TYPE_STRING) {\n return arg;\n }\n const offset = indent ? toInteger(indent) : 0;\n return JSON.stringify(value, null, offset);\n }\n\n function balanceArrays(listOfArrays) {\n const maxLen = Math.max(...listOfArrays.map(a => (Array.isArray(a) ? a.length : 0)));\n const allArrays = listOfArrays.map(a => {\n if (Array.isArray(a)) {\n return a.concat(Array(maxLen - a.length).fill(null));\n }\n return Array(maxLen).fill(a);\n });\n // convolve allArrays\n const arrays = [];\n for (let i = 0; i < maxLen; i += 1) {\n const row = [];\n for (let j = 0; j < allArrays.length; j += 1) {\n row.push(allArrays[j][i]);\n }\n arrays.push(row);\n }\n return arrays;\n }\n\n function evaluate(args, fn) {\n if (args.some(Array.isArray)) {\n return balanceArrays(args).map(a => evaluate(a, fn));\n }\n return fn(...args);\n }\n\n function datedifFn(date1Arg, date2Arg, unitArg) {\n const unit = toString(unitArg).toLowerCase();\n const date1 = getDateObj(date1Arg);\n const date2 = getDateObj(date2Arg);\n if (date2 === date1) return 0;\n if (date2 < date1) throw functionError('end_date must be >= start_date in datedif()');\n\n if (unit === 'd') return Math.floor(getDateNum(date2 - date1));\n const yearDiff = date2.getFullYear() - date1.getFullYear();\n let monthDiff = date2.getMonth() - date1.getMonth();\n const dayDiff = date2.getDate() - date1.getDate();\n\n if (unit === 'y') {\n let y = yearDiff;\n if (monthDiff < 0) y -= 1;\n if (monthDiff === 0 && dayDiff < 0) y -= 1;\n return y;\n }\n if (unit === 'm') {\n return yearDiff * 12 + monthDiff + (dayDiff < 0 ? -1 : 0);\n }\n if (unit === 'ym') {\n if (dayDiff < 0) monthDiff -= 1;\n if (monthDiff <= 0 && yearDiff > 0) return 12 + monthDiff;\n return monthDiff;\n }\n if (unit === 'yd') {\n if (dayDiff < 0) monthDiff -= 1;\n if (monthDiff < 0) date2.setFullYear(date1.getFullYear() + 1);\n else date2.setFullYear(date1.getFullYear());\n return Math.floor(getDateNum(date2 - date1));\n }\n throw functionError(`Unrecognized unit parameter \"${unit}\" for datedif()`);\n }\n\n function endsWithFn(searchArg, suffixArg) {\n const searchStr = valueOf(searchArg);\n const suffix = valueOf(suffixArg);\n // make sure the comparison is based on code points\n const search = Array.from(searchStr).reverse();\n const ending = Array.from(suffix).reverse();\n return ending.every((c, i) => c === search[i]);\n }\n\n function eomonthFn(dateArg, monthsArg) {\n const jsDate = getDateObj(dateArg);\n const months = toInteger(monthsArg);\n // We can give the constructor a month value > 11 and it will increment the years\n // Since day is 1-based, giving zero will yield the last day of the previous month\n const newDate = new Date(jsDate.getFullYear(), jsDate.getMonth() + months + 1, 0);\n return getDateNum(newDate);\n }\n\n function findFn(queryArg, textArg, offsetArg) {\n const query = Array.from(toString(queryArg));\n const text = Array.from(toString(textArg));\n const offset = toInteger(offsetArg);\n if (offset < 0) throw evaluationError('find() start position must be >= 0');\n if (query.length === 0) {\n // allow an empty string to be found at any position -- including the end\n if (offset > text.length) return null;\n return offset;\n }\n for (let i = offset; i < text.length; i += 1) {\n if (text.slice(i, i + query.length).every((c, j) => c === query[j])) {\n return i;\n }\n }\n return null;\n }\n\n function properFn(arg) {\n const capitalize = word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`;\n const original = toString(arg);\n // split the string by whitespace, punctuation, and numbers\n const wordParts = original.match(/[\\s\\d\\p{P}]+|[^\\s\\d\\p{P}]+/gu);\n if (wordParts !== null) return wordParts.map(w => capitalize(w)).join('');\n return capitalize(original);\n }\n\n function reptFn(textArg, countArg) {\n const text = toString(textArg);\n const count = toInteger(countArg);\n if (count < 0) throw evaluationError('rept() count must be greater than or equal to 0');\n return text.repeat(count);\n }\n\n function searchFn(findTextString, withinTextString, startPosInt = 0) {\n const findText = toString(findTextString);\n const withinText = toString(withinTextString);\n const startPos = toInteger(startPosInt);\n if (startPos < 0) throw functionError('search() startPos must be greater than or equal to 0');\n if (findText === null || withinText === null || withinText.length === 0) return [];\n\n // Process as an array of code points\n // Find escapes and wildcards\n const globString = Array.from(findText).reduce((acc, cur) => {\n if (acc.escape) return { escape: false, result: acc.result.concat(cur) };\n if (cur === '\\\\') return { escape: true, result: acc.result };\n if (cur === '?') return { escape: false, result: acc.result.concat('dot') };\n if (cur === '*') {\n // consecutive * are treated as a single *\n if (acc.result.slice(-1).pop() === 'star') return acc;\n return { escape: false, result: acc.result.concat('star') };\n }\n return { escape: false, result: acc.result.concat(cur) };\n }, { escape: false, result: [] }).result;\n\n const testMatch = (array, glob, match) => {\n // we've consumed the entire glob, so we're done\n if (glob.length === 0) return match;\n // we've consumed the entire array, but there's still glob left -- no match\n if (array.length === 0) return null;\n const testChar = array[0];\n let [globChar, ...nextGlob] = glob;\n const isStar = globChar === 'star';\n if (isStar) {\n // '*' is at the end of the match -- so we're done matching\n if (glob.length === 1) return match;\n // we'll check for a match past the * and if not found, we'll process the *\n [globChar, ...nextGlob] = glob.slice(1);\n }\n if (testChar === globChar || globChar === 'dot') {\n return testMatch(array.slice(1), nextGlob, match.concat(testChar));\n }\n // no match, so consume wildcard *\n if (isStar) return testMatch(array.slice(1), glob, match.concat(testChar));\n\n return null;\n };\n // process code points\n const within = Array.from(withinText);\n for (let i = startPos; i < within.length; i += 1) {\n const result = testMatch(within.slice(i), globString, []);\n if (result !== null) return [i, result.join('')];\n }\n return [];\n }\n\n function splitFn(strArg, separatorArg) {\n const str = toString(strArg);\n const separator = toString(separatorArg);\n // for empty separator, return an array of code points\n return separator.length === 0 ? Array.from(str) : str.split(separator);\n }\n\n function startsWithFn(subjectString, prefixString) {\n const subject = Array.from(toString(subjectString));\n const prefix = Array.from(toString(prefixString));\n if (prefix.length > subject.length) return false;\n for (let i = 0; i < prefix.length; i += 1) {\n if (prefix[i] !== subject[i]) return false;\n }\n return true;\n }\n\n function substituteFn(source, oldString, replacementString, nearest) {\n const src = Array.from(toString(source));\n const old = Array.from(toString(oldString));\n const replacement = Array.from(toString(replacementString));\n\n if (old.length === 0) return source;\n\n // no third parameter? replace all instances\n let replaceAll = true;\n let whch = 0;\n if (nearest > -1) {\n replaceAll = false;\n whch = nearest + 1;\n }\n\n let found = 0;\n const result = [];\n // find the instances to replace\n for (let j = 0; j < src.length;) {\n const match = old.every((c, i) => src[j + i] === c);\n if (match) found += 1;\n if (match && (replaceAll || found === whch)) {\n result.push(...replacement);\n j += old.length;\n } else {\n result.push(src[j]);\n j += 1;\n }\n }\n return result.join('');\n }\n\n function truncFn(number, d) {\n const digits = toInteger(d);\n\n const method = number >= 0 ? Math.floor : Math.ceil;\n return method(number * 10 ** digits) / 10 ** digits;\n }\n\n function weekdayFn(date, type) {\n const jsDate = getDateObj(date);\n const day = jsDate.getDay();\n // day is in range [0-7) with 0 mapping to sunday\n switch (toInteger(type)) {\n case 1:\n // range = [1, 7], sunday = 1\n return day + 1;\n case 2:\n // range = [1, 7] sunday = 7\n return ((day + 6) % 7) + 1;\n case 3:\n // range = [0, 6] sunday = 6\n return (day + 6) % 7;\n default:\n throw functionError(`Unsupported returnType: \"${type}\" for weekday()`);\n }\n }\n\n const functionMap = {\n // name: [function, ]\n // The can be:\n //\n // {\n // args: [[type1, type2], [type1, type2]],\n // variadic: true|false\n // }\n //\n // Each arg in the arg list is a list of valid types\n // (if the function is overloaded and supports multiple\n // types. If the type is \"any\" then no type checking\n // occurs on the argument. Variadic is optional\n // and if not provided is assumed to be false.\n /**\n * Find the absolute (non-negative) value of the provided argument `value`.\n * @param {number|number[]} value A numeric value\n * @return {number|number[]} If `value < 0`, returns `-value`, otherwise returns `value`\n * @function abs\n * @example\n * abs(-1) // returns 1\n */\n abs: {\n _func: args => evaluate(args, Math.abs),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n /**\n * Compute the inverse cosine (in radians) of a number.\n * @param {number|number[]} cosine A number between -1 and 1, inclusive,\n * representing the angle's cosine value.\n * @return {number|number[]} The inverse cosine angle in radians between 0 and PI\n * @function acos\n * @example\n * acos(0) => 1.5707963267948966\n */\n acos: {\n _func: args => evaluate(args, n => validNumber(Math.acos(n), 'acos')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Finds the logical AND result of all parameters.\n * If the parameters are not boolean they will be <<_type_coercion_rules,cast to boolean>>.\n * Note the related <<_and_operator, And Operator>>.\n * @param {any} firstOperand logical expression\n * @param {...any} [additionalOperands] any number of additional expressions\n * @returns {boolean} The logical result of applying AND to all parameters\n * @example\n * and(10 > 8, length(\"foo\") < 5) // returns true\n * and(`null`, length(\"foo\") < 5) // returns false\n * @function and\n */\n and: {\n _func: resolvedArgs => {\n let result = toBoolean(valueOf(resolvedArgs[0]));\n resolvedArgs.slice(1).forEach(arg => {\n result = result && toBoolean(valueOf(arg));\n });\n return result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n\n /**\n * Compute the inverse sine (in radians) of a number.\n * @param {number|number[]} sine A number between -1 and 1, inclusive,\n * representing the angle's sine value.\n * @return {number|number[]} The inverse sine angle in radians between -PI/2 and PI/2\n * @function asin\n * @example\n * Math.asin(0) => 0\n */\n asin: {\n _func: args => evaluate(args, n => validNumber(Math.asin(n), 'asin')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Compute the angle in the plane (in radians) between the positive\n * x-axis and the ray from (0, 0) to the point (x, y)\n * @param {number|number[]} y The y coordinate of the point\n * @param {number|number[]} x The x coordinate of the point\n * @return {number|number[]} The angle in radians (between -PI and PI),\n * between the positive x-axis and the ray from (0, 0) to the point (x, y).\n * @function atan2\n * @example\n * atan2(20,10) => 1.1071487177940904\n */\n atan2: {\n _func: args => evaluate(args, Math.atan2),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds the average of the elements in an array.\n * Non-numeric values (text, boolean, null, object) are ignored.\n * If there are nested arrays, they are flattened.\n * If the array is empty, an evaluation error is thrown\n * @param {any[]} elements array of values\n * @return {number} average value\n * @function avg\n * @example\n * avg([1, 2, 3]) // returns 2\n */\n avg: {\n _func: resolvedArgs => {\n let sum = 0;\n const filtered = resolvedArgs\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (filtered.length === 0) throw evaluationError('avg() requires at least one argument');\n filtered.forEach(a => {\n sum += a;\n });\n return sum / filtered.length;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Finds the average of the elements in an array, converting strings and booleans to number.\n * If any conversions to number fail, a type error is thrown.\n * If there are nested arrays, they are flattened.\n * If the array is empty, an evaluation error is thrown\n * @param {number[]} elements array of numeric values\n * @return {number} average value\n * @function avgA\n * @example\n * avgA([1, 2, \"3\", null()]) // returns 2\n */\n avgA: {\n _func: resolvedArgs => {\n let sum = 0;\n let filtered;\n try {\n filtered = resolvedArgs\n .flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n } catch (_e) {\n throw typeError('avgA() received non-numeric parameters');\n }\n if (filtered.length === 0) throw evaluationError('avg() requires at least one argument');\n filtered.forEach(a => {\n sum += a;\n });\n return sum / filtered.length;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Generates a lower-case string of the `input` string using locale-specific mappings.\n * e.g. Strings with German letter ß (eszett) can be compared to \"ss\"\n * @param {string|string[]} input string to casefold\n * @returns {string|string[]} A new string converted to lower case\n * @function casefold\n * @example\n * casefold(\"AbC\") // returns \"abc\"\n */\n casefold: {\n _func: (args, _data, interpreter) => evaluate(args, s => toString(s)\n .toLocaleUpperCase(interpreter.language)\n .toLocaleLowerCase(interpreter.language)),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Finds the next highest integer value of the argument `num` by rounding up if necessary.\n * i.e. ceil() rounds toward positive infinity.\n * @param {number|number[]} num numeric value\n * @return {integer|integer[]} The smallest integer greater than or equal to num\n * @function ceil\n * @example\n * ceil(10) // returns 10\n * ceil(10.4) // return 11\n\n */\n ceil: {\n _func: args => evaluate(args, Math.ceil),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n /**\n * Retrieve the first code point from a string\n * @param {string|string[]} str source string.\n * @return {integer|integer[]} Unicode code point value.\n * If the input string is empty, returns `null`.\n * @function codePoint\n * @example\n * codePoint(\"ABC\") // 65\n */\n codePoint: {\n _func: args => evaluate(args, arg => {\n const text = toString(arg);\n return text.length === 0 ? null : text.codePointAt(0);\n }),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Determines if the given `subject` contains `search`.\n * If `subject` is an array, this function returns true if one of the elements\n * in the array is equal to the `search` value. If `subject`\n * is a string, return true if the string contains the\n * `search` value.\n * @param {array|string} subject The element to be searched\n * @param {any} search element to find.\n * If `subject` is an array, search for an exact match for `search` in the array.\n * If `subject` is a string, `search` must also be a string.\n * @return {boolean} true if found\n * @function contains\n * @example\n * contains([1, 2, 3, 4], 2) // returns true\n * contains([1, 2, 3, 4], -1) // returns false\n * contains(\"Abcd\", \"d\") // returns true\n * contains(\"Abcd\", \"x\") // returns false\n\n */\n contains: {\n _func: resolvedArgs => {\n const subject = valueOf(resolvedArgs[0]);\n const search = valueOf(resolvedArgs[1]);\n if (isArrayType(resolvedArgs[0])) {\n return subject.some(s => strictDeepEqual(s, search));\n }\n const source = Array.from(subject);\n if (getType(search) !== TYPE_STRING) {\n throw typeError('contains() requires a string search value for string subjects');\n }\n if (search === '') return true;\n const searchLen = Array.from(search).length;\n for (let i = 0; i < source.length; i += 1) {\n if (source.slice(i, i + searchLen).join('') === search) return true;\n }\n return false;\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_ANY] }],\n },\n /**\n * Compute the cosine (in radians) of a number.\n * @param {number|number[]} angle A number representing an angle in radians\n * @return {number|number[]} The cosine of the angle, between -1 and 1, inclusive.\n * @function cos\n * @example\n * cos(1.0471975512) => 0.4999999999970535\n */\n cos: {\n _func: args => evaluate(args, Math.cos),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Return difference between two date values.\n * The measurement of the difference is determined by the `unit` parameter. One of:\n *\n * * `y` the number of whole years between `start_date` and `end_date`\n * * `m` the number of whole months between `start_date` and `end_date`.\n * * `d` the number of days between `start_date` and `end_date`\n * * `ym` the number of whole months between `start_date` and `end_date`\n * after subtracting whole years.\n * * `yd` the number of days between `start_date` and `end_date`, assuming `start_date`\n * and `end_date` were no more than one year apart\n * @param {number|number[]} start_date The starting <<_date_and_time_values, date/time value>>.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {number|number[]} end_date The end <<_date_and_time_values, date/time value>> -- must\n * be greater or equal to start_date. If not, an error will be thrown.\n * @param {string|string[]} unit Case-insensitive string representing the unit of\n * time to measure. An unrecognized unit will result in an error.\n * @returns {integer|integer[]} The number of days/months/years difference\n * @function datedif\n * @example\n * datedif(datetime(2001, 1, 1), datetime(2003, 1, 1), \"y\") // returns 2\n * datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), \"D\") // returns 805\n * // 805 days between June 1, 2001, and August 15, 2003\n * datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), \"YD\") // returns 75\n * // 75 days between June 1 and August 15, ignoring the years of the dates (75)\n */\n datedif: {\n _func: args => evaluate(args, datedifFn),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Generate a date/time value from individual date/time parts.\n * If any of the units are greater than their normal range,\n * the overflow will be added to the next greater unit.\n * e.g. specifying 25 hours will increment the day value by 1.\n * Similarly,\n * negative values will decrement the next greater unit.\n * e.g. datetime(year, month, day - 30) will return a date 30 days earlier.\n * @param {integer} year The year to use for date construction.\n * Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year\n * @param {integer} month The month: beginning with 1 for\n * January to 12 for December.\n * @param {integer} day The day of the month.\n * @param {integer} [hours=0] Integer value between 0 and 23 representing the hour of the day.\n * @param {integer} [minutes=0] Integer value representing the minute segment of a time.\n * @param {integer} [seconds=0] Integer value representing the second segment of a time.\n * @param {integer} [milliseconds=0] Integer value representing the\n * millisecond segment of a time.\n * @returns {number} A <<_date_and_time_values, date/time value>>\n * to be used with other date/time functions\n * @function datetime\n * @example\n * datetime(2010, 10, 10) // returns representation of October 10, 2010\n * datetime(2010, 2, 28) // returns representation of February 28, 2010\n * datetime(2023,13,5) | year(@) & \"/\" & month(@) // returns 2024/1\n */\n datetime: {\n _func: args => {\n const year = toInteger(args[0]);\n const month = toInteger(args[1]) - 1; // javascript months start from 0\n const day = toInteger(args[2]);\n const hours = args.length > 3 ? toInteger(args[3]) : 0;\n const minutes = args.length > 4 ? toInteger(args[4]) : 0;\n const seconds = args.length > 5 ? toInteger(args[5]) : 0;\n const ms = args.length > 6 ? toInteger(args[6]) : 0;\n\n const baseDate = new Date(year, month, day, hours, minutes, seconds, ms);\n\n return getDateNum(baseDate);\n },\n _signature: [\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the day of the month for a date value\n * @param {number|number[]} date <<_date_and_time_values, date/time value>> generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The day of the month ranging from 1 to 31.\n * @function day\n * @example\n * day(datetime(2008,5,23)) // returns 23\n */\n day: {\n _func: args => evaluate(args, a => getDateObj(a).getDate()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Debug a json-formula expression.\n * The `debug()` function allows users to inspect a sub-expression within a formula.\n * @param {any} arg The expression to return from `debug()` function,\n * and the default expression to be debugged. May be any type except an expression.\n * @param {any|expression} [displayValue=arg] Optionally override the value to be debugged.\n * `displayValue` may be an expression to\n * be evaluated with the context of `arg`.\n * @returns {any} The value of the `arg` parameter\n * @function debug\n * @example\n * avg(([1,2,3] * [2,3,4]).debug(@)).round(@,3) // 6.667\n * avg(debug([1,2,3] * [2,3,4],&\"average of: \" &toString(@))).round(@,3) // 6.667\n */\n debug: {\n _func: resolvedArgs => {\n const arg = resolvedArgs[0];\n if (resolvedArgs.length > 1) {\n if (getType(resolvedArgs[1]) === TYPE_EXPREF) {\n debug.push(runtime.interpreter.visit(resolvedArgs[1], arg));\n } else {\n debug.push(resolvedArgs[1]);\n }\n } else {\n debug.push(toJSON(resolvedArgs[0]));\n }\n return arg;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY, TYPE_EXPREF], optional: true },\n ],\n },\n\n /**\n * Performs a depth-first search of a nested hierarchy to\n * return an array of key values that match a `name`.\n * The name can be either a key into an object or an array index.\n * This is similar to the Descendant Accessor operator (`..`) from [E4X](https://ecma-international.org/publications-and-standards/standards/ecma-357/).\n * @param {object|array|null} object The starting object or array where we start the search\n * @param {string|integer} name The name (or index position) of the elements to find.\n * If `name` is a string, search for nested objects with a matching key.\n * If `name` is an integer, search for nested arrays with a matching index.\n * @returns {any[]} The array of matched elements\n * @function deepScan\n * @example\n * deepScan({a : {b1 : {c : 2}, b2 : {c : 3}}}, \"c\") // returns [2, 3]\n */\n deepScan: {\n _func: resolvedArgs => {\n const [source, n] = resolvedArgs;\n const [name, checkArrays] = getType(n) === TYPE_NUMBER\n ? [toInteger(n), true] : [toString(n), false];\n const items = [];\n function scan(node) {\n if (node === null) return;\n if (isArrayType(node)) {\n if (checkArrays && node[name] !== undefined) items.push(node[name]);\n node.forEach(scan);\n } else if (isObject(node)) {\n Object.entries(node).forEach(([k, v]) => {\n if (!checkArrays && k === name) items.push(v);\n scan(v);\n });\n }\n }\n scan(source);\n return items;\n },\n _signature: [\n { types: [TYPE_OBJECT, TYPE_ARRAY, TYPE_NULL] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n\n /**\n * Determines if the `subject` string ends with a specific `suffix`\n * @param {string|string[]} subject source string in which to search\n * @param {string|string[]} suffix search string\n * @return {boolean|boolean[]} true if the `suffix` value is at the end of the `subject`\n * @function endsWith\n * @example\n * endsWith(\"Abcd\", \"d\") // returns true\n * endsWith(\"Abcd\", \"A\") // returns false\n */\n endsWith: {\n _func: args => evaluate(args, endsWithFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Returns an array of `[key, value]` pairs from an object or array.\n * The `fromEntries()` function may be used to convert an array to an object.\n * @param {object|array} obj source object or array\n * @returns {any[]} an array of arrays where each child array has two elements\n * representing the key and value of a pair\n * @function entries\n * @example\n * entries({a: 1, b: 2}) // returns [[\"a\", 1], [\"b\", 2]]\n * entries([4,5]) // returns [[\"0\", 4],[\"1\", 5]]\n */\n entries: {\n _func: args => {\n const obj = valueOf(args[0]);\n return Object.entries(obj);\n },\n _signature: [\n {\n types: [\n TYPE_ARRAY,\n TYPE_OBJECT,\n ],\n },\n ],\n },\n\n /**\n * Finds the date value of the end of a month, given `startDate` plus `monthAdd` months\n * @param {number|number[]} startDate The base date to start from.\n * <<_date_and_time_values, Date/time values>> can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {integer|integer[]} monthAdd Number of months to add to start date\n * @return {number|number[]} the date of the last day of the month\n * @function eomonth\n * @example\n * eomonth(datetime(2011, 1, 1), 1) | [month(@), day(@)] // returns [2, 28]\n * eomonth(datetime(2011, 1, 1), -3) | [month(@), day(@)] // returns [10, 31]\n */\n eomonth: {\n _func: args => evaluate(args, eomonthFn),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds e (the base of natural logarithms) raised to a power. (i.e. e^x)\n * @param {number|number[]} x A numeric expression representing the power of e.\n * @returns {number|number[]} e (the base of natural logarithms) raised to power x\n * @function exp\n * @example\n * exp(10) // returns 22026.465794806718\n */\n exp: {\n _func: args => evaluate(args, Math.exp),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Return constant boolean false value.\n * Expressions may also use the JSON literal: `` `false` ``\n * @returns {boolean} constant boolean value `false`\n * @function false\n */\n false: {\n _func: () => false,\n _signature: [],\n },\n\n /**\n * Finds and returns the index of query in text from a start position\n * @param {string|string[]} findText string to search\n * @param {string|string[]} withinText text to be searched\n * @param {integer|integer[]} [start=0] zero-based position to start searching.\n * If specified, `start` must be greater than or equal to 0\n * @returns {integer|null|integer[]} The position of the found string, null if not found.\n * @function find\n * @example\n * find(\"m\", \"abm\") // returns 2\n * find(\"M\", \"abMcdM\", 3) // returns 5\n * find(\"M\", \"ab\") // returns `null`\n * find(\"M\", \"abMcdM\", 2) // returns 2\n */\n find: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 3) args.push(0);\n return evaluate(args, findFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the next lowest integer value of the argument `num` by rounding down if necessary.\n * i.e. floor() rounds toward negative infinity.\n * @param {number|number[]} num numeric value\n * @return {integer|integer[]} The largest integer smaller than or equal to num\n * @function floor\n * @example\n * floor(10.4) // returns 10\n * floor(10) // returns 10\n */\n floor: {\n _func: args => evaluate(args, Math.floor),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Create a string from a code point.\n * @param {integer|integer[]} codePoint An integer or array of integers\n * between 0 and 0x10FFFF (inclusive) representing Unicode code point(s).\n * @return {string} A string from the given code point(s)\n * @function fromCodePoint\n * @example\n * fromCodePoint(65) // \"A\"\n * fromCodePoint(65) == \"\\u0041\" // true\n */\n fromCodePoint: {\n _func: args => {\n try {\n const points = Array.isArray(args[0]) ? args[0] : [args[0]];\n return String.fromCodePoint(...points.map(toInteger));\n } catch (e) {\n throw evaluationError(`Invalid code point: \"${args[0]}\"`);\n }\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Returns an object by transforming a list of key-value `pairs` into an object.\n * `fromEntries()` is the inverse operation of `entries()`.\n * If the nested arrays are not of the form: `[key, value]`\n * (where key is a string), an error will be thrown.\n * @param {any[]} pairs A nested array of key-value pairs to create the object from\n * The nested arrays must have exactly two values, where the first value is a string.\n * If a key is specified more than once, the last occurrence will override any previous value.\n * @returns {object} An object constructed from the provided key-value pairs\n * @function fromEntries\n * @example\n * fromEntries([[\"a\", 1], [\"b\", 2]]) // returns {a: 1, b: 2}\n */\n fromEntries: {\n _func: args => {\n const array = args[0];\n // validate beyond the TYPE_ARRAY_ARRAY check\n if (!array.every(a => {\n if (!Array.isArray(a)) return false;\n if (a.length !== 2) return false;\n if (getType(a[0]) !== TYPE_STRING) return false;\n return true;\n })) {\n throw typeError('fromEntries() requires an array of key value pairs');\n }\n return Object.fromEntries(array);\n },\n _signature: [\n { types: [TYPE_ARRAY_ARRAY, TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Compute the nearest 32-bit single precision float representation of a number\n * @param {number|number[]} num input to be rounded\n * @return {number|number[]} The rounded representation of `num`\n * @function fround\n * @example\n * fround(2147483650.987) => 2147483648\n * fround(100.44444444444444444444) => 100.44444274902344\n */\n fround: {\n _func: args => evaluate(args, Math.fround),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Determine if an object has a property or if an array index is in range.\n * @param {object|array|null} subject source object or array.\n * When querying for <<_hidden_properties,hidden properties>>, `subject` may be any data type.\n * @param {string|integer} name The name (or index position) of the element to find.\n * if `subject` is an array, `name` must be an integer;\n * if `subject` is an object, `name` must be a string.\n * @returns {boolean} true if the element exists\n * @function hasProperty\n * @example\n * hasProperty({a: 1, b: 2}, \"a\") // returns true\n * hasProperty([\"apples\", \"oranges\"], 3) // returns false\n * hasProperty(`null`, \"a\") // returns false\n */\n hasProperty: {\n _func: args => {\n let key = args[1];\n const keyType = getType(key);\n\n // if the object/array has a getter for this property then don't validate types\n if (args[0] !== null && Object.getOwnPropertyDescriptor(args[0], key)?.get) return true;\n const obj = valueOf(args[0]);\n if (obj === null) return false;\n const isArray = isArrayType(obj);\n if (!(isArray || getType(obj) === TYPE_OBJECT)) {\n throw typeError('First parameter to hasProperty() must be either an object or array.');\n }\n\n if (isArray) {\n if (keyType !== TYPE_NUMBER) throw TypeError('hasProperty(): Array index must be an integer');\n key = toInteger(key);\n } else if (keyType !== TYPE_STRING) throw TypeError('hasProperty(): Object key must be a string');\n const result = getProperty(obj, key);\n return result !== undefined;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n /**\n * Extract the hour from a <<_date_and_time_values, date/time value>>\n * @param {number|number[]} date The datetime/time for which the hour is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} value between 0 and 23\n * @function hour\n * @example\n * hour(datetime(2008,5,23,12, 0, 0)) // returns 12\n * hour(time(12, 0, 0)) // returns 12\n */\n hour: {\n _func: args => evaluate(args, a => getDateObj(a).getHours()),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Return one of two values `result1` or `result2`, depending on the `condition`\n * @param {any} condition boolean result of a logical expression\n * @param {any} result1 if condition is true\n * @param {any} result2 if condition is false\n * @return {any} either result1 or result2\n * @function if\n\n * @example\n * if(true(), 1, 2) // returns 1\n * if(false(), 1, 2) // returns 2\n */\n if: {\n _func: (unresolvedArgs, data, interpreter) => {\n const conditionNode = unresolvedArgs[0];\n const leftBranchNode = unresolvedArgs[1];\n const rightBranchNode = unresolvedArgs[2];\n unresolvedArgs\n .forEach(arg => {\n if (arg.type === 'ExpressionReference') {\n throw typeError('\"if()\" does not accept an expression reference argument.');\n }\n });\n\n const condition = interpreter.visit(conditionNode, data);\n if (toBoolean(valueOf(condition))) {\n return interpreter.visit(leftBranchNode, data);\n }\n return interpreter.visit(rightBranchNode, data);\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY] }],\n },\n\n /**\n * Combines all the elements from the provided\n * array, joined together using the `glue` argument as a separator between each array element.\n * @param {any[]} array array of values that will be converted to strings using `toString()`\n * @param {string} glue\n * @return {string} String representation of the array\n * @function join\n * @example\n * join([\"a\", \"b\", \"c\"], \",\") // returns \"a,b,c\"\n * join([\"apples\", \"bananas\"], \" and \") // returns \"apples and bananas\"\n * join([1, 2, 3, null()], \"|\") // returns \"1|2|3|null\"\n */\n join: {\n _func: resolvedArgs => {\n const listJoin = resolvedArgs[0];\n const joinChar = resolvedArgs[1];\n return listJoin.map(a => toJSON(a)).join(joinChar);\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n { types: [TYPE_STRING] },\n ],\n },\n\n /**\n * Generates an array of the keys of the input object. If the\n * object is null, the value return an empty array\n * @param {object} obj the object to examine\n * @return {array} the array of all the key names\n * @function keys\n * @example\n * keys({a : 3, b : 4}) // returns [\"a\", \"b\"]\n */\n keys: {\n _func: resolvedArgs => Object.keys(resolvedArgs[0]),\n _signature: [{ types: [TYPE_OBJECT] }],\n },\n /**\n * Return a substring from the start of a string or the left-most elements of an array\n * @param {string|array} subject The source text/array of code points/elements\n * @param {integer} [elements=1] number of elements to pick\n * @return {string|array}\n * @function left\n * @example\n * left(\"Sale Price\", 4) // returns \"Sale\"\n * left(\"Sweden\") // returns \"S\"\n * left([4, 5, 6], 2) // returns [4, 5]\n */\n left: {\n _func: args => {\n const numEntries = args.length > 1 ? toInteger(args[1]) : 1;\n if (numEntries < 0) throw evaluationError('left() requires a non-negative number of elements');\n if (isArrayType(args[0])) return args[0].slice(0, numEntries);\n const text = Array.from(toString(args[0]));\n return text.slice(0, numEntries).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the length of the input argument based on types:\n *\n * * string: returns the number of unicode code points\n * * array: returns the number of array elements\n * * object: returns the number of key-value pairs\n * @param {string | array | object} subject subject whose length to calculate\n * @return {integer} the length of the input subject\n * @function length\n * @example\n * length(`[]`) // returns 0\n * length(\"\") // returns 0\n * length(\"abcd\") // returns 4\n * length([1, 2, 3, 4]) // returns 4\n * length(`{}`) // returns 0\n * length({a : 3, b : 4}) // returns 2\n */\n length: {\n _func: resolvedArgs => {\n const arg = valueOf(resolvedArgs[0]);\n if (isObject(arg)) return Object.keys(arg).length;\n // Array.from splits a string into code points\n // If we didn't do this, then String.length would return the number of UTF-16 code units\n return isArrayType(arg) ? arg.length : Array.from(toString(arg)).length;\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT] }],\n },\n\n /**\n * Compute the natural logarithm (base e) of a number\n * @param {number|number[]} num A number greater than zero\n * @return {number|number[]} The natural log value\n * @function log\n * @example\n * log(10) // 2.302585092994046\n */\n log: {\n _func: args => evaluate(args, a => validNumber(Math.log(a), 'log')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Compute the base 10 logarithm of a number.\n * @param {number|number[]} num A number greater than or equal to zero\n * @return {number|number[]} The base 10 log result\n * @function log10\n * @example\n * log10(100000) // 5\n */\n log10: {\n _func: args => evaluate(args, a => validNumber(Math.log10(a), 'log10')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Converts all the alphabetic code points in a string to lowercase.\n * @param {string|string[]} input input string\n * @returns {string|string[]} the lower case value of the input string\n * @function lower\n * @example\n * lower(\"E. E. Cummings\") // returns \"e. e. cummings\"\n */\n lower: {\n _func: args => evaluate(args, a => toString(a).toLowerCase()),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Apply an expression to every element in an array and return the array of results.\n * An input array of length N will return an array of length N.\n * @param {array} elements array of elements to process\n * @param {expression} expr expression to evaluate\n * @return {array} the mapped array\n * @function map\n * @example\n * map([1, 2, 3, 4], &(@ + 1)) // returns [2, 3, 4, 5]\n * map([\"doe\", \"nick\", \"chris\"], &length(@)) // returns [3, 4, 5]\n */\n map: {\n _func: resolvedArgs => {\n const exprefNode = resolvedArgs[1];\n return resolvedArgs[0].map(arg => runtime.interpreter.visit(exprefNode, arg));\n },\n _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }],\n },\n\n /**\n * Calculates the largest value in the input numbers.\n * Any values that are not numbers (null, boolean, strings, objects) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(array|any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function max\n * @example\n * max([1, 2, 3], [4, 5, 6]) // returns 6\n * max([\\\"a\\\", \\\"a1\\\", \\\"b\\\"], null(), true())) // returns 0\n * max(8, 10, 12, \"14\") // returns 12\n */\n max: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => typeof valueOf(a) === 'number');\n\n if (array.length === 0) return 0;\n\n return Math.max(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Calculates the largest value in the input values, coercing parameters to numbers.\n * Null values are ignored.\n * If any parameters cannot be converted to a number,\n * the function will fail with a type error.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function maxA\n * @example\n * maxA([1, 2, 3], [4, 5, 6]) // returns 6\n * maxA([\"a\", \"a1\", \"b\", null()]) // error\n * maxA(8, 10, 12, \"14\") // returns 14\n */\n maxA: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => valueOf(a) !== null)\n .map(toNumber);\n\n if (array.find(a => a === null)) {\n throw evaluationError('maxA() received non-numeric parameters');\n }\n if (array.length === 0) return 0;\n\n return Math.max(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Accepts one or more objects, and returns a single object with\n * all objects merged.\n * The first object is copied, and then\n * and each key value pair from each subsequent object\n * are added to the first object. Duplicate keys in subsequent objects will\n * override those found in earlier objects.\n * @param {...object} args\n * @return {object} The combined object\n * @function merge\n * @example\n * merge({a: 1, b: 2}, {c : 3, d: 4}) // returns {a :1, b: 2, c: 3, d: 4}\n * merge({a: 1, b: 2}, {a : 3, d: 4}) // returns {a :3, b: 2, d: 4}\n */\n merge: {\n _func: resolvedArgs => {\n const merged = {};\n resolvedArgs.forEach(current => {\n if (current === null) return;\n Object.entries(current || {}).forEach(([key, value]) => {\n merged[key] = value;\n });\n });\n return merged;\n },\n _signature: [{ types: [TYPE_OBJECT, TYPE_NULL], variadic: true }],\n },\n\n /**\n * Extracts a substring from text, or a subset from an array.\n * @param {string|array} subject the text string or array of elements from which to extract.\n * @param {integer} startPos the zero-based position of the first code point\n * or element to extract.\n * @param {integer} length The number of code points or elements to return from the\n * string or array.\n * If greater then the length of `subject` the length of the subject is used.\n * @return {string|array} The resulting substring or array subset of elements\n * @function mid\n * @example\n * mid(\"Fluid Flow\", 0, 5) // returns \"Fluid\"\n * mid(\"Fluid Flow\", 6, 20) // returns \"Flow\"\n * mid(\"Fluid Flow\", 20, 5) // returns \"\"\n * mid([0,1,2,3,4,5,6,7,8,9], 2, 3) // returns [2,3,4]\n */\n mid: {\n _func: args => {\n const startPos = toInteger(args[1]);\n const numEntries = toInteger(args[2]);\n if (startPos < 0) throw evaluationError('mid() requires a non-negative start position');\n if (numEntries < 0) throw evaluationError('mid() requires a non-negative length parameter');\n if (isArrayType(args[0])) {\n return args[0].slice(startPos, startPos + numEntries);\n }\n const text = Array.from(toString(args[0]));\n return text.slice(startPos, startPos + numEntries).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n ],\n },\n\n /**\n * Extract the milliseconds of the time value in a <<_date_and_time_values, date/time value>>.\n * @param {number|number[]} date datetime/time for which the millisecond is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The number of milliseconds: 0 through 999\n * @function millisecond\n * @example\n * millisecond(datetime(2008, 5, 23, 12, 10, 53, 42)) // returns 42\n */\n millisecond: {\n _func: args => evaluate(args, a => getDateObj(a).getMilliseconds()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Calculates the smallest value in the input numbers.\n * Any values that are not numbers (null, boolean, string, object) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any[]|any)} collection\n * Values/arrays to search for the minimum value\n * @return {number} the smallest value found\n * @function min\n * @example\n * min([1, 2, 3], [4, 5, 6]) // returns 1\n * min(\"4\", 8, 10, 12, null()) // returns 8\n */\n min: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => typeof valueOf(a) === 'number');\n if (array.length === 0) return 0;\n\n return Math.min(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Calculates the smallest value in the input values, coercing parameters to numbers.\n * Null values are ignored.\n * If any parameters cannot be converted to a number,\n * the function will fail with a type error.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any[]|any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function minA\n * @example\n * minA([1, 2, 3], [4, 5, 6]) // returns 1\n * minA(\"4\", 8, 10, 12, null()) // returns 4\n */\n minA: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => valueOf(a) !== null)\n .map(toNumber);\n\n if (array.find(a => a === null)) {\n throw evaluationError('minA() received non-numeric parameters');\n }\n if (array.length === 0) return 0;\n\n return Math.min(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Extract the minute (0 through 59) from a <<_date_and_time_values, date/time value>>\n * @param {number|number[]} date A datetime/time value.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} Number of minutes in the time portion of the date/time value\n * @function minute\n * @example\n * minute(datetime(2008,5,23,12, 10, 0)) // returns 10\n * minute(time(12, 10, 0)) // returns 10\n */\n minute: {\n _func: args => evaluate(args, a => getDateObj(a).getMinutes()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Return the remainder when one number is divided by another number.\n * @param {number|number[]} dividend The number for which to find the remainder.\n * @param {number|number[]} divisor The number by which to divide number.\n * @return {number|number[]} Computes the remainder of `dividend`/`divisor`.\n * If `dividend` is negative, the result will also be negative.\n * If `dividend` is zero, an error is thrown.\n * @function mod\n * @example\n * mod(3, 2) // returns 1\n * mod(-3, 2) // returns -1\n */\n mod: {\n _func: args => evaluate(args, (a, b) => {\n const result = a % b;\n if (Number.isNaN(result)) throw evaluationError(`Bad parameter for mod: '${a} % ${b}'`);\n return result;\n }),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds the month of a date.\n * @param {number|number[]} date source <<_date_and_time_values, date/time value>>.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The month number value, ranging from 1 (January) to 12 (December)\n * @function month\n * @example\n * month(datetime(2008,5,23)) // returns 5\n */\n month: {\n // javascript months start from 0\n _func: args => evaluate(args, a => getDateObj(a).getMonth() + 1),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Compute logical NOT of a value. If the parameter is not boolean\n * it will be <<_type_coercion_rules,cast to boolean>>\n * Note the related <<_not_operator, unary NOT operator>>.\n * @param {any} value - any data type\n * @returns {boolean} The logical NOT applied to the input parameter\n * @example\n * not(length(\"bar\") > 0) // returns false\n * not(false()) // returns true\n * not(\"abcd\") // returns false\n * not(\"\") // returns true\n * @function not\n */\n not: {\n _func: resolveArgs => !toBoolean(valueOf(resolveArgs[0])),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Finds the first argument that does not resolve to `null`.\n * This function accepts one or more arguments, and will evaluate\n * them in order until a non-null argument is encountered. If all\n * arguments values resolve to null, then return a null value.\n * @param {...any} argument\n * @return {any}\n * @function notNull\n * @example\n * notNull(1, 2, 3, 4, `null`) // returns 1\n * notNull(`null`, 2, 3, 4, `null`) // returns 2\n */\n notNull: {\n _func: resolvedArgs => {\n const result = resolvedArgs.find(arg => getType(arg) !== TYPE_NULL);\n return result === undefined ? null : result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n /**\n * Retrieve the current date/time.\n * @return {number} representation of the <<_date_and_time_values, current date/time value>>.\n * @function now\n */\n now: {\n _func: () => getDateNum(Date.now()),\n _signature: [],\n },\n\n /**\n * Return constant null value.\n * Expressions may also use the JSON literal: `` `null` ``\n * @returns {boolean} True\n * @function null\n */\n null: {\n _func: () => null,\n _signature: [],\n },\n\n /**\n * Determines the logical OR result of a set of parameters.\n * If the parameters are not boolean they will be <<_type_coercion_rules,cast to\n * boolean>>.\n * Note the related <<_or_operator, Or Operator>>.\n * @param {any} first logical expression\n * @param {...any} [operand] any number of additional expressions\n * @returns {boolean} The logical result of applying OR to all parameters\n * @example\n * or((x / 2) == y, (y * 2) == x) // true\n * @function or\n */\n or: {\n _func: resolvedArgs => {\n let result = toBoolean(valueOf(resolvedArgs[0]));\n resolvedArgs.slice(1).forEach(arg => {\n result = result || toBoolean(valueOf(arg));\n });\n return result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n\n /**\n * Computes `a` raised to a power `x`. (a^x)\n * @param {number|number[]} a The base number -- can be any real number.\n * @param {number|number[]} x The exponent to which the base number is raised.\n * @return {number|number[]}\n * @function power\n * @example\n * power(10, 2) // returns 100 (10 raised to power 2)\n */\n power: {\n _func: args => evaluate(args, (a, b) => validNumber(a ** b, 'power')),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Apply proper casing to a string. Proper casing is where the first letter of each\n * word is converted to an\n * uppercase letter and the rest of the letters in the word converted to lowercase.\n * Words are demarcated by whitespace, punctuation, or numbers.\n * Specifically, any character(s) matching the regular expression: `[\\s\\d\\p{P}]+`.\n * @param {string|string[]} text source string\n * @returns {string|string[]} source string with proper casing applied.\n * @function proper\n * @example\n * proper(\"this is a TITLE\") // returns \"This Is A Title\"\n * proper(\"2-way street\") // returns \"2-Way Street\"\n * proper(\"76BudGet\") // returns \"76Budget\"\n */\n proper: {\n _func: args => evaluate(args, properFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Generate a pseudo random number.\n * @returns {number} A value greater than or equal to zero, and less than one.\n * @function random\n * @example\n * random() // 0.022585461160693265\n */\n random: {\n _func: () => Math.random(),\n _signature: [],\n },\n /**\n * Executes a user-supplied reducer expression on each element of an\n * array, in order, passing in the return value from the expression from the preceding element.\n * The final result of running the reducer across all elements of the input array is a\n * single value.\n * The expression can access the following properties of the current object:\n *\n * * accumulated: accumulated value based on the previous expression.\n * For the first array element use the `initialValue` parameter. If not provided, then `null`\n * * current: current element to process\n * * index: index of the current element in the array\n * * array: original array\n * @param {array} elements array of elements on which the expression will be evaluated\n * @param {expression} expr reducer expression to be executed on each element\n * @param {any} initialValue the accumulated value to pass to the first array element\n * @return {any}\n * @function reduce\n * @example\n * reduce([1, 2, 3], &(accumulated + current)) // returns 6\n * // find maximum entry by age\n * reduce(\n * [{age: 10, name: \"Joe\"},{age: 20, name: \"John\"}],\n * &max(@.accumulated.age, @.current.age), @[0].age)\n * reduce([3, 3, 3], &accumulated * current, 1) // returns 27\n */\n reduce: {\n _func: resolvedArgs => {\n const exprefNode = resolvedArgs[1];\n return resolvedArgs[0].reduce(\n (accumulated, current, index, array) => runtime.interpreter.visit(exprefNode, {\n accumulated, current, index, array,\n }),\n resolvedArgs.length === 3 ? resolvedArgs[2] : null,\n );\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n { types: [TYPE_EXPREF] },\n { types: [TYPE_ANY], optional: true },\n ],\n },\n\n /**\n * Register a function. The registered function may take one parameter.\n * If more parameters are needed, combine them in an array or object.\n * A function may not be re-registered with a different definition.\n * Note that implementations are not required to provide `register()` in order to be conformant.\n * Built-in functions may not be overridden.\n * @param {string} functionName Name of the function to register.\n * `functionName` must begin with an underscore or uppercase letter and follow the regular\n * expression pattern:\n * `{caret}{startsb}_A-Z{endsb}{startsb}_a-zA-Z0-9${endsb}{asterisk}$`\n * @param {expression} expr Expression to execute with this function call\n * @return {{}} returns an empty object\n * @function register\n * @example\n * register(\"_product\", &@[0] * @[1]) // can now call: _product([2,21]) => returns 42\n * register(\"_ltrim\", &split(@,\"\").reduce(@, &accumulated & current | if(@ = \" \", \"\", @), \"\"))\n * // _ltrim(\" abc \") => returns \"abc \"\n */\n register: {\n _func: resolvedArgs => {\n const functionName = resolvedArgs[0];\n const exprefNode = resolvedArgs[1];\n\n if (!/^[_A-Z][_a-zA-Z0-9$]*$/.test(functionName)) throw functionError(`Invalid function name: \"${functionName}\"`);\n if (functionMap[functionName]\n && functionMap[functionName]._exprefNode.value !== exprefNode.value) {\n // custom functions can be re-registered as long as the expression is the same\n throw functionError(`Cannot override function: \"${functionName}\" with a different definition`);\n }\n functionMap[functionName] = {\n _func: args => runtime.interpreter.visit(exprefNode, ...args),\n _signature: [{ types: [TYPE_ANY], optional: true }],\n _exprefNode: exprefNode,\n };\n return {};\n },\n _signature: [\n { types: [TYPE_STRING] },\n { types: [TYPE_EXPREF] },\n ],\n },\n\n /**\n * Register a function that accepts multiple parameters.\n * A function may not be re-registered with a different definition.\n * Note that implementations are not required to provide `registerWithParams()`\n * in order to be conformant.\n * Built-in functions may not be overridden.\n * @param {string} functionName Name of the function to register.\n * `functionName` must begin with an underscore or uppercase letter and follow the regular\n * expression pattern:\n * `{caret}{startsb}_A-Z{endsb}{startsb}_a-zA-Z0-9${endsb}{asterisk}$`\n * @param {expression} expr Expression to execute with this function call.\n * Parameters are passed as an array.\n * @return {{}} returns an empty object\n * @function registerWithParams\n * @example\n * registerWithParams(\"Product\", &@[0] * @[1])\n * // can now call: Product(2,21) => returns 42\n * registerWithParams(\n * \"Ltrim\",\n * &split(@[0],\"\").reduce(@, &accumulated & current | if(@ = \" \", \"\", @), \"\")\n * )\n * // Ltrim(\" abc \") => returns \"abc \"\n */\n registerWithParams: {\n _func: resolvedArgs => {\n const functionName = resolvedArgs[0];\n const exprefNode = resolvedArgs[1];\n\n if (!/^[_A-Z][_a-zA-Z0-9$]*$/.test(functionName)) throw functionError(`Invalid function name: \"${functionName}\"`);\n if (functionMap[functionName]\n && functionMap[functionName]._exprefNode.value !== exprefNode.value) {\n // custom functions can be re-registered as long as the expression is the same\n throw functionError(`Cannot override function: \"${functionName}\" with a different definition`);\n }\n functionMap[functionName] = {\n _func: args => runtime.interpreter.visit(exprefNode, args),\n _signature: [{ types: [TYPE_ANY], optional: true, variadic: true }],\n _exprefNode: exprefNode,\n };\n return {};\n },\n _signature: [\n { types: [TYPE_STRING] },\n { types: [TYPE_EXPREF] },\n ],\n },\n\n /**\n * Generates text (or an array) where we substitute elements at a given start position and\n * length, with new text (or array elements).\n * @param {string|array} subject original text or array\n * @param {integer} start zero-based index in the original text\n * from where to begin the replacement. Must be greater than or equal to 0.\n * @param {integer} length number of code points to be replaced.\n * If `start` + `length` is greater than the length of `subject`,\n * all text past `start` will be replaced.\n * @param {any} replacement Replacement to insert at the start index.\n * If `subject` is an array, and `replacement` is an array, the `replacement` array\n * elements will be inserted into the `subject` array.\n * If `subject` is an array and replacement is not an array, the `replacement` will be\n * inserted as a single element in `subject`\n * If `subject` is a string, the `replacement` will be coerced to a string.\n * @returns {string|array} the resulting text or array\n * @function replace\n * @example\n * replace(\"abcdefghijk\", 5, 5, \"*\") // returns abcde*k\n * replace(\"2009\",2,2,\"10\") // returns 2010\n * replace(\"123456\",0,3,\"@\") // returns @456\n * replace([\"blue\",\"black\",\"white\",\"red\"], 1, 2, [\"green\"]) // returns [\"blue\",\"green\",\"red\"]\n */\n replace: {\n _func: args => {\n const startPos = toInteger(args[1]);\n const numElements = toInteger(args[2]);\n if (startPos < 0) throw evaluationError('replace() start position must be greater than or equal to 0');\n if (numElements < 0) throw evaluationError('replace() length must be greater than or equal to 0');\n if (isArrayType(args[0])) {\n const sourceArray = valueOf(args[0]);\n let replacement = valueOf(args[3]);\n if (!isArrayType(replacement)) replacement = [replacement];\n sourceArray.splice(startPos, numElements, ...replacement);\n return sourceArray;\n }\n const subject = Array.from(toString(args[0]));\n if (isArrayType(args[3]) || getType(args[3]) === TYPE_OBJECT) throw typeError('replace() replacement must not be an array or object');\n const newText = toString(args[3]);\n\n subject.splice(startPos, numElements, newText);\n return subject.join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_ANY] },\n ],\n },\n\n /**\n * Return text repeated `count` times.\n * @param {string|string[]} text text to repeat\n * @param {integer|integer[]} count number of times to repeat the text.\n * Must be greater than or equal to 0.\n * @returns {string|string[]} Text generated from the repeated text.\n * if `count` is zero, returns an empty string.\n * @function rept\n * @example\n * rept(\"x\", 5) // returns \"xxxxx\"\n */\n rept: {\n _func: args => evaluate(args, reptFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Reverses the order of an array or the order of code points in a string\n * @param {string|array} subject the source to be reversed\n * @return {array} The resulting reversed array or string\n * @function reverse\n * @example\n * reverse([\"a\", \"b\", \"c\"]) // returns [\"c\", \"b\", \"a\"]\n */\n reverse: {\n _func: resolvedArgs => {\n const originalStr = valueOf(resolvedArgs[0]);\n const typeName = getType(originalStr);\n if (typeName === TYPE_STRING) {\n return Array.from(originalStr).reverse().join('');\n }\n const reversedArray = resolvedArgs[0].slice(0);\n return reversedArray.reverse();\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] }],\n },\n\n /**\n * Generates a string from the right-most code points of a string or\n * a subset of elements from the end of an array\n * @param {string|array} subject The text/array containing the code points/elements to extract\n * @param {integer} [elements=1] number of elements to pick\n * @return {string|array} The extracted substring or array subset\n * Returns null if the number of elements is less than 0\n * @function right\n * @example\n * right(\"Sale Price\", 4) // returns \"rice\"\n * right(\"Sweden\") // returns \"n\"\n * right([4, 5, 6], 2) // returns [5, 6]\n */\n right: {\n _func: args => {\n const numEntries = args.length > 1 ? toInteger(args[1]) : 1;\n if (numEntries < 0) throw evaluationError('right() count must be greater than or equal to 0');\n if (args[0] instanceof Array) {\n if (numEntries === 0) return [];\n return args[0].slice(numEntries * -1);\n }\n if (numEntries === 0) return '';\n const text = Array.from(toString(args[0]));\n return text.slice(numEntries * -1).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Round a number to a specified precision:\n *\n * * If `precision` is greater than zero, round to the specified number of decimal places.\n * * If `precision` is 0, round to the nearest integer.\n * * If `precision` is less than 0, round to the left of the decimal point.\n * @param {number|number[]} num number to round\n * @param {integer|integer[]} [precision=0] precision to use for the rounding operation.\n * @returns {number|number[]} rounded value. Rounding a half value will round up.\n * @function round\n * @example\n * round(2.15, 1) // returns 2.2\n * round(626.3,-3) // returns 1000 (Rounds 626.3 to the nearest multiple of 1000)\n * round(626.3, 0) // returns 626\n * round(1.98,-1) // returns 0 (Rounds 1.98 to the nearest multiple of 10)\n * round(-50.55,-2) // -100 (round -50.55 to the nearest multiple of 100)\n * round(1.95583) // 2\n * round(-1.5) // -1\n */\n round: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2)args.push(0);\n return evaluate(args, (a, n) => {\n const digits = toInteger(n);\n return round(a, digits);\n });\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Perform a wildcard search. The search is case-sensitive and supports two forms of wildcards:\n * `{asterisk}` finds a sequence of code points and `?` finds a single code point.\n * To use `{asterisk}` or `?` or `{backslash}` as text values,\n * precede them with an escape (`{backslash}`) character.\n * Note that the wildcard search is not greedy.\n * e.g. `search(\"a{asterisk}b\", \"abb\")` will return `[0, \"ab\"]` Not `[0, \"abb\"]`\n * @param {string|string[]} findText the search string -- which may include wild cards.\n * @param {string|string[]} withinText The string to search.\n * @param {integer|integer[]} [startPos=0] The zero-based position of withinText\n * to start searching.\n * A negative value is not allowed.\n * @returns {array} returns an array with two values:\n *\n * * The start position of the found text and the text string that was found.\n * * If a match was not found, an empty array is returned.\n * @function search\n * @example\n * search(\"a?c\", \"acabc\") // returns [2, \"abc\"]\n */\n search: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(0);\n return evaluate(args, searchFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n\n },\n\n /**\n * Extract the seconds of the time value in a <<_date_and_time_values, date/time value>>.\n * @param {number|number[]} date datetime/time for which the second is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The number of seconds: 0 through 59\n * @function second\n * @example\n * second(datetime(2008,5,23,12, 10, 53)) // returns 53\n * second(time(12, 10, 53)) // returns 53\n */\n second: {\n _func: args => evaluate(args, a => getDateObj(a).getSeconds()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Computes the sign of a number passed as argument.\n * @param {number|number[]} num any number\n * @return {number|number[]} returns 1 or -1, indicating the sign of `num`.\n * If the `num` is 0, it will return 0.\n * @function sign\n * @example\n * sign(5) // 1\n * sign(-5) // -1\n * sign(0) // 0\n */\n sign: {\n _func: args => evaluate(args, Math.sign),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Computes the sine of a number in radians\n * @param {number|number[]} angle A number representing an angle in radians.\n * @return {number|number[]} The sine of `angle`, between -1 and 1, inclusive\n * @function sin\n * @example\n * sin(0) // 0\n * sin(1) // 0.8414709848078965\n */\n sin: {\n _func: args => evaluate(args, Math.sin),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * This function accepts an array values and returns an\n * array with the elements in sorted order.\n * If there are mixed data types, the values will be grouped in order:\n * numbers, strings, booleans, nulls\n * String sorting is based on code points and is not locale-sensitive.\n * If the sort encounters any objects or arrays, it will throw an evaluation error.\n * @param {any[]} list to be sorted\n * @return {any[]} The ordered result\n * @function sort\n * @example\n * sort([1, 2, 4, 3, 1]) // returns [1, 1, 2, 3, 4]\n * sort([\"20\", 20, true(), \"100\", null(), 100]) // returns [20, 100, \"100\", \"20\", true, null]\n */\n sort: {\n _func: resolvedArgs => {\n /*\n numbers sort first\n strings sort second\n Booleans sort third\n nulls sort last\n */\n const typeVals = resolvedArgs[0].map(value => {\n const type = getType(value);\n if (![TYPE_NUMBER, TYPE_STRING, TYPE_BOOLEAN, TYPE_NULL].includes(type)) {\n throw evaluationError('Bad datatype for sort');\n }\n return { type, value };\n });\n\n const sortFunction = (a, b) => {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n };\n\n const sorted = typeVals\n .filter(v => v.type === TYPE_NUMBER)\n .map(v => v.value)\n .sort(sortFunction);\n\n sorted.push(\n ...typeVals\n .filter(v => v.type === TYPE_STRING)\n .map(v => v.value)\n .sort(),\n );\n\n sorted.push(...typeVals.filter(v => v.type === TYPE_BOOLEAN).map(v => v.value));\n sorted.push(...typeVals.filter(v => v.type === TYPE_NULL).map(v => v.value));\n return sorted;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Sort an array using an expression to find the sort key. For each element\n * in the array, the expression is applied and the resulting\n * value is used as the sort value. If the result of\n * evaluating the expression against the current array element results in type\n * other than a number or a string, a <<_errors, TypeError>> will occur.\n * @param {array} elements Array to be sorted\n * @param {expression} expr The comparison expression\n * @return {array} The sorted array\n * @function sortBy\n * @example\n * // returns [\"e\", \"def\", \"abcd\"]\n * sortBy([\"abcd\", \"e\", \"def\"], &length(@))\n *\n * // returns [{year: 1910}, {year: 2010}, {year: 2020}]\n * sortBy([{year: 2010}, {year: 2020}, {year: 1910}], &year)\n *\n * // returns [5, -10, -11, -15, 30]\n * sortBy([-15, 30, -10, -11, 5], &abs(@))\n */\n sortBy: {\n _func: resolvedArgs => {\n const sortedArray = resolvedArgs[0].slice(0);\n if (sortedArray.length === 0) {\n return sortedArray;\n }\n const exprefNode = resolvedArgs[1];\n const requiredType = getType(\n runtime.interpreter.visit(exprefNode, sortedArray[0]),\n );\n if (![TYPE_NUMBER, TYPE_STRING].includes(requiredType)) {\n throw typeError('Bad data type for sortBy()');\n }\n // In order to get a stable sort out of an unstable\n // sort algorithm, we decorate/sort/undecorate (DSU)\n // by creating a new list of [index, element] pairs.\n // In the cmp function, if the evaluated elements are\n // equal, then the index will be used as the tiebreaker.\n // After the decorated list has been sorted, it will be\n // undecorated to extract the original elements.\n const decorated = [];\n for (let i = 0; i < sortedArray.length; i += 1) {\n decorated.push([i, sortedArray[i]]);\n }\n decorated.sort((a, b) => {\n const exprA = runtime.interpreter.visit(exprefNode, a[1]);\n const typeA = getType(exprA);\n const exprB = runtime.interpreter.visit(exprefNode, b[1]);\n const typeB = getType(exprB);\n if (typeA !== requiredType) {\n throw typeError(`sortBy expected ${typeNameTable[requiredType]}, received ${typeNameTable[typeA]}`);\n } else if (typeB !== requiredType) {\n throw typeError(`sortyBy expected ${typeNameTable[requiredType]}, received ${typeNameTable[typeB]}`);\n }\n if (exprA > exprB) return 1;\n if (exprA < exprB) return -1;\n // If they\"re equal compare the items by their\n // order to maintain relative order of equal keys\n // (i.e. to get a stable sort).\n return a[0] - b[0];\n });\n // Undecorate: extract out the original list elements.\n for (let j = 0; j < decorated.length; j += 1) {\n [, sortedArray[j]] = decorated[j];\n }\n return sortedArray;\n },\n _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }],\n },\n\n /**\n * Split a string into an array, given a separator\n * @param {string|string[]} string string to split\n * @param {string|string[]} separator separator where the split(s) should occur\n * @return {string[]|string[][]} The array of separated strings\n * @function split\n * @example\n * split(\"abcdef\", \"\") // returns [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n * split(\"abcdef\", \"e\") // returns [\"abcd\", \"f\"]\n */\n split: {\n _func: args => evaluate(args, splitFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Find the square root of a number\n * @param {number|number[]} num source number\n * @return {number|number[]} The calculated square root value\n * @function sqrt\n * @example\n * sqrt(4) // returns 2\n */\n sqrt: {\n _func: args => evaluate(args, arg => validNumber(Math.sqrt(arg), 'sqrt')),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Determine if a string starts with a prefix.\n * @param {string|string[]} subject string to search\n * @param {string|string[]} prefix prefix to search for\n * @return {boolean|boolean[]} true if `prefix` matches the start of `subject`\n * @function startsWith\n * @example\n * startsWith(\"jack is at home\", \"jack\") // returns true\n */\n startsWith: {\n _func: args => evaluate(args, startsWithFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n /**\n * Estimates standard deviation based on a sample.\n * `stdev` assumes that its arguments are a sample of the entire population.\n * If your data represents a entire population,\n * then compute the standard deviation using [stdevp]{@link stdevp}.\n * Non-numeric values (text, boolean, null etc) are ignored.\n * If there are nested arrays, they are flattened.\n * @param {any[]} values The array containing numbers comprising the population.\n * Array size must be greater than 1.\n * @returns {number} [Standard deviation](https://en.wikipedia.org/wiki/Standard_deviation)\n * @function stdev\n * @example\n * stdev([1345, 1301, 1368]) // returns 34.044089061098404\n * stdevp([1345, 1301, 1368]) // returns 27.797\n */\n stdev: {\n _func: args => {\n const values = args.flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (values.length <= 1) throw evaluationError('stdev() must have at least two values');\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const sumSquare = values.reduce((a, b) => a + b * b, 0);\n const result = Math.sqrt((sumSquare - values.length * mean * mean) / (values.length - 1));\n return validNumber(result, 'stdev');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Estimates standard deviation based on a sample.\n * `stdev` assumes that its arguments are a sample of the entire population.\n * If your data represents a entire population,\n * then compute the standard deviation using [stdevpA]{@link stdevpA}.\n * Nested arrays are flattened.\n * Null values are ignored. All other parameters are converted to number.\n * If conversion to number fails, a type error is thrown.\n * @param {number[]} numbers The array of numbers comprising the population.\n * Array size must be greater than 1.\n * @returns {number} [Standard deviation](https://en.wikipedia.org/wiki/Standard_deviation)\n * @function stdevA\n * @example\n * stdevA([1345, \"1301\", 1368]) // returns 34.044089061098404\n * stdevpA([1345, 1301, \"1368\"]) // returns 27.797\n */\n stdevA: {\n _func: args => {\n let values;\n try {\n values = args.flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n } catch (_e) {\n throw evaluationError('stdevA() received non-numeric parameters');\n }\n\n if (values.length <= 1) throw evaluationError('stdevA() must have at least two values');\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const sumSquare = values.reduce((a, b) => a + b * b, 0);\n const result = Math.sqrt((sumSquare - values.length * mean * mean) / (values.length - 1));\n return validNumber(result, 'stdevA');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Calculates standard deviation based on the entire population given as arguments.\n * `stdevp` assumes that its arguments are the entire population.\n * If your data represents a sample of the population,\n * then compute the standard deviation using [stdev]{@link stdev}.\n * Non-numeric values (text, boolean, null etc) are ignored.\n * If there are nested arrays, they are flattened.\n * @param {any[]} values The array containing numbers comprising the population.\n * An empty array is not allowed.\n * @returns {number} Calculated standard deviation\n * @function stdevp\n * @example\n * stdevp([1345, 1301, 1368]) // returns 27.797\n * stdev([1345, 1301, 1368]) // returns 34.044\n */\n stdevp: {\n _func: args => {\n const values = args[0]\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (values.length === 0) throw evaluationError('stdevp() must have at least one value');\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const meanSumSquare = values.reduce((a, b) => a + b * b, 0) / values.length;\n const result = Math.sqrt(meanSumSquare - mean * mean);\n return validNumber(result, 'stdevp');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Calculates standard deviation based on the entire population given as arguments.\n * `stdevpA` assumes that its arguments are the entire population.\n * If your data represents a sample of the population,\n * then compute the standard deviation using [stdevA]{@link stdevA}.\n * Nested arrays are flattened.\n * Null values are ignored. All other parameters are converted to number.\n * If conversion to number fails, a type error is thrown.\n * @param {number[]} numbers The array of numbers comprising the population.\n * An empty array is not allowed.\n * @returns {number} Calculated standard deviation\n * @function stdevp\n * @example\n * stdevpA([1345, \"1301\", 1368]) // returns 27.797\n * stdevA([1345, 1301, \"1368\"]) // returns 34.044\n */\n stdevpA: {\n _func: args => {\n const values = args[0]\n .flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n\n if (values.length === 0) throw evaluationError('stdevp() must have at least one value');\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const meanSumSquare = values.reduce((a, b) => a + b * b, 0) / values.length;\n const result = Math.sqrt(meanSumSquare - mean * mean);\n return validNumber(result, 'stdevp');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Generates a string from the input `text`,\n * with text `old` replaced by text `new` (when searching from the left).\n * If there is no match, or if `old` has length 0, `text` is returned unchanged.\n * Note that `old` and `new` may have different lengths.\n * @param {string|string[]} text The text for which to substitute code points.\n * @param {string|string[]} old The text to replace.\n * @param {string|string[]} new The text to replace `old` with.\n * If `new` is an empty string, then occurrences of `old` are removed from `text`.\n * @param {integer|integer[]} [which]\n * The zero-based occurrence of `old` text to replace with `new` text.\n * If `which` parameter is omitted, every occurrence of `old` is replaced with `new`.\n * @returns {string|string[]} replaced string\n * @function substitute\n * @example\n * substitute(\"Sales Data\", \"Sales\", \"Cost\") // returns \"Cost Data\"\n * substitute(\"Quarter 1, 2001\", \"1\", \"2\", 1)\" // returns \"Quarter 1, 2002\"\n * substitute(\"Quarter 1, 2011\", \"1\", \"2\", 2)\" // returns \"Quarter 1, 2012\"\n */\n substitute: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n let n;\n if (args.length > 3) {\n if (Array.isArray(args[3])) {\n n = args[3].map(toInteger);\n if (n.find(o => o < 0) !== undefined) throw evaluationError('substitute() which parameter must be greater than or equal to 0');\n } else {\n n = toInteger(args[3]);\n if (n < 0) throw evaluationError('substitute() which parameter must be greater than or equal to 0');\n }\n args[3] = n;\n }\n return evaluate(args, substituteFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the sum of the provided array.\n * An empty array will produce a return value of 0.\n * Any values that are not numbers (null, boolean, strings, objects) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * @param {any[]} collection array of values\n * @return {number} The computed sum\n * @function sum\n * @example\n * sum([1, 2, 3]) // returns 6\n */\n sum: {\n _func: resolvedArgs => {\n let sum = 0;\n resolvedArgs[0]\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER)\n .forEach(arg => {\n sum += arg * 1;\n });\n\n return sum;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Computes the tangent of a number in radians\n * @param {number|number[]} angle A number representing an angle in radians.\n * @return {number|number[]} The tangent of `angle`\n * @function tan\n * @example\n * tan(0) // 0\n * tan(1) // 1.5574077246549023\n */\n tan: {\n _func: args => evaluate(args, Math.tan),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Construct and returns a <<_date_and_time_values, time value>>.\n * If any of the units are greater or less than their normal range,\n * the overflow/underflow will be added/subtracted from the next greater unit.\n * @param {integer} hours Zero-based integer value between 0 and 23 representing\n * the hour of the day.\n * @param {integer} [minutes=0] Zero-based integer value representing\n * the minute segment of a time.\n * @param {integer} [seconds=0] Zero-based integer value representing the seconds\n * segment of a time.\n * @return {number} Returns a date/time value representing the fraction\n * of the day consumed by the given time\n * @function time\n * @example\n * time(12, 0, 0) | [hour(@), minute(@), second(@)] // returns [12, 0, 0]\n */\n time: {\n _func: args => {\n const hours = toInteger(args[0]);\n const minutes = args.length > 1 ? toInteger(args[1]) : 0;\n const seconds = args.length > 2 ? toInteger(args[2]) : 0;\n // Since time values are interchangeable with date and datetime values, it\"s consistent\n // to create them at the epoch\n const epochTime = new Date(1970, 0, 1, hours, minutes, seconds);\n return getDateNum(epochTime);\n },\n _signature: [\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Converts the provided argument to an array.\n * The conversion happens as per the following rules:\n *\n * * array - Returns the provided value.\n * * number/string/object/boolean/null - Returns a one element array containing the argument.\n * @param {any} arg parameter to turn into an array\n * @return {array} The resulting array\n * @function toArray\n * @example\n * toArray(1) // returns [1]\n * toArray(null()) // returns [`null`]\n */\n toArray: {\n _func: resolvedArgs => (isArrayType(resolvedArgs[0]) ? resolvedArgs[0] : [resolvedArgs[0]]),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Converts the provided string to a date/time value.\n *\n * @param {string} ISOString An [ISO8601 formatted string]{@link https://www.iso.org/iso-8601-date-and-time-format.html}.\n * (limited to the [RFC 3339]{@link https://www.rfc-editor.org/rfc/rfc3339} profile)\n * If the string does not include a timezone offset (or trailing 'Z'),\n * it will be assumed to be local time\n * @return {number} The resulting <<_date_and_time_values, date/time number>>.\n * If conversion fails, return null.\n * @function toDate\n * @example\n * toDate(\"20231110T130000+04:00\") // returns 19671.375\n * toDate(\"2023-11-10T13:00:00+04:00\") // returns 19671.375\n * toDate(\"20231110\") | year(@) & \"/\" & month(@) // returns \"2023/11\"\n */\n toDate: {\n _func: resolvedArgs => {\n // expand compact notation so that the Date() constructor will\n // accept the value\n const iso = toString(resolvedArgs[0])\n .replace(/(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)/, '$1-$2-$3')\n .replace(/T(\\d\\d)(\\d\\d)(\\d\\d)/, 'T$1:$2:$3');\n const dateparts = iso.split(/[\\D,zZ]+/);\n let d;\n if (dateparts.length <= 3) {\n if (dateparts.length < 3 || dateparts.find(x => x === '') === '') {\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n return null;\n }\n }\n if (dateparts.length < 7) {\n // no timezone component, so assume local time\n // The date constructor always parses an ISO string as\n // UTC -- with or without a trailing 'z'\n // But if there's no timezone component, it needs to be local time\n\n const range = [99999, 12, 31, 23, 59, 59, 999];\n // check that the date parts are in range\n for (let i = 0; i < dateparts.length; i += 1) {\n if (dateparts[i] > range[i]) {\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n return null;\n }\n }\n // account for zero-based date month parts\n d = new Date(...dateparts.map((x, i) => (i === 1 ? x - 1 : x * 1)));\n } else {\n d = new Date(iso);\n }\n if (d instanceof Date && Number.isFinite(d.getTime())) return getDateNum(d);\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n\n return null;\n },\n _signature: [{ types: [TYPE_STRING] }],\n },\n\n /**\n * Returns a <<_date_and_time_values, date/time>> value representing\n * the start of the current day. i.e. midnight\n * @return {number} today at midnight\n * @function today\n */\n today: {\n _func: () => {\n const now = new Date(Date.now());\n // We used to take the floor() to truncate h/m/s from Date.now(), but that would return\n // today at UTC time. We want today in local time.\n // i.e. UTC time could be a day ahead or behind\n // But note that means that the result is not an integer.\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n return getDateNum(today);\n },\n _signature: [],\n },\n\n /**\n * Converts the provided arg to a number.\n * The conversions follow the <<_type_coercion_rules,type coercion rules>> but will also:\n * * Convert non-numeric strings to zero\n * * Convert arrays to arrays of numbers\n *\n * @param {any|any[]} value to convert to number\n * @param {integer|integer[]} [base=10] If the input `arg` is a string,\n * the base to use to convert to number.\n * One of: 2, 8, 10, 16. Defaults to 10.\n * @return {number} The resulting number. If conversion to number fails, return null.\n * @function toNumber\n * @example\n * toNumber(1) // returns 1\n * toNumber(\"10\") // returns 10\n * toNumber({a: 1}) // returns null\n * toNumber(true()) // returns 1\n * toNumber(\"10f\") // returns null\n * toNumber(\"FF\", 16) // returns 255\n */\n toNumber: {\n _func: resolvedArgs => {\n const toNumberFn = (value, base) => {\n const num = valueOf(value);\n if (getType(num) === TYPE_STRING && base !== 10) {\n let digitCheck;\n if (base === 2) digitCheck = /^\\s*(\\+|-)?[01.]+\\s*$/;\n else if (base === 8) digitCheck = /^\\s*(\\+|-)?[0-7.]+\\s*$/;\n else if (base === 16) digitCheck = /^\\s*(\\+|-)?[0-9A-Fa-f.]+\\s*$/;\n else throw evaluationError(`Invalid base: \"${base}\" for toNumber()`);\n\n if (num === '') return 0;\n if (!digitCheck.test(num)) {\n debug.push(`Failed to convert \"${num}\" base \"${base}\" to number`);\n return null;\n }\n const parts = num.split('.').map(p => p.trim());\n\n let decimal = 0;\n if (parts.length > 1) {\n decimal = parseInt(parts[1], base) * base ** -parts[1].length;\n }\n\n const result = parseInt(parts[0], base) + decimal;\n if (parts.length > 2 || Number.isNaN(result)) {\n debug.push(`Failed to convert \"${num}\" base \"${base}\" to number`);\n return null;\n }\n return result;\n }\n try {\n return toNumber(num);\n } catch (e) {\n const errorString = arg => {\n const v = toJSON(arg);\n return v.length > 50 ? `${v.substring(0, 20)} ...` : v;\n };\n\n debug.push(`Failed to convert \"${errorString(num)}\" to number`);\n return null;\n }\n };\n let base = 10;\n if (resolvedArgs.length > 1) {\n base = Array.isArray(resolvedArgs[1])\n ? resolvedArgs.map(toInteger)\n : toInteger(resolvedArgs[1]);\n }\n return evaluate([resolvedArgs[0], base], toNumberFn);\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Returns the argument converted to a string.\n * If the argument is a string, it will be returned unchanged.\n * Otherwise, returns the JSON encoded value of the argument.\n * @param {any} arg Value to be converted to a string\n * @param {integer} [indent=0] Indentation to use when converting\n * objects and arrays to a JSON string\n * @return {string} The result string.\n * @function toString\n * @example\n * toString(1) // returns \"1\"\n * toString(true()) // returns \"true\"\n * toString({sum: 12 + 13}) // \"{\"sum\":25}\"\n * toString(\"hello\") // returns \"hello\"\n */\n toString: {\n _func: resolvedArgs => toJSON(resolvedArgs[0], resolvedArgs.length > 1 ? resolvedArgs[1] : 0),\n _signature: [{ types: [TYPE_ANY] }, { types: [TYPE_NUMBER], optional: true }],\n },\n\n /**\n * Remove leading and trailing spaces (U+0020), and replace all internal multiple spaces\n * with a single space. Note that other whitespace characters are left intact.\n * @param {string|string[]} text string to trim\n * @return {string|string[]} trimmed string\n * @function trim\n * @example\n * trim(\" ab c \") // returns \"ab c\"\n */\n trim: {\n _func: args => evaluate(args, s => toString(s).split(' ').filter(x => x).join(' ')),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Return constant boolean true value.\n * Expressions may also use the JSON literal: `` `true` ``\n * @returns {boolean} True\n * @function true\n */\n true: {\n _func: () => true,\n _signature: [],\n },\n\n /**\n * Truncates a number to an integer by removing the fractional part of the number.\n * i.e. it rounds towards zero.\n * @param {number|number[]} numA number to truncate\n * @param {integer|integer[]} [numB=0]\n * A number specifying the number of decimal digits to preserve.\n * @return {number|number[]} Truncated value\n * @function trunc\n * @example\n * trunc(8.9) // returns 8\n * trunc(-8.9) // returns -8\n * trunc(8.912, 2) // returns 8.91\n */\n trunc: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(0);\n return evaluate(args, truncFn);\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the type name of the given `subject` argument as a string value.\n * The return value will be one of the following:\n *\n * * number\n * * string\n * * boolean\n * * array\n * * object\n * * null\n * @param {any} subject type to evaluate\n * @return {string} The type name\n *\n * @function type\n * @example\n * type(1) // returns \"number\"\n * type(\"\") // returns \"string\"\n */\n type: {\n _func: resolvedArgs => ({\n [TYPE_NUMBER]: 'number',\n [TYPE_STRING]: 'string',\n [TYPE_ARRAY]: 'array',\n [TYPE_ARRAY_NUMBER]: 'array',\n [TYPE_ARRAY_STRING]: 'array',\n [TYPE_ARRAY_ARRAY]: 'array',\n [TYPE_OBJECT]: 'object',\n [TYPE_BOOLEAN]: 'boolean',\n [TYPE_EXPREF]: 'expref',\n [TYPE_NULL]: 'null',\n }[getType(resolvedArgs[0])]),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Find the set of unique elements within an array\n * @param {array} input input array\n * @return {array} array with duplicate elements removed\n * @function unique\n * @example\n * unique([1, 2, 3, 4, 1, 1, 2]) // returns [1, 2, 3, 4]\n */\n unique: {\n _func: args => {\n // create an array of values for searching. That way if the array elements are\n // represented by class objects with a valueOf(), we'll locate them in the valueArray\n // but return the original class object.\n const valueArray = args[0].map(a => valueOf(a));\n return args[0]\n .filter(\n (v, index) => valueArray.findIndex(\n lookup => strictDeepEqual(lookup, valueOf(v)),\n ) === index,\n );\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Converts all the alphabetic code points in a string to uppercase.\n * @param {string|string[]} input input string\n * @returns {string|string[]} the upper case value of the input string\n * @function upper\n * @example\n * upper(\"abcd\") // returns \"ABCD\"\n */\n upper: {\n _func: args => evaluate(args, a => toString(a).toUpperCase()),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Perform an indexed lookup on an object or array\n * @param {object | array | null} subject on which to perform the lookup.\n * When querying for <<_hidden_properties,hidden properties>>, `subject` may be any data type.\n * @param {string | integer} index if `subject` is an object, `index` must be a string\n * indicating the key name to search for.\n * If `subject` is an array, then index must be an integer indicating the offset into the array\n * @returns {any} the result of the lookup -- or `null` if not found.\n * @function value\n * @example\n * value({a: 1, b:2, c:3}, \"a\") // returns 1\n * value([1, 2, 3, 4], 2) // returns 3\n */\n value: {\n _func: args => {\n const indexType = getType(args[1]);\n let index = args[1];\n const subjectArray = isArrayType(args[0]);\n // if the object/array has a getter for this property then don't validate types\n // just return the value.\n if (args[0] !== null && Object.getOwnPropertyDescriptor(args[0], index)?.get) {\n return getProperty(args[0], index);\n }\n const obj = valueOf(args[0]);\n if (obj === null) return null;\n if (!(getType(obj) === TYPE_OBJECT || subjectArray)) {\n throw typeError('First parameter to value() must be one of: object, array, null.');\n }\n if (subjectArray) {\n if (indexType !== TYPE_NUMBER) throw typeError('value() requires an integer index for arrays');\n index = toInteger(index);\n } else if (indexType !== TYPE_STRING) {\n throw typeError('value() requires a string index for objects');\n }\n const result = getProperty(args[0], index);\n if (result === undefined) {\n if (subjectArray) {\n debug.push(\n `Index: ${index} out of range for array size: ${obj.length}`,\n );\n } else debugAvailable(debug, obj, index);\n return null;\n }\n return result;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n\n /**\n * Generates an array of the values of the provided object.\n * Note that because JSON objects are\n * inherently unordered, the values associated with the provided object are\n * also unordered.\n * @param {object} obj source object\n * @return {array} array of the values\n * @function values\n * @example\n * values({a : 3, b : 4}) // returns [3, 4]\n */\n values: {\n _func: resolvedArgs => Object.values(resolvedArgs[0]),\n _signature: [{ types: [TYPE_OBJECT] }],\n },\n\n /**\n * Extract the day of the week from a date.\n * The specific numbering of the day of week is controlled by the `returnType` parameter:\n *\n * * 1 : Sunday (1), Monday (2), ..., Saturday (7)\n * * 2 : Monday (1), Tuesday (2), ..., Sunday(7)\n * * 3 : Monday (0), Tuesday (1), ...., Sunday(6)\n * @param {number|number[]} date <<_date_and_time_values, date/time value>> for\n * which the day of the week is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {integer|integer[]} [returnType=1] Determines the\n * representation of the result.\n * An unrecognized returnType will result in a error.\n * @returns {integer|integer[]} day of the week\n * @function weekday\n * @example\n * weekday(datetime(2006,5,21)) // 1\n * weekday(datetime(2006,5,21), 2) // 7\n * weekday(datetime(2006,5,21), 3) // 6\n */\n weekday: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(1);\n return evaluate(args, weekdayFn);\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the year of a datetime value\n * @param {number|number[]} date input <<_date_and_time_values, date/time value>>\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The year value\n * @function year\n * @example\n * year(datetime(2008,5,23)) // returns 2008\n */\n year: {\n _func: args => evaluate(args, a => getDateObj(a).getFullYear()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Generates a convolved (zipped) array containing grouped arrays of values from\n * the array arguments from index 0, 1, 2, etc.\n * This function accepts a variable number of arguments.\n * The length of the returned array is equal to the length of the shortest array.\n * @param {...array} arrays array of arrays to zip together\n * @return {array} An array of arrays with elements zipped together\n * @function zip\n * @example\n * zip([1, 2, 3], [4, 5, 6, 7]) // returns [[1, 4], [2, 5], [3, 6]]\n */\n zip: {\n _func: args => {\n const count = args.reduce((min, current) => Math.min(min, current.length), args[0].length);\n const result = new Array(count);\n for (let i = 0; i < count; i += 1) {\n result[i] = [];\n args.forEach(a => {\n result[i].push(a[i]);\n });\n }\n return result;\n },\n _signature: [{ types: [TYPE_ARRAY], variadic: true }],\n },\n };\n return functionMap;\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable max-classes-per-file */\n/* eslint-disable no-underscore-dangle */\nimport TreeInterpreter from './TreeInterpreter.js';\nimport Parser from './Parser.js';\nimport { dataTypes } from './dataTypes.js';\nimport { matchType, getType, isArrayType } from './matchType.js';\nimport functions from './functions.js';\nimport {\n isObject, strictDeepEqual, getValueOf,\n} from './utils.js';\nimport {\n evaluationError, typeError, functionError,\n} from './errors.js';\n\n// Type constants used to define functions.\nconst { TYPE_OBJECT } = dataTypes;\n\nfunction getToNumber(stringToNumber) {\n return value => {\n const n = getValueOf(value); // in case it's an object that implements valueOf()\n if (n === null) return 0;\n if (n instanceof Array) {\n throw typeError('Failed to convert array to number');\n }\n const type = typeof n;\n if (type === 'number') return n;\n if (type === 'string') return stringToNumber(n);\n if (type === 'boolean') return n ? 1 : 0;\n throw typeError('Failed to convert object to number');\n };\n}\nfunction toString(a) {\n if (a === null || a === undefined) return '';\n const type = getType(a);\n if (isArrayType(type)) {\n throw typeError('Failed to convert array to string');\n }\n if (type === TYPE_OBJECT) {\n throw typeError('Failed to convert object to string');\n }\n return a.toString();\n}\n\nconst defaultStringToNumber = (str => {\n const n = +str;\n return Number.isNaN(n) ? 0 : n;\n});\n\nclass Runtime {\n constructor(debug, toNumber, customFunctions = {}) {\n this.strictDeepEqual = strictDeepEqual;\n this.toNumber = toNumber;\n this.functionTable = functions(\n this,\n isObject,\n toNumber,\n getType,\n isArrayType,\n getValueOf,\n toString,\n debug,\n );\n\n Object.entries(customFunctions).forEach(([fname, func]) => {\n // Provide the runtime to custom functions so that\n // they can implement lambda functions\n // eslint-disable-next-line no-param-reassign\n func._runtime = this;\n this.functionTable[fname] = func;\n });\n }\n\n // eslint-disable-next-line class-methods-use-this\n _validateArgs(argName, args, signature, bResolved) {\n // Validating the args requires validating\n // the correct arity and the correct type of each arg.\n // If the last argument is declared as variadic, then we need\n // a minimum number of args to be required. Otherwise it has to\n // be an exact amount.\n if (signature.length === 0 && args.length > 0) {\n throw functionError(`${argName}() does not accept parameters`);\n }\n\n if (signature.length === 0) {\n return;\n }\n let pluralized;\n const argsNeeded = signature.filter(arg => !arg.optional).length;\n const lastArg = signature[signature.length - 1];\n if (lastArg.variadic) {\n if (args.length < signature.length && !lastArg.optional) {\n pluralized = signature.length === 1 ? ' argument' : ' arguments';\n throw functionError(`${argName}() takes at least ${signature.length}${pluralized\n } but received ${args.length}`);\n }\n } else if (args.length < argsNeeded || args.length > signature.length) {\n pluralized = signature.length === 1 ? ' argument' : ' arguments';\n throw functionError(`${argName}() takes ${signature.length}${pluralized\n } but received ${args.length}`);\n }\n // if the arguments are unresolved, there's no point in validating types\n if (!bResolved) return;\n let currentSpec;\n const limit = signature[signature.length - 1].variadic ? args.length\n : Math.min(signature.length, args.length);\n\n for (let i = 0; i < limit; i += 1) {\n currentSpec = i > signature.length - 1 ? signature[signature.length - 1].types\n : signature[i].types;\n // eslint-disable-next-line no-param-reassign\n args[i] = matchType(currentSpec, args[i], argName, this.toNumber, toString);\n }\n }\n\n callFunction(name, resolvedArgs, data, interpreter, bResolved = true) {\n // this check will weed out 'valueOf', 'toString' etc\n if (!Object.prototype.hasOwnProperty.call(this.functionTable, name)) {\n throw functionError(`No such function: ${name}()`);\n }\n\n const functionEntry = this.functionTable[name];\n this._validateArgs(name, resolvedArgs, functionEntry._signature, bResolved);\n return functionEntry._func.call(this, resolvedArgs, data, interpreter);\n }\n}\n\nexport default class Formula {\n constructor(debug, customFunctions, stringToNumberFn) {\n this.debug = debug;\n this.toNumber = getToNumber(stringToNumberFn || defaultStringToNumber);\n this.runtime = new Runtime(debug, this.toNumber, customFunctions);\n }\n\n compile(stream, allowedGlobalNames = []) {\n const parser = new Parser(allowedGlobalNames);\n return parser.parse(stream, this.debug);\n }\n\n search(node, data, globals = {}, language = 'en-US') {\n // This needs to be improved. Both the interpreter and runtime depend on\n // each other. The runtime needs the interpreter to support exprefs.\n // There's likely a clean way to avoid the cyclic dependency.\n this.runtime.interpreter = new TreeInterpreter(\n this.runtime,\n globals,\n this.toNumber,\n toString,\n this.debug,\n language,\n );\n\n try {\n return this.runtime.interpreter.search(node, data);\n } catch (e) {\n this.debug.push(e.message || e.toString());\n if (e.name === 'Error') throw evaluationError(e.message || e.toString());\n throw e;\n }\n }\n}\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport Formula from './interpreter.js';\n\nexport { dataTypes } from './dataTypes.js';\n\n/**\n * Class represents an instance of a JsonFormula Expression that can be executed later on with\n * multiple instances of JSON Data. The instance of the class has a search\n * function that can be used to evaluate the expression on a json payload.\n */\nclass JsonFormula {\n /**\n * @param {object} [customFunctions={}] custom functions needed by a hosting application.\n * @param {function} [stringToNumber='null'] A function that converts string values to numbers.\n * Can be used to convert currencies/dates to numbers\n * @param {string} [language=en-US]\n * @param {array} [debug=[]] will be populated with any errors/warnings\n */\n constructor(\n customFunctions = {},\n stringToNumber = null,\n debug = [],\n ) {\n this.customFunctions = { ...customFunctions };\n this.stringToNumber = stringToNumber;\n this.debug = debug;\n this.formula = new Formula(debug, customFunctions, stringToNumber);\n }\n\n /**\n * Evaluates the JsonFormula on a particular json payload and return the result\n * @param {object|array} json the json data on which the expression needs to be evaluated\n * @param {object} [globals={}] global objects that can be accessed via custom functions.\n * @returns {*} the result of the expression being evaluated\n */\n search(expression, json, globals = {}, language = 'en-US') {\n const ast = this.compile(expression, Object.keys(globals));\n return this.run(ast, json, language, globals);\n }\n\n /**\n * Execute a previously compiled expression against a json object and return the result\n * @param {object} ast The abstract syntax tree returned from compile()\n * @param {object|array} json the json data on which the expression needs to be evaluated\n * @param globals {*} set of objects available in global scope\n * @returns {*} the result of the expression being evaluated\n */\n run(ast, json, language, globals) {\n return this.formula.search(\n ast,\n json,\n globals,\n language,\n );\n }\n\n /**\n * Creates a compiled expression that can be executed later on with some data.\n * @param {string} expression the expression to evaluate\n * @param {string[]} [allowedGlobalNames=[]] A list of names of the global variables\n * being used in the expression.\n * @param {array} [debug=[]] will be populated with any errors/warnings\n */\n compile(expression, allowedGlobalNames = []) {\n this.debug.length = 0;\n return this.formula.compile(expression, allowedGlobalNames);\n }\n}\n\n/**\n * Compile and execute a json-formula expression.\n * If executing the same expression multiple times, it is more efficient to create a\n * class instance of {JsonFormula} and call the search method multiple times.\n* @param {object|array} json the json data on which the expression needs to be evaluated\n* @param {object} globals global objects that can be accessed via custom functions.\n* @param {string} expression the expression to evaluate\n* @param {object} [customFunctions={}] custom functions needed by a hosting application.\n* @param {function} [stringToNumber='null'] A function that converts string values to numbers.\n* Can be used to convert currencies/dates to numbers\n* @param {string} [language=en-US]\n* @param {array} [debug=[]] will be populated with any errors/warnings\n* @returns {*} the result of the expression being evaluated\n */\n\nexport function jsonFormula(\n json,\n globals,\n expression,\n customFunctions = {},\n stringToNumber = null,\n debug = [],\n language = 'en-US',\n) {\n return new JsonFormula(customFunctions, stringToNumber, debug)\n .search(expression, json, globals, language);\n}\n\nexport default JsonFormula;\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-param-reassign */\n/* eslint-disable max-classes-per-file */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable no-underscore-dangle */\n/*\n Field class allows objects to evaluate correctly according to context.\n - if used in an expression, will return a value or string.\n - for JSON.stringify() returns a scalar\n - BUT also allows explicit access to properties. e.g. field.required, field.name etc.\n\n Should allow us to eliminate getFieldProperty()\n */\nclass ArrayClass extends Array {}\nclass ObjectClass {}\n\nfunction createField(name, value, readonly = false, required = true) {\n class Field extends ObjectClass {\n valueOf() { return value; }\n\n toString() { return value.toString(); }\n\n toJSON() { return value; }\n }\n const f = new Field();\n Object.defineProperty(f, '$name', { get: () => name });\n Object.defineProperty(f, '$value', { get: () => value });\n Object.defineProperty(f, '$readonly', { get: () => readonly });\n Object.defineProperty(f, '$required', { get: () => required });\n\n return f;\n}\n\nfunction createFieldset(fsname, isObj, fields, children) {\n class FieldsetObj extends ObjectClass {\n _add(k, v) {\n this[k] = v;\n children.push(v);\n }\n }\n class FieldsetArray extends ArrayClass {\n _add(k, v) {\n this[k] = v;\n children.push(v);\n }\n }\n const fieldset = isObj ? new FieldsetObj() : new FieldsetArray();\n Object.defineProperty(fieldset, '$name', { get: () => fsname });\n Object.defineProperty(fieldset, '$fields', { get: () => fields });\n Object.defineProperty(fieldset, '$value', { get: () => fieldset.valueOf() });\n\n return fieldset;\n}\n\nfunction createFields(parent, childref, child) {\n const result = [];\n if (child instanceof Array) {\n // parent._add(childref, createFieldset(childref, false));\n parent._add(childref, createFieldset(childref, false, result, []));\n child.forEach((item, index) => {\n const fields = createFields(parent[childref], index, item);\n result.push(...fields);\n });\n } else if (child !== null && typeof child === 'object') {\n parent._add(childref, createFieldset(childref, true, result, []));\n Object.keys(child).forEach(k => {\n const fields = createFields(parent[childref], k, child[k]);\n result.push(...fields);\n });\n } else {\n const field = createField(childref, child);\n parent._add(childref, field);\n result.push(field);\n }\n return result;\n}\n\nexport default function createForm(dataRoot) {\n // if it's not an object or array (a scalar) then don't bother trying to create a form\n if (dataRoot === null || typeof dataRoot !== 'object') return dataRoot;\n\n const allFields = [];\n const form = createFieldset('', !Array.isArray(dataRoot), allFields, []);\n Object.entries(dataRoot).forEach(([k, v]) => {\n allFields.push(...createFields(form, k, v));\n });\n return form;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { typeError } from './errors.js';\n\nexport default function stringToNumber(n) {\n if (!/^\\s*(-|\\+)?(\\d*)(\\.\\d+)?(e(\\+|-)?\\d+)?\\s*$/i.test(n)) throw typeError(`Failed to convert \"${n}\" to number`);\n const ret = +n;\n if (Number.isNaN(ret)) {\n throw typeError(`Failed to convert \"${n}\" to number`);\n }\n return ret;\n}\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* global window, document */\nimport Formula from '../src/json-formula.js';\nimport createForm from './Form.js';\nimport stringToNumber from '../src/stringToNumber.js';\n\nwindow.addEventListener('load', () => {\n const dataElement = document.getElementById('data');\n const expression = document.getElementById('expression');\n const result = document.getElementById('result');\n const debug = document.getElementById('debug');\n const debugInfo = [];\n // keep one instance active for the entire session so that any registered\n // functions are retained\n const formula = new Formula({}, stringToNumber, debugInfo);\n const defaultData = `{\n \"address\": {\n \"street\": \"12 Oak St\",\n \"city\": \"San Jose\",\n \"state\": \"CA\",\n \"country\": \"USA\",\n \"phone\": \"1234561234\"\n },\n \"items\": [\n {\n \"desc\": \"pens\",\n \"quantity\": 2,\n \"price\": 3.23\n },\n {\n \"desc\": \"pencils\",\n \"quantity\": 3,\n \"price\": 1.34\n }\n ],\n \"tax\": 1.13\n }`;\n\n const params = new URLSearchParams(document.location.search);\n if (params.has('sample')) {\n const sampleJSON = JSON.parse(atob(params.get('sample')));\n if (sampleJSON.data) dataElement.value = JSON.stringify(sampleJSON.data, null, 2);\n if (sampleJSON.expression) expression.value = sampleJSON.expression;\n if (sampleJSON.description) {\n document.getElementById('description-row').style.display = 'table-row';\n document.getElementById('description').innerText = sampleJSON.description;\n }\n Array.from(document.getElementsByClassName('controls')).forEach(c => c.classList.add('hidden'));\n } else {\n const d = window.localStorage.getItem('data');\n if (d) dataElement.value = d;\n else dataElement.value = defaultData;\n const exp = window.localStorage.getItem('expression');\n if (exp) expression.value = exp;\n else expression.value = 'sum(items[*].price * items[*].quantity)';\n }\n\n function run() {\n // save for next time...\n window.localStorage.setItem('data', dataElement.value);\n window.localStorage.setItem('expression', expression.value);\n const input = expression.value;\n const useFields = document.getElementById('use-fields').checked;\n let jsonData;\n try {\n jsonData = JSON.parse(dataElement.value);\n if (useFields) {\n jsonData = createForm(jsonData);\n }\n } catch (e) {\n result.value = e.toString();\n return;\n }\n\n try {\n const jsonResult = formula.search(input, jsonData, {});\n debug.innerHTML = debugInfo.join('\\n');\n let r = jsonResult;\n if (jsonResult !== null && jsonResult !== undefined) {\n r = jsonResult.valueOf.call(jsonResult);\n }\n if (typeof r === 'object') {\n result.value = JSON.stringify(r, null, 2);\n } else {\n result.value = r;\n }\n } catch (e) {\n result.value = e.toString();\n debug.innerHTML = debugInfo.join('\\n');\n }\n }\n\n dataElement.addEventListener('blur', run);\n expression.addEventListener('blur', run);\n document.getElementById('data-reset').addEventListener(\n 'click',\n () => {\n dataElement.value = defaultData;\n if (params.has('sample')) {\n expression.value = 'sum(items[*].price * items[*].quantity)';\n document.getElementById('description-row').style.display = 'none';\n Array.from(document.getElementsByClassName('controls')).forEach(c => c.classList.remove('hidden'));\n window.history.pushState({}, document.title, '/');\n run();\n }\n },\n );\n document.getElementById('canned').addEventListener('change', e => {\n expression.value = e.target.value;\n run();\n });\n run();\n\n fetch('../antlr/JsonFormula.g4').then(r => {\n r.text().then(g4 => {\n // remove comments and processing directives.\n const strippedGrammar = g4\n .replace(/[\\s\\S.]*grammar/m, 'grammar')\n .replace(/#.*/g, '');\n document.getElementById('grammar-out').innerHTML = strippedGrammar;\n });\n });\n});\n"],"names":["__webpack_require__","exports","Symbol","toStringTag","Object","defineProperty","value","dataTypes","TYPE_NUMBER","TYPE_ANY","TYPE_STRING","TYPE_ARRAY","TYPE_OBJECT","TYPE_BOOLEAN","TYPE_EXPREF","TYPE_NULL","TYPE_ARRAY_NUMBER","TYPE_ARRAY_STRING","TYPE_ARRAY_ARRAY","TYPE_EMPTY_ARRAY","typeNameTable","TOK_EOF","TOK_IDENTIFIER","TOK_QUOTEDIDENTIFIER","TOK_RBRACKET","TOK_RPAREN","TOK_COMMA","TOK_COLON","TOK_CONCATENATE","TOK_RBRACE","TOK_NUMBER","TOK_CURRENT","TOK_GLOBAL","TOK_EXPREF","TOK_PIPE","TOK_OR","TOK_AND","TOK_ADD","TOK_SUBTRACT","TOK_UNARY_MINUS","TOK_MULTIPLY","TOK_UNION","TOK_DIVIDE","TOK_COMPARATOR","TOK_FLATTEN","TOK_STAR","TOK_FILTER","TOK_DOT","TOK_NOT","TOK_LBRACE","TOK_LBRACKET","TOK_LPAREN","TOK_JSON","TOK_STRING","TOK_INT","typeError","desc","TypeError","syntaxError","e","Error","name","functionError","evaluationError","tokenDefinitions","isArray","t","includes","getType","inputObj","simpleType","obj","Array","length","flat","Infinity","every","a","jmespathType","type","JSON","parse","stringify","isArrayType","getTypeName","arg","matchType","expectedList","argValue","context","toNumber","toString","actual","isObject","some","match","expect","found","filteredList","filter","supportedConversion","to","exactMatch","expected","wrongType","map","join","keys","toArray","coerceString","coerceNumber","prototype","call","getValueOf","i","valueOf","toBoolean","param","val","strictDeepEqual","lhs","rhs","first","second","f","key","hasOwnProperty","getProperty","getOwnPropertyDescriptor","enumerable","get","for","debugAvailable","debug","chainStart","available","push","entries","getOwnPropertyDescriptors","k","test","startsWith","balanceArrayOperands","opLeft","opRight","shorter","diff","Math","abs","fill","TreeInterpreter","constructor","runtime","globals","language","this","visitFunctions","initVisitFunctions","debugChainStart","search","node","visit","field","undefined","Identifier","bind","QuotedIdentifier","ChainedExpression","result","children","BracketExpression","left","Index","index","Slice","sliceParams","start","stop","step","computeSliceParams","Projection","base","collected","forEach","b","current","ValueProjection","projection","values","FilterProjection","filtered","finalResults","Comparator","type1","type2","_e","original","merged","Identity","_node","ArrayExpression","child","ObjectExpression","OrExpression","matched","AndExpression","AddExpression","applyOperator","ConcatenateExpression","UnionExpression","concat","SubtractExpression","MultiplyExpression","DivideExpression","NotExpression","UnaryMinusExpression","minus","Number","isNaN","String","Literal","Integer","Function","callFunction","resolvedArgs","ExpressionReference","refNode","n","v","arrayLength","capSliceRange","arrayLen","stp","actualValue","stepValueNegative","operator","n1","n2","isFinite","basicTokens","operatorStartToken","skipChars","isAlphaNum","ch","isIdentifier","stream","pos","Lexer","allowedGlobalNames","_allowedGlobalNames","tokenize","tokens","identifier","token","_current","prev","slice","_isGlobal","_consumeGlobal","_consumeUnquotedIdentifier","_isNumber","_consumeNumber","_consumeLBracket","_consumeQuotedIdentifier","_consumeRawStringLiteral","json","_consumeJson","_consumeOperator","_consumeUnaryMinus","maxLength","foundNonAlpha","replace","substring","literal","num","toLowerCase","parseFloat","parseInt","global","startingChar","literalString","trimStart","replaceAll","bindingPower","Parser","expression","_loadTokens","ast","_lookahead","_lookaheadToken","rbp","leftToken","_advance","nud","currentToken","led","number","previous","next","_lookAheadIndex","idx","_getIndex","_setIndex","right","args","Not","UnaryMinus","_parseProjectionRHS","Star","_parseObjectExpression","Flatten","_parseIndexExpression","_projectIfSlice","_parseArrayExpression","Expref","_match","_errorToken","condition","leftNode","rightNode","Concatenate","Dot","_parseDotRHS","Pipe","Or","And","Add","Subtract","Multiply","Divide","Union","_parseFunctionArgs","Filter","_parseComparator","tokenType","firstExpression","_parseSignedInt","oldIndex","_parseSliceExpression","indexExpr","parts","comparator","lookahead","indexOf","expressions","pairs","identifierTypes","keyToken","keyName","MS_IN_DAY","getDateObj","dateNum","Date","round","getDateNum","dateObj","validNumber","defaultStringToNumber","str","Runtime","customFunctions","functionTable","toInteger","trunc","toJSON","indent","offset","evaluate","fn","listOfArrays","maxLen","max","allArrays","arrays","row","j","balanceArrays","datedifFn","date1Arg","date2Arg","unitArg","unit","date1","date2","floor","yearDiff","getFullYear","monthDiff","getMonth","dayDiff","getDate","y","setFullYear","endsWithFn","searchArg","suffixArg","searchStr","suffix","from","reverse","c","eomonthFn","dateArg","monthsArg","jsDate","months","findFn","queryArg","textArg","offsetArg","query","text","properFn","capitalize","word","charAt","toUpperCase","wordParts","w","reptFn","countArg","count","repeat","searchFn","findTextString","withinTextString","startPosInt","findText","withinText","startPos","globString","reduce","acc","cur","escape","pop","testMatch","array","glob","testChar","globChar","nextGlob","isStar","within","splitFn","strArg","separatorArg","separator","split","startsWithFn","subjectString","prefixString","subject","prefix","substituteFn","source","oldString","replacementString","nearest","src","old","replacement","whch","truncFn","d","digits","ceil","weekdayFn","date","day","getDay","functionMap","_func","_signature","types","acos","and","variadic","asin","atan2","avg","sum","avgA","casefold","_data","interpreter","s","toLocaleUpperCase","toLocaleLowerCase","codePoint","codePointAt","contains","searchLen","cos","datedif","datetime","year","month","hours","minutes","seconds","ms","optional","deepScan","checkArrays","items","scan","endsWith","eomonth","exp","false","find","fromCodePoint","points","fromEntries","fround","hasProperty","keyType","hour","getHours","if","unresolvedArgs","data","conditionNode","leftBranchNode","rightBranchNode","listJoin","joinChar","numEntries","log","log10","lower","exprefNode","maxA","merge","mid","millisecond","getMilliseconds","min","minA","minute","getMinutes","mod","not","resolveArgs","notNull","now","null","or","power","proper","random","accumulated","register","functionName","_exprefNode","registerWithParams","numElements","sourceArray","splice","newText","rept","originalStr","precision","getSeconds","sign","sin","sort","typeVals","sorted","sortFunction","sortBy","sortedArray","requiredType","decorated","exprA","typeA","exprB","typeB","sqrt","stdev","mean","sumSquare","stdevA","stdevp","meanSumSquare","stdevpA","substitute","o","tan","time","toDate","iso","dateparts","x","range","getTime","today","toNumberFn","digitCheck","p","trim","decimal","errorString","true","unique","valueArray","findIndex","lookup","upper","indexType","subjectArray","weekday","zip","functions","fname","func","_runtime","_validateArgs","argName","signature","bResolved","pluralized","argsNeeded","lastArg","currentSpec","limit","functionEntry","Formula","stringToNumberFn","stringToNumber","getToNumber","compile","message","formula","run","ArrayClass","ObjectClass","createFieldset","fsname","isObj","fields","fieldset","_add","createFields","parent","childref","item","readonly","required","createField","ret","window","addEventListener","dataElement","document","getElementById","debugInfo","defaultData","params","URLSearchParams","location","has","sampleJSON","atob","description","style","display","innerText","getElementsByClassName","classList","add","localStorage","getItem","setItem","input","useFields","checked","jsonData","dataRoot","allFields","form","createForm","jsonResult","innerHTML","r","remove","history","pushState","title","target","fetch","then","g4","strippedGrammar"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"tutorial.js","mappings":"mCACA,IAAIA,ECAqBC,IACH,oBAAXC,QAA0BA,OAAOC,aAC1CC,OAAOC,eAAeJ,EAASC,OAAOC,YAAa,CAAEG,MAAO,WAE7DF,OAAOC,eAAeJ,EAAS,aAAc,CAAEK,OAAO,GAAO,E,gBCwB9D,MAAMC,EAAY,CAChBC,YAAa,EACbC,SAAU,EACVC,YAAa,EACbC,WAAY,EACZC,YAAa,EACbC,aAAc,EACdC,YAAa,EACbC,UAAW,EACXC,kBAAmB,EACnBC,kBAAmB,EACnBC,iBAAkB,GAClBC,iBAAkB,IAGdC,EAAgB,CACpB,CAACb,EAAUC,aAAc,SACzB,CAACD,EAAUE,UAAW,MACtB,CA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GAE1B,CAAE,MAAO3mB,GAEP,YADA6G,EAAOlK,MAAQqD,EAAEgC,WAEnB,CAEA,IACE,MAAMglB,EAAajD,EAAQ3d,OAAOogB,EAAOG,EAAU,CAAC,GACpDjiB,EAAMuiB,UAAY3B,EAAUviB,KAAK,MACjC,IAAImkB,EAAIF,EACJA,UACFE,EAAIF,EAAWxjB,QAAQH,KAAK2jB,IAG5BngB,EAAOlK,MADQ,iBAANuqB,EACM7lB,KAAKE,UAAU2lB,EAAG,KAAM,GAExBA,CAEnB,CAAE,MAAOlnB,GACP6G,EAAOlK,MAAQqD,EAAEgC,WACjB0C,EAAMuiB,UAAY3B,EAAUviB,KAAK,KACnC,CACF,CAEAoiB,EAAYD,iBAAiB,OAAQlB,GACrC9V,EAAWgX,iBAAiB,OAAQlB,GACpCoB,SAASC,eAAe,cAAcH,iBACpC,SACA,KACEC,EAAYxoB,MAAQ4oB,EAChBC,EAAOG,IAAI,YACbzX,EAAWvR,MAAQ,0CACnByoB,SAASC,eAAe,mBAAmBU,MAAMC,QAAU,OAC3DnlB,MAAMsU,KAAKiQ,SAASc,uBAAuB,aAAate,SAAQyN,GAAKA,EAAE8Q,UAAUgB,OAAO,YACxFlC,OAAOmC,QAAQC,UAAU,CAAC,EAAGjC,SAASkC,MAAO,KAC7CtD,IACF,IAGJoB,SAASC,eAAe,UAAUH,iBAAiB,UAAUllB,IAC3DkO,EAAWvR,MAAQqD,EAAEunB,OAAO5qB,MAC5BqnB,GAAK,IAEPA,IAEAwD,MAAM,2BAA2BC,MAAKP,IACpCA,EAAElR,OAAOyR,MAAKC,IAEZ,MAAMC,EAAkBD,EACrBta,QAAQ,mBAAoB,WAC5BA,QAAQ,OAAQ,IACnBgY,SAASC,eAAe,eAAe4B,UAAYU,CAAe,GAClE,GACF,G","sources":["webpack://jsonFormula/webpack/bootstrap","webpack://jsonFormula/webpack/runtime/make namespace object","webpack://jsonFormula/./src/dataTypes.js","webpack://jsonFormula/./src/tokenDefinitions.js","webpack://jsonFormula/./src/errors.js","webpack://jsonFormula/./src/matchType.js","webpack://jsonFormula/./src/utils.js","webpack://jsonFormula/./src/TreeInterpreter.js","webpack://jsonFormula/./src/Lexer.js","webpack://jsonFormula/./src/Parser.js","webpack://jsonFormula/./src/functions.js","webpack://jsonFormula/./src/interpreter.js","webpack://jsonFormula/./src/json-formula.js","webpack://jsonFormula/./tutorial/Form.js","webpack://jsonFormula/./src/stringToNumber.js","webpack://jsonFormula/./tutorial/tutorial.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n// Type constants used to define functions.\nconst dataTypes = {\n TYPE_NUMBER: 0,\n TYPE_ANY: 1,\n TYPE_STRING: 2,\n TYPE_ARRAY: 3,\n TYPE_OBJECT: 4,\n TYPE_BOOLEAN: 5,\n TYPE_EXPREF: 6,\n TYPE_NULL: 7,\n TYPE_ARRAY_NUMBER: 8,\n TYPE_ARRAY_STRING: 9,\n TYPE_ARRAY_ARRAY: 10,\n TYPE_EMPTY_ARRAY: 11,\n};\n\nconst typeNameTable = {\n [dataTypes.TYPE_NUMBER]: 'number',\n [dataTypes.TYPE_ANY]: 'any',\n [dataTypes.TYPE_STRING]: 'string',\n [dataTypes.TYPE_ARRAY]: 'array',\n [dataTypes.TYPE_OBJECT]: 'object',\n [dataTypes.TYPE_BOOLEAN]: 'boolean',\n [dataTypes.TYPE_EXPREF]: 'expression',\n [dataTypes.TYPE_NULL]: 'null',\n [dataTypes.TYPE_ARRAY_NUMBER]: 'Array',\n [dataTypes.TYPE_ARRAY_STRING]: 'Array',\n [dataTypes.TYPE_ARRAY_ARRAY]: 'Array',\n [dataTypes.TYPE_EMPTY_ARRAY]: 'array',\n};\n\nexport { dataTypes, typeNameTable };\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nexport default {\n TOK_EOF: 'EOF',\n TOK_IDENTIFIER: 'Identifier',\n TOK_QUOTEDIDENTIFIER: 'QuotedIdentifier',\n TOK_RBRACKET: 'Rbracket',\n TOK_RPAREN: 'Rparen',\n TOK_COMMA: 'Comma',\n TOK_COLON: 'Colon',\n TOK_CONCATENATE: 'Concatenate',\n TOK_RBRACE: 'Rbrace',\n TOK_NUMBER: 'Number',\n TOK_CURRENT: 'Current',\n TOK_GLOBAL: 'Global',\n TOK_EXPREF: 'Expref',\n TOK_PIPE: 'Pipe',\n TOK_OR: 'Or',\n TOK_AND: 'And',\n TOK_ADD: 'Add',\n TOK_SUBTRACT: 'Subtract',\n TOK_UNARY_MINUS: 'UnaryMinus',\n TOK_MULTIPLY: 'Multiply',\n TOK_UNION: 'Union',\n TOK_DIVIDE: 'Divide',\n TOK_COMPARATOR: 'Comparator',\n TOK_FLATTEN: 'Flatten',\n TOK_STAR: 'Star',\n TOK_FILTER: 'Filter',\n TOK_DOT: 'Dot',\n TOK_NOT: 'Not',\n TOK_LBRACE: 'Lbrace',\n TOK_LBRACKET: 'Lbracket',\n TOK_LPAREN: 'Lparen',\n TOK_JSON: 'Literal',\n TOK_STRING: 'String',\n TOK_INT: 'Integer',\n};\n","/*\nCopyright 2023 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nexport function typeError(desc) {\n return new TypeError(desc);\n}\n\nexport function syntaxError(desc) {\n const e = new Error(desc);\n e.name = 'SyntaxError';\n return e;\n}\n\nexport function functionError(desc) {\n const e = new Error(desc);\n e.name = 'FunctionError';\n return e;\n}\n\nexport function evaluationError(desc) {\n const e = new Error(desc);\n e.name = 'EvaluationError';\n return e;\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { dataTypes, typeNameTable } from './dataTypes.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { typeError } from './errors.js';\n// import { isClass } from './utils.js';\n\nconst {\n TYPE_NUMBER,\n TYPE_ANY,\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_OBJECT,\n TYPE_BOOLEAN,\n TYPE_EXPREF,\n TYPE_NULL,\n TYPE_ARRAY_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY_ARRAY,\n TYPE_EMPTY_ARRAY,\n} = dataTypes;\n\nconst {\n TOK_EXPREF,\n} = tokenDefinitions;\n\nfunction isArray(t) {\n return [\n TYPE_ARRAY, TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING, TYPE_ARRAY_ARRAY, TYPE_EMPTY_ARRAY,\n ].includes(t);\n}\n\nexport function getType(inputObj) {\n function simpleType(obj) {\n if (obj === null) return TYPE_NULL;\n const t = typeof obj;\n if (t === 'string') return TYPE_STRING;\n if (t === 'number') return TYPE_NUMBER;\n if (t === 'boolean') return TYPE_BOOLEAN;\n if (Array.isArray(obj)) {\n if (obj.length === 0) return TYPE_EMPTY_ARRAY;\n if (obj.flat(Infinity).every(a => getType(a) === TYPE_NUMBER)) return TYPE_ARRAY_NUMBER;\n if (obj.flat(Infinity).every(a => getType(a) === TYPE_STRING)) return TYPE_ARRAY_STRING;\n if (obj.every(a => isArray(getType(a)))) return TYPE_ARRAY_ARRAY;\n return TYPE_ARRAY;\n }\n // Check if it's an expref. If it has, it's been\n // tagged with a jmespathType attr of 'Expref';\n if (obj.jmespathType === TOK_EXPREF) return TYPE_EXPREF;\n return TYPE_OBJECT;\n }\n let type = simpleType(inputObj);\n if (type !== TYPE_OBJECT) return type;\n // if inputObj is a class, then convert it to its base type via JSON\n const obj = JSON.parse(JSON.stringify(inputObj));\n type = simpleType(obj);\n return type;\n}\n\nexport function isArrayType(t) {\n return [\n TYPE_ARRAY, TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING, TYPE_ARRAY_ARRAY, TYPE_EMPTY_ARRAY,\n ].includes(getType(t));\n}\n\nexport function getTypeName(arg) {\n return typeNameTable[getType(arg)];\n}\n\nfunction supportedConversion(from, to) {\n const pairs = {\n [TYPE_NUMBER]: [\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_ARRAY_NUMBER,\n TYPE_BOOLEAN,\n ],\n [TYPE_BOOLEAN]: [\n TYPE_STRING,\n TYPE_NUMBER,\n TYPE_ARRAY,\n ],\n [TYPE_ARRAY]: [TYPE_BOOLEAN, TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER],\n [TYPE_ARRAY_NUMBER]: [TYPE_BOOLEAN, TYPE_ARRAY_STRING, TYPE_ARRAY],\n [TYPE_ARRAY_STRING]: [TYPE_BOOLEAN, TYPE_ARRAY_NUMBER, TYPE_ARRAY],\n [TYPE_ARRAY_ARRAY]: [TYPE_BOOLEAN],\n [TYPE_EMPTY_ARRAY]: [TYPE_BOOLEAN],\n\n [TYPE_OBJECT]: [TYPE_BOOLEAN],\n [TYPE_NULL]: [\n TYPE_STRING,\n TYPE_NUMBER,\n TYPE_BOOLEAN,\n ],\n [TYPE_STRING]: [\n TYPE_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY,\n TYPE_BOOLEAN],\n };\n return pairs[from].includes(to);\n}\n\nexport function matchType(expectedList, argValue, context, toNumber, toString) {\n const actual = getType(argValue);\n if (argValue?.jmespathType === TOK_EXPREF && !expectedList.includes(TYPE_EXPREF)) {\n throw typeError(`${context} does not accept an expression reference argument.`);\n }\n const isObject = t => t === TYPE_OBJECT;\n const match = (expect, found) => expect === found\n || expect === TYPE_ANY\n || (expect === TYPE_ARRAY && isArray(found))\n || (isArray(expect) && found === TYPE_EMPTY_ARRAY);\n\n if (expectedList.some(type => match(type, actual))) return argValue;\n\n // if the function allows multiple types, we can't coerce the type and we need an exact match\n // Of the set of expected types, filter out the ones that can be coerced from the actual type\n const filteredList = expectedList.filter(t => supportedConversion(actual, t));\n if (filteredList.length === 0) {\n throw typeError(`${context} expected argument to be type ${typeNameTable[expectedList[0]]} but received type ${typeNameTable[actual]} instead.`);\n }\n const exactMatch = filteredList.length > 1;\n const expected = filteredList[0];\n let wrongType = false;\n\n // Can't coerce objects and arrays to any other type\n if (isArray(actual)) {\n if ([TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING].includes(expected)) {\n if (argValue.flat(Infinity).some(a => {\n const t = getType(a);\n // can't coerce arrays or objects to numbers or strings\n return isArray(t) || isObject(t);\n })) wrongType = true;\n }\n }\n // nothing coerces to an object\n if (exactMatch && expected === TYPE_OBJECT) wrongType = true;\n\n if (exactMatch) {\n throw typeError(`${context} cannot process type: ${typeNameTable[actual]}. Must be one of: ${expectedList.map(t => typeNameTable[t]).join(', ')}.`);\n }\n if (wrongType) {\n throw typeError(`${context} expected argument to be type ${typeNameTable[expected]} but received type ${typeNameTable[actual]} instead.`);\n }\n // Can't coerce Objects and arrays to anything other than boolean\n if (isObject(actual) && expected === TYPE_BOOLEAN) {\n return Object.keys(argValue).length === 0;\n }\n\n // no exact match, see if we can coerce an array type\n if (isArray(actual)) {\n const toArray = a => (Array.isArray(a) ? a : [a]);\n const coerceString = a => (Array.isArray(a) ? a.map(coerceString) : toString(a));\n const coerceNumber = a => (Array.isArray(a) ? a.map(coerceNumber) : toNumber(a));\n\n if (expected === TYPE_BOOLEAN) return argValue.length > 0;\n if (expected === TYPE_ARRAY_STRING) return argValue.map(coerceString);\n if (expected === TYPE_ARRAY_NUMBER) return argValue.map(coerceNumber);\n if (expected === TYPE_ARRAY_ARRAY) return argValue.map(toArray);\n }\n\n if (!isArray(actual) && !isObject(actual)) {\n if (expected === TYPE_ARRAY_STRING) return [toString(argValue)];\n if (expected === TYPE_ARRAY_NUMBER) return [toNumber(argValue)];\n if (expected === TYPE_ARRAY) return [argValue];\n if (expected === TYPE_NUMBER) return toNumber(argValue);\n if (expected === TYPE_STRING) return toString(argValue);\n if (expected === TYPE_BOOLEAN) return !!argValue;\n }\n\n throw typeError(`${context} expected argument to be type ${typeNameTable[expected]} but received type ${typeNameTable[actual]} instead.`);\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nexport function isArray(obj) {\n return Array.isArray(obj);\n}\n\nexport function isObject(obj) {\n if (obj !== null) {\n return Object.prototype.toString.call(obj) === '[object Object]';\n }\n return false;\n}\n\nexport function getValueOf(a) {\n if (a === null || a === undefined) return a;\n if (isArray(a)) {\n return a.map(i => getValueOf(i));\n }\n // if we have a child named 'valueOf' then we're an object,\n // and just return the object.\n if (typeof (a.valueOf) !== 'function') return a;\n return a.valueOf();\n}\n\nexport function toBoolean(param) {\n if (param === null) return false;\n // in case it's an object with a valueOf defined\n const val = getValueOf(param);\n\n // empty arrays are false\n if (Array.isArray(val)) return val.length > 0;\n // empty objects are false\n if (isObject(val)) return Object.keys(val).length > 0;\n return !!val;\n}\n\nexport function strictDeepEqual(lhs, rhs) {\n const first = getValueOf(lhs);\n const second = getValueOf(rhs);\n // Check the scalar case first.\n if (first === second) {\n return true;\n }\n\n // Check if they are the same type.\n const firstType = Object.prototype.toString.call(first);\n if (firstType !== Object.prototype.toString.call(second)) {\n return false;\n }\n // We know that first and second have the same type so we can just check the\n // first type from now on.\n if (isArray(first) === true) {\n // Short circuit if they're not the same length;\n if (first.length !== second.length) return false;\n return first.every((f, i) => strictDeepEqual(f, second[i]));\n }\n if (isObject(first) === true) {\n if (Object.keys(first).length !== Object.keys(second).length) return false;\n // An object is equal if it has the same key/value pairs.\n // eslint-disable-next-line no-restricted-syntax\n for (const key in first) {\n if (hasOwnProperty.call(first, key)) {\n if (strictDeepEqual(first[key], second[key]) === false) return false;\n }\n }\n return true;\n }\n return false;\n}\n\nexport function getProperty(obj, key) {\n const desc = Object.getOwnPropertyDescriptor(obj, key);\n // if it's a regular enumerable property or if it's configured with a getter,\n // then return it.\n // if it's a built-in property such as length or toString etc. we'll want to ignore it.\n if (desc?.enumerable || !!desc?.get) {\n // for applications that want to track which properties are accessed, allow for a special\n // hook to callback and register this key/value accessor.\n obj[key]?.[Symbol.for('track')]?.(obj, key);\n return obj[key];\n }\n return undefined;\n}\n\nexport function debugAvailable(debug, obj, key, chainStart = null) {\n try {\n let available = [];\n if (isArray(obj) && obj.length > 0) {\n debug.push(`Failed to find: '${key}' on an array object.`);\n debug.push(`Did you mean to use a projection? e.g. ${chainStart || 'array'}[*].${key}`);\n return;\n }\n debug.push(`Failed to find: '${key}'`);\n if (obj !== null) {\n available = [...available, ...Object.entries(Object.getOwnPropertyDescriptors(obj, key))\n .filter(([k, desc]) => (desc?.enumerable || !!desc?.get) && !/^[0-9]+$/.test(k) && (!k.startsWith('$') || key.startsWith('$')))\n .map(([k]) => `'${k}'`)];\n }\n if (available.length) debug.push(`Available fields: ${available}`);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n}\n\nexport function isClass(obj) {\n if (obj === null) return false;\n if (Array.isArray(obj)) return false;\n return !['Object', 'Boolean', 'Number', 'String'].includes(obj.constructor.name);\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport {\n matchType, getTypeName, getType, isArrayType,\n} from './matchType.js';\nimport { dataTypes } from './dataTypes.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport {\n isArray, isObject, strictDeepEqual, getValueOf, getProperty, debugAvailable, toBoolean,\n} from './utils.js';\nimport { evaluationError, typeError } from './errors.js';\n\nconst {\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_FLATTEN,\n} = tokenDefinitions;\n\nconst {\n TYPE_STRING,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY,\n TYPE_NUMBER,\n} = dataTypes;\n\nfunction objValues(obj) {\n return Object.values(obj);\n}\n\nfunction balanceArrayOperands(opLeft, opRight) {\n if (isArray(opLeft) && isArray(opRight)) {\n // balance the size of the arrays by padding with nulls\n const shorter = opLeft.length < opRight.length ? opLeft : opRight;\n const diff = Math.abs(opLeft.length - opRight.length);\n shorter.length += diff;\n shorter.fill(null, shorter.length - diff);\n }\n}\n\nexport default class TreeInterpreter {\n constructor(runtime, globals, toNumber, toString, debug, language) {\n this.runtime = runtime;\n this.globals = globals;\n this.toNumber = toNumber;\n this.toString = toString;\n this.debug = debug;\n this.language = language;\n this.visitFunctions = this.initVisitFunctions();\n // track the identifier name that started the chain\n // so that we can use it in debug hints\n this.debugChainStart = null;\n }\n\n search(node, value) {\n return this.visit(node, value);\n }\n\n field(node, value) {\n // we used to check isObject(value) here -- but it is possible for an array-based\n // object to have properties. So we'll allow the child check on objects and arrays.\n if (value !== null && (isObject(value) || isArray(value))) {\n const field = getProperty(value, node.name);\n if (field === undefined) {\n debugAvailable(this.debug, value, node.name, this.debugChainStart);\n return null;\n }\n return field;\n }\n debugAvailable(this.debug, value, node.name, this.debugChainStart);\n return null;\n }\n\n initVisitFunctions() {\n return {\n Identifier: this.field.bind(this),\n QuotedIdentifier: this.field.bind(this),\n ChainedExpression: (node, value) => {\n let result = this.visit(node.children[0], value);\n this.debugChainStart = node.children[0].name;\n for (let i = 1; i < node.children.length; i += 1) {\n result = this.visit(node.children[1], result);\n if (result === null) return null;\n }\n return result;\n },\n\n BracketExpression: (node, value) => {\n const left = this.visit(node.children[0], value);\n return this.visit(node.children[1], left);\n },\n\n Index: (node, value) => {\n if (isArray(value)) {\n let index = node.value.value;\n if (index < 0) {\n index = value.length + index;\n }\n const result = value[index];\n if (result === undefined) {\n this.debug.push(`Index: ${index} out of range for array size: ${value.length}`);\n return null;\n }\n return result;\n }\n this.debug.push('Left side of index expression must be an array');\n this.debug.push(`Did you intend a single-element array? if so, use a JSON literal: \\`[${node.value.value}]\\``);\n return null;\n },\n\n Slice: (node, value) => {\n if (!isArray(value)) {\n this.debug.push('Slices apply to arrays only');\n return null;\n }\n const sliceParams = node.children.map(param => (param === null ? null : param.value));\n const [start, stop, step] = this.computeSliceParams(value.length, sliceParams);\n const result = [];\n if (step > 0) {\n for (let i = start; i < stop; i += step) {\n result.push(value[i]);\n }\n } else {\n for (let i = start; i > stop; i += step) {\n result.push(value[i]);\n }\n }\n return result;\n },\n\n Projection: (node, value) => {\n // Evaluate left child.\n const base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n if (node.debug === 'Wildcard') {\n this.debug.push('Bracketed wildcards apply to arrays only');\n }\n return null;\n }\n const collected = [];\n base.forEach(b => {\n const current = this.visit(node.children[1], b);\n collected.push(current);\n });\n return collected;\n },\n\n // wildcard: \".*\"\n ValueProjection: (node, value) => {\n // Evaluate left child.\n const projection = this.visit(node.children[0], value);\n if (!isObject(getValueOf(projection))) {\n this.debug.push('Chained wildcards apply to objects only');\n return null;\n }\n const collected = [];\n const values = objValues(projection);\n values.forEach(val => {\n const current = this.visit(node.children[1], val);\n collected.push(current);\n });\n return collected;\n },\n\n FilterProjection: (node, value) => {\n const base = this.visit(node.children[0], value);\n if (!isArray(base)) {\n this.debug.push('Filter expressions apply to arrays only');\n return null;\n }\n const filtered = base.filter(b => {\n const matched = this.visit(node.children[2], b);\n return toBoolean(matched);\n });\n\n const finalResults = [];\n filtered.forEach(f => {\n const current = this.visit(node.children[1], f);\n finalResults.push(current);\n });\n return finalResults;\n },\n\n Comparator: (node, value) => {\n let first = getValueOf(this.visit(node.children[0], value));\n let second = getValueOf(this.visit(node.children[1], value));\n\n if (node.value === '==') return strictDeepEqual(first, second);\n if (node.value === '!=') return !strictDeepEqual(first, second);\n if (isObject(first) || isArray(first)) {\n this.debug.push(`Cannot use comparators with ${getTypeName(first)}`);\n return false;\n }\n if (isObject(second) || isArray(second)) {\n this.debug.push(`Cannot use comparators with ${getTypeName(second)}`);\n return false;\n }\n const type1 = getType(first);\n const type2 = getType(second);\n // if either parameter is a number, we need to do a numeric comparison\n // javascript will compare this way automatically, but if we explicitly convert\n // to numbers, we will get debug warnings for non-numeric strings\n if (type1 === TYPE_NUMBER || type2 === TYPE_NUMBER) {\n // if toNumber fails, it will populate the debug array\n // with an appropriate warning\n try {\n first = this.toNumber(first);\n second = this.toNumber(second);\n if (first === null || second === null) return false;\n } catch (_e) {\n // failing to convert to a number for comparison is not an error\n // we just return false\n return false;\n }\n }\n if (node.value === '>') return first > second;\n if (node.value === '>=') return first >= second;\n if (node.value === '<') return first < second;\n // if (node.value === '<=)\n // must be LTE\n return first <= second;\n },\n\n [TOK_FLATTEN]: (node, value) => {\n const original = this.visit(node.children[0], value);\n if (!isArray(original)) {\n this.debug.push('Flatten expressions apply to arrays only. If you want an empty array, use a JSON literal: `[]`');\n return null;\n }\n const merged = [];\n original.forEach(current => {\n if (isArray(current)) {\n merged.push(...current);\n } else {\n merged.push(current);\n }\n });\n return merged;\n },\n\n Identity: (_node, value) => value,\n\n ArrayExpression: (node, value) => node.children.map(child => this.visit(child, value)),\n\n ObjectExpression: (node, value) => {\n // at one time we used to have this:\n // if (value === null) return null;\n // BUT then an expression such as:\n // values({a: 'aa'})\n // would return null if the document were `null`\n // Removing the check means that:\n // `null`.{a: 'aa'}\n // returns: {a: 'aa'}\n // which is a bit odd, but seems correct.\n const collected = {};\n node.children.forEach(child => {\n if (collected[child.name] !== undefined) this.debug.push(`Duplicate key: '${child.name}'`);\n collected[child.name] = this.visit(child.value, value);\n });\n return collected;\n },\n\n OrExpression: (node, value) => {\n let matched = this.visit(node.children[0], value);\n if (!toBoolean(matched)) matched = this.visit(node.children[1], value);\n return matched;\n },\n\n AndExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n\n if (!toBoolean(first)) return first;\n return this.visit(node.children[1], value);\n },\n\n AddExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '+');\n },\n\n ConcatenateExpression: (node, value) => {\n let first = this.visit(node.children[0], value);\n let second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n if (isArrayType(first)) {\n first = matchType([TYPE_ARRAY_STRING], first, 'concatenate', this.toNumber, this.toString);\n } else {\n first = matchType([TYPE_STRING], first, 'concatenate', this.toNumber, this.toString);\n }\n if (isArrayType(second)) {\n second = matchType([TYPE_ARRAY_STRING], second, 'concatenate', this.toNumber, this.toString);\n } else {\n second = matchType([TYPE_STRING], second, 'concatenate', this.toNumber, this.toString);\n }\n return this.applyOperator(first, second, '&');\n },\n\n UnionExpression: (node, value) => {\n let first = this.visit(node.children[0], value);\n if (first === null) first = [null];\n let second = this.visit(node.children[1], value);\n if (second === null) second = [null];\n first = matchType([TYPE_ARRAY], first, 'union', this.toNumber, this.toString);\n second = matchType([TYPE_ARRAY], second, 'union', this.toNumber, this.toString);\n return first.concat(second);\n },\n\n SubtractExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '-');\n },\n\n MultiplyExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '*');\n },\n\n DivideExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const second = this.visit(node.children[1], value);\n balanceArrayOperands(first, second);\n return this.applyOperator(first, second, '/');\n },\n\n NotExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n return !toBoolean(first);\n },\n\n UnaryMinusExpression: (node, value) => {\n const first = this.visit(node.children[0], value);\n const minus = first * -1;\n if (Number.isNaN(minus)) throw typeError(`Failed to convert \"${first}\" to number`);\n return minus;\n },\n\n String: node => node.value,\n\n Literal: node => node.value,\n\n Number: node => node.value,\n\n Integer: node => node.value,\n\n [TOK_PIPE]: (node, value) => {\n const left = this.visit(node.children[0], value);\n return this.visit(node.children[1], left);\n },\n\n [TOK_CURRENT]: (_node, value) => value,\n\n [TOK_GLOBAL]: node => {\n const result = this.globals[node.name];\n return result === undefined ? null : result;\n },\n\n Function: (node, value) => {\n // Special case for if()\n // we need to make sure the results are called only after the condition is evaluated\n // Otherwise we end up with both results invoked -- which could include side effects\n // For \"if\", the last parameter to callFunction is false (bResolved) to indicate there's\n // no point in validating the argument type.\n if (node.name === 'if') return this.runtime.callFunction(node.name, node.children, value, this, false);\n const resolvedArgs = node.children.map(child => this.visit(child, value));\n return this.runtime.callFunction(node.name, resolvedArgs, value, this);\n },\n\n ExpressionReference: node => {\n const [refNode] = node.children;\n // Tag the node with a specific attribute so the type\n // checker verify the type.\n refNode.jmespathType = TOK_EXPREF;\n return refNode;\n },\n };\n }\n\n visit(n, v = null) {\n const fn = n && this.visitFunctions[n.type];\n return fn(n, v);\n }\n\n // eslint-disable-next-line class-methods-use-this\n computeSliceParams(arrayLength, sliceParams) {\n function capSliceRange(arrayLen, actual, stp) {\n let actualValue = actual;\n if (actualValue < 0) {\n actualValue += arrayLen;\n if (actualValue < 0) {\n actualValue = stp < 0 ? -1 : 0;\n }\n } else if (actualValue >= arrayLen) {\n actualValue = stp < 0 ? arrayLen - 1 : arrayLen;\n }\n return actualValue;\n }\n\n let [start, stop, step] = sliceParams;\n if (step === null) {\n step = 1;\n } else if (step === 0) {\n throw evaluationError('Invalid slice, step cannot be 0');\n }\n const stepValueNegative = step < 0;\n\n if (start === null) {\n start = stepValueNegative ? arrayLength - 1 : 0;\n } else {\n start = capSliceRange(arrayLength, start, step);\n }\n\n if (stop === null) {\n stop = stepValueNegative ? -1 : arrayLength;\n } else {\n stop = capSliceRange(arrayLength, stop, step);\n }\n return [start, stop, step];\n }\n\n applyOperator(first, second, operator) {\n if (isArray(first) && isArray(second)) {\n const result = [];\n for (let i = 0; i < first.length; i += 1) {\n result.push(this.applyOperator(first[i], second[i], operator));\n }\n return result;\n }\n\n if (isArray(first)) return first.map(a => this.applyOperator(a, second, operator));\n if (isArray(second)) return second.map(a => this.applyOperator(first, a, operator));\n\n if (operator === '&') return first + second;\n if (operator === '*') return this.toNumber(first) * this.toNumber(second);\n const n1 = this.toNumber(first);\n const n2 = this.toNumber(second);\n if (operator === '+') return n1 + n2;\n if (operator === '-') return n1 - n2;\n // if (operator === '/') {\n // Must be division\n const result = n1 / n2;\n if (!Number.isFinite(result)) {\n throw evaluationError(`Division by zero ${first}/${second}`);\n }\n return result;\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-underscore-dangle */\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { syntaxError } from './errors.js';\n\nconst {\n TOK_IDENTIFIER,\n TOK_QUOTEDIDENTIFIER,\n TOK_RBRACKET,\n TOK_RPAREN,\n TOK_COMMA,\n TOK_COLON,\n TOK_CONCATENATE,\n TOK_RBRACE,\n TOK_NUMBER,\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_OR,\n TOK_COMPARATOR,\n TOK_AND,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_UNARY_MINUS,\n TOK_DIVIDE,\n TOK_UNION,\n TOK_FLATTEN,\n TOK_STAR,\n TOK_FILTER,\n TOK_DOT,\n TOK_NOT,\n TOK_LBRACE,\n TOK_LBRACKET,\n TOK_LPAREN,\n TOK_JSON,\n TOK_STRING,\n TOK_INT,\n} = tokenDefinitions;\n\n// The \"&\", \"[\", \"<\", \">\" tokens\n// are not in basicToken because\n// there are two token variants\n// (\"&&\", \"[?\", \"<=\", \">=\"). This is specially handled\n// below.\n\nconst basicTokens = {\n '.': TOK_DOT,\n ',': TOK_COMMA,\n ':': TOK_COLON,\n '{': TOK_LBRACE,\n '}': TOK_RBRACE,\n ']': TOK_RBRACKET,\n '(': TOK_LPAREN,\n ')': TOK_RPAREN,\n '@': TOK_CURRENT,\n};\n\nconst globalStartToken = '$';\nconst operatorStartToken = {\n '<': true,\n '>': true,\n '=': true,\n '!': true,\n};\n\nconst skipChars = {\n ' ': true,\n '\\t': true,\n '\\n': true,\n};\n\nfunction isAlphaNum(ch) {\n return (ch >= 'a' && ch <= 'z')\n || (ch >= 'A' && ch <= 'Z')\n || (ch >= '0' && ch <= '9')\n || ch === '_';\n}\n\nfunction isIdentifier(stream, pos) {\n const ch = stream[pos];\n // $ is special -- it's allowed to be part of an identifier if it's the first character\n // return whether character 'isAlpha'\n return ch === '$'\n || (ch >= 'a' && ch <= 'z')\n || (ch >= 'A' && ch <= 'Z')\n || ch === '_';\n}\n\nexport default class Lexer {\n constructor(allowedGlobalNames = [], debug = []) {\n this._allowedGlobalNames = allowedGlobalNames;\n this.debug = debug;\n }\n\n tokenize(stream) {\n const tokens = [];\n this._current = 0;\n let start;\n let identifier;\n let token;\n while (this._current < stream.length) {\n const prev = tokens.length ? tokens.slice(-1)[0].type : null;\n\n if (this._isGlobal(prev, stream, this._current)) {\n tokens.push(this._consumeGlobal(stream));\n } else if (isIdentifier(stream, this._current)) {\n start = this._current;\n identifier = this._consumeUnquotedIdentifier(stream);\n tokens.push({\n type: TOK_IDENTIFIER,\n value: identifier,\n start,\n });\n } else if (this._isNumber(stream)) {\n token = this._consumeNumber(stream);\n tokens.push(token);\n } else if (basicTokens[stream[this._current]] !== undefined) {\n tokens.push({\n type: basicTokens[stream[this._current]],\n value: stream[this._current],\n start: this._current,\n });\n this._current += 1;\n } else if (stream[this._current] === '-' && ![TOK_GLOBAL, TOK_CURRENT, TOK_NUMBER, TOK_INT, TOK_RPAREN, TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_RBRACKET, TOK_JSON, TOK_STRING].includes(prev)) {\n token = this._consumeUnaryMinus(stream);\n tokens.push(token);\n } else if (stream[this._current] === '[') {\n // No need to increment this._current. This happens\n // in _consumeLBracket\n token = this._consumeLBracket(stream);\n tokens.push(token);\n } else if (stream[this._current] === \"'\") {\n start = this._current;\n identifier = this._consumeQuotedIdentifier(stream);\n tokens.push({\n type: TOK_QUOTEDIDENTIFIER,\n value: identifier,\n start,\n });\n } else if (stream[this._current] === '\"') {\n start = this._current;\n identifier = this._consumeRawStringLiteral(stream);\n tokens.push({\n type: TOK_STRING,\n value: identifier,\n start,\n });\n } else if (stream[this._current] === '`') {\n start = this._current;\n const json = this._consumeJson(stream);\n tokens.push({\n type: TOK_JSON,\n value: json,\n start,\n });\n } else if (operatorStartToken[stream[this._current]] !== undefined) {\n tokens.push(this._consumeOperator(stream));\n } else if (skipChars[stream[this._current]] !== undefined) {\n // Ignore whitespace.\n this._current += 1;\n } else if (stream[this._current] === '&') {\n start = this._current;\n this._current += 1;\n if (stream[this._current] === '&') {\n this._current += 1;\n tokens.push({ type: TOK_AND, value: '&&', start });\n } else if (prev === TOK_COMMA || prev === TOK_LPAREN) {\n // based on previous token we'll know if this & is a JMESPath expression-type\n // or if it's a concatenation operator\n // if we're a function arg then it's an expression-type\n tokens.push({ type: TOK_EXPREF, value: '&', start });\n } else {\n tokens.push({ type: TOK_CONCATENATE, value: '&', start });\n }\n } else if (stream[this._current] === '~') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_UNION, value: '~', start });\n } else if (stream[this._current] === '+') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_ADD, value: '+', start });\n } else if (stream[this._current] === '-') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_SUBTRACT, value: '-', start });\n } else if (stream[this._current] === '*') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_STAR, value: '*', start });\n } else if (stream[this._current] === '/') {\n start = this._current;\n this._current += 1;\n tokens.push({ type: TOK_DIVIDE, value: '/', start });\n } else if (stream[this._current] === '|') {\n start = this._current;\n this._current += 1;\n if (stream[this._current] === '|') {\n this._current += 1;\n tokens.push({ type: TOK_OR, value: '||', start });\n } else {\n tokens.push({ type: TOK_PIPE, value: '|', start });\n }\n } else {\n throw syntaxError(`Unknown character:${stream[this._current]}`);\n }\n }\n return tokens;\n }\n\n _consumeUnquotedIdentifier(stream) {\n const start = this._current;\n this._current += 1;\n while (\n this._current < stream.length\n && (stream[this._current] === '$' || isAlphaNum(stream[this._current]))\n ) {\n this._current += 1;\n }\n return stream.slice(start, this._current);\n }\n\n _consumeQuotedIdentifier(stream) {\n const start = this._current;\n this._current += 1;\n const maxLength = stream.length;\n let foundNonAlpha = !isIdentifier(stream, start + 1);\n while (stream[this._current] !== \"'\" && this._current < maxLength) {\n // You can escape a single quote and you can escape an escape.\n let current = this._current;\n if (!isAlphaNum(stream[current])) foundNonAlpha = true;\n if (stream[current] === '\\\\' && (stream[current + 1] === '\\\\'\n || stream[current + 1] === \"'\")) {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n this._current += 1;\n const val = stream.slice(start, this._current);\n // Check for unnecessary single quotes.\n // json-formula uses single quotes to escape characters that don't belong in names.\n // e.g. \"purchase-order\".address\n // If we find a single-quoted entity with spaces or all legal characters, issue a warning\n try {\n if (!foundNonAlpha) {\n this.debug.push(`Suspicious quotes: ${val}`);\n this.debug.push(`Did you intend a literal? \"${val.replace(/'/g, '')}\"?`);\n }\n // eslint-disable-next-line no-empty\n } catch (e) { }\n // we want to do all the escape-processing that JSON does ...\n // except that JSON expects to escape double quotes, and our identifiers\n // escape single quotes.\n return JSON.parse(`\"${val.substring(1, val.length - 1).replace(/\\\\'/g, \"'\")}\"`);\n }\n\n _consumeRawStringLiteral(stream) {\n const start = this._current;\n this._current += 1;\n const maxLength = stream.length;\n while (stream[this._current] !== '\"' && this._current < maxLength) {\n // You can escape a double quote and you can escape an escape.\n let current = this._current;\n if (stream[current] === '\\\\' && (stream[current + 1] === '\\\\'\n || stream[current + 1] === '\"')) {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n this._current += 1;\n const literal = stream.slice(start + 1, this._current - 1);\n if (this._current > maxLength) {\n throw syntaxError(`Unterminated string literal at ${start}, \"${literal}`);\n }\n try {\n return JSON.parse(`\"${literal}\"`);\n } catch (_e) {\n throw syntaxError(`Invalid string literal: ${literal}`);\n }\n }\n\n _isNumber(stream) {\n // if we see the first two characters are either a digit or radix, then we have a number\n let ch = stream[this._current];\n if (ch >= '0' && ch <= '9') return true;\n if (ch !== '.') return false;\n if (this._current === stream.length) return false;\n ch = stream[this._current + 1];\n return ch >= '0' && ch <= '9';\n }\n\n _consumeNumber(stream) {\n const start = this._current;\n const num = stream.slice(start);\n const match = num.match(/^[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?/);\n if (!match) throw syntaxError(`Invalid number: ${num}`);\n const n = match[0];\n this._current += n.length;\n let value;\n if (n.includes('.') || n.toLowerCase().includes('e')) {\n value = parseFloat(n);\n return { type: TOK_NUMBER, value, start };\n }\n value = parseInt(n, 10);\n return { type: TOK_INT, value, start };\n }\n\n _consumeUnaryMinus() {\n const start = this._current;\n this._current += 1;\n return { type: TOK_UNARY_MINUS, value: '-', start };\n }\n\n _consumeLBracket(stream) {\n const start = this._current;\n this._current += 1;\n if (stream[this._current] === '?') {\n this._current += 1;\n return { type: TOK_FILTER, value: '[?', start };\n }\n if (stream[this._current] === ']') {\n this._current += 1;\n return { type: TOK_FLATTEN, value: '[]', start };\n }\n return { type: TOK_LBRACKET, value: '[', start };\n }\n\n _isGlobal(prev, stream, pos) {\n // global tokens occur only at the start of an expression\n if (prev !== null && prev === TOK_DOT) return false;\n const ch = stream[pos];\n if (ch !== globalStartToken) return false;\n // $ is special -- it's allowed to be part of an identifier if it's the first character\n let i = pos + 1;\n while (i < stream.length && (stream[i] === '$' || isAlphaNum(stream[i]))) i += 1;\n const global = stream.slice(pos, i);\n return this._allowedGlobalNames.includes(global);\n }\n\n _consumeGlobal(stream) {\n const start = this._current;\n this._current += 1;\n while (this._current < stream.length\n && (stream[this._current] === '$' || isAlphaNum(stream[this._current]))) this._current += 1;\n const global = stream.slice(start, this._current);\n\n return { type: TOK_GLOBAL, name: global, start };\n }\n\n _consumeOperator(stream) {\n const start = this._current;\n const startingChar = stream[start];\n this._current += 1;\n if (startingChar === '!') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '!=', start };\n }\n return { type: TOK_NOT, value: '!', start };\n }\n if (startingChar === '<') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '<=', start };\n }\n if (stream[this._current] === '>') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '!=', start };\n }\n return { type: TOK_COMPARATOR, value: '<', start };\n }\n if (startingChar === '>') {\n if (stream[this._current] === '=') {\n this._current += 1;\n return { type: TOK_COMPARATOR, value: '>=', start };\n }\n return { type: TOK_COMPARATOR, value: '>', start };\n }\n // startingChar is '='\n if (stream[this._current] === '=') {\n this._current += 1;\n }\n return { type: TOK_COMPARATOR, value: '==', start };\n }\n\n _consumeJson(stream) {\n this._current += 1;\n const start = this._current;\n const maxLength = stream.length;\n while (stream[this._current] !== '`' && this._current < maxLength) {\n let current = this._current;\n if (stream[current] === '\\\\' && stream[current + 1] === '`') {\n current += 2;\n } else {\n current += 1;\n }\n this._current = current;\n }\n let literalString = stream.slice(start, this._current).trimStart();\n literalString = literalString.replaceAll('\\\\`', '`');\n // +1 gets us to the ending \"`\", +1 to move on to the next char.\n this._current += 1;\n if (this._current > maxLength) {\n throw syntaxError(`Unterminated JSON literal at ${start}: \\`${literalString}`);\n }\n\n return JSON.parse(literalString);\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport Lexer from './Lexer.js';\nimport tokenDefinitions from './tokenDefinitions.js';\nimport { syntaxError } from './errors.js';\n\n/* eslint-disable no-underscore-dangle */\nconst {\n TOK_JSON,\n TOK_COLON,\n TOK_EOF,\n TOK_IDENTIFIER,\n TOK_QUOTEDIDENTIFIER,\n TOK_RBRACKET,\n TOK_RPAREN,\n TOK_COMMA,\n TOK_CONCATENATE,\n TOK_RBRACE,\n TOK_NUMBER,\n TOK_CURRENT,\n TOK_GLOBAL,\n TOK_EXPREF,\n TOK_PIPE,\n TOK_OR,\n TOK_AND,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_UNARY_MINUS,\n TOK_MULTIPLY,\n TOK_DIVIDE,\n TOK_UNION,\n TOK_COMPARATOR,\n TOK_FLATTEN,\n TOK_STAR,\n TOK_FILTER,\n TOK_DOT,\n TOK_NOT,\n TOK_LBRACE,\n TOK_LBRACKET,\n TOK_LPAREN,\n TOK_STRING,\n TOK_INT,\n} = tokenDefinitions;\n\nconst bindingPower = {\n [TOK_EOF]: 0,\n [TOK_IDENTIFIER]: 0,\n [TOK_QUOTEDIDENTIFIER]: 0,\n [TOK_RBRACKET]: 0,\n [TOK_RPAREN]: 0,\n [TOK_COMMA]: 0,\n [TOK_RBRACE]: 0,\n [TOK_NUMBER]: 0,\n [TOK_INT]: 0,\n [TOK_CURRENT]: 0,\n [TOK_GLOBAL]: 0,\n [TOK_EXPREF]: 0,\n [TOK_PIPE]: 1,\n [TOK_OR]: 2,\n [TOK_AND]: 3,\n [TOK_COMPARATOR]: 4,\n [TOK_CONCATENATE]: 5,\n [TOK_ADD]: 6,\n [TOK_SUBTRACT]: 6,\n [TOK_UNION]: 6,\n [TOK_MULTIPLY]: 7,\n [TOK_DIVIDE]: 7,\n [TOK_NOT]: 8,\n [TOK_UNARY_MINUS]: 8,\n [TOK_FLATTEN]: 10,\n [TOK_STAR]: 20,\n [TOK_FILTER]: 21,\n [TOK_DOT]: 40,\n [TOK_LBRACE]: 50,\n [TOK_LBRACKET]: 55,\n [TOK_LPAREN]: 60,\n};\n\nexport default class Parser {\n constructor(allowedGlobalNames = []) {\n this._allowedGlobalNames = allowedGlobalNames;\n }\n\n parse(expression, debug) {\n this.debug = debug;\n this._loadTokens(expression);\n this.index = 0;\n const ast = this.expression(0);\n if (this._lookahead(0) !== TOK_EOF) {\n const t = this._lookaheadToken(0);\n throw syntaxError(`Unexpected token type: ${t.type}, value: ${t.value}`);\n }\n return ast;\n }\n\n _loadTokens(expression) {\n const lexer = new Lexer(this._allowedGlobalNames, this.debug);\n const tokens = lexer.tokenize(expression);\n tokens.push({ type: TOK_EOF, value: '', start: expression.length });\n this.tokens = tokens;\n }\n\n expression(rbp) {\n const leftToken = this._lookaheadToken(0);\n this._advance();\n let left = this.nud(leftToken);\n let currentToken = this._lookaheadToken(0, left);\n while (rbp < bindingPower[currentToken.type]) {\n this._advance();\n left = this.led(currentToken, left);\n currentToken = this._lookaheadToken(0, left);\n }\n return left;\n }\n\n _lookahead(number) {\n return this.tokens[this.index + number].type;\n }\n\n _lookaheadToken(number, previous = {}) {\n const next = this.tokens[this.index + number];\n // disambiguate multiply and star\n if (next.type === TOK_STAR) {\n if (![\n undefined,\n TOK_LBRACKET,\n TOK_DOT,\n TOK_PIPE,\n TOK_AND,\n TOK_OR,\n TOK_COMMA,\n TOK_NOT,\n TOK_MULTIPLY,\n TOK_ADD,\n TOK_SUBTRACT,\n TOK_DIVIDE,\n TOK_LPAREN,\n TOK_CONCATENATE,\n TOK_UNION,\n TOK_COMPARATOR].includes(previous.type)) {\n next.type = TOK_MULTIPLY;\n }\n }\n\n return next;\n }\n\n _advance() {\n this.index += 1;\n }\n\n _lookAheadIndex() {\n let idx = 0;\n if (this._lookahead(idx) === TOK_UNARY_MINUS) idx += 1;\n if (this._lookahead(idx) === TOK_INT) idx += 1;\n if (this._lookahead(idx) === TOK_RBRACKET\n || this._lookahead(idx) === TOK_COLON) return true;\n return false;\n }\n\n _getIndex() {\n return this.index;\n }\n\n _setIndex(index) {\n this.index = index;\n }\n\n // eslint-disable-next-line consistent-return\n nud(token) {\n let left;\n let right;\n let expression;\n let node;\n let args;\n switch (token.type) {\n case TOK_STRING:\n return { type: 'String', value: token.value };\n case TOK_JSON:\n return { type: 'Literal', value: token.value };\n case TOK_NUMBER:\n return { type: 'Number', value: token.value };\n case TOK_INT:\n return { type: 'Integer', value: token.value };\n case TOK_IDENTIFIER:\n return { type: 'Identifier', name: token.value };\n case TOK_QUOTEDIDENTIFIER:\n node = { type: 'QuotedIdentifier', name: token.value };\n return node;\n case TOK_NOT:\n right = this.expression(bindingPower.Not);\n return { type: 'NotExpression', children: [right] };\n case TOK_UNARY_MINUS:\n right = this.expression(bindingPower.UnaryMinus);\n return { type: 'UnaryMinusExpression', children: [right] };\n case TOK_STAR:\n left = { type: 'Identity' };\n if (this._lookahead(0) === TOK_RBRACKET) {\n // This can happen in a ArrayExpression,\n // [a, b, *]\n right = { type: 'Identity' };\n } else {\n right = this._parseProjectionRHS(bindingPower.Star);\n }\n return { type: 'ValueProjection', children: [left, right] };\n case TOK_FILTER:\n return this.led(token, { type: 'Identity' });\n case TOK_LBRACE:\n return this._parseObjectExpression();\n case TOK_FLATTEN:\n left = { type: TOK_FLATTEN, children: [{ type: 'Identity' }] };\n right = this._parseProjectionRHS(bindingPower.Flatten);\n return { type: 'Projection', children: [left, right] };\n case TOK_LBRACKET:\n if (this._lookAheadIndex()) {\n right = this._parseIndexExpression();\n return this._projectIfSlice({ type: 'Identity' }, right);\n }\n if (this._lookahead(0) === TOK_STAR && this._lookahead(1) === TOK_RBRACKET) {\n this._advance();\n this._advance();\n right = this._parseProjectionRHS(bindingPower.Star);\n return {\n type: 'Projection',\n children: [{ type: 'Identity' }, right],\n debug: 'Wildcard',\n };\n }\n return this._parseArrayExpression();\n\n case TOK_CURRENT:\n return { type: TOK_CURRENT };\n case TOK_GLOBAL:\n return { type: TOK_GLOBAL, name: token.name };\n case TOK_EXPREF:\n expression = this.expression(bindingPower.Expref);\n return { type: 'ExpressionReference', children: [expression] };\n case TOK_LPAREN:\n args = [];\n while (this._lookahead(0) !== TOK_RPAREN) {\n expression = this.expression(0);\n args.push(expression);\n }\n this._match(TOK_RPAREN);\n return args[0];\n default:\n this._errorToken(token);\n }\n }\n\n // eslint-disable-next-line consistent-return\n led(token, left) {\n let condition;\n let right;\n let name;\n let args;\n let node;\n let rbp;\n let leftNode;\n let rightNode;\n const tokenName = token.type;\n switch (tokenName) {\n case TOK_CONCATENATE:\n right = this.expression(bindingPower.Concatenate);\n return { type: 'ConcatenateExpression', children: [left, right] };\n case TOK_DOT:\n rbp = bindingPower.Dot;\n if (this._lookahead(0) !== TOK_STAR) {\n right = this._parseDotRHS(rbp);\n return { type: 'ChainedExpression', children: [left, right] };\n }\n // Creating a projection.\n this._advance();\n right = this._parseProjectionRHS(rbp);\n return { type: 'ValueProjection', children: [left, right] };\n case TOK_PIPE:\n right = this.expression(bindingPower.Pipe);\n return { type: TOK_PIPE, children: [left, right] };\n case TOK_OR:\n right = this.expression(bindingPower.Or);\n return { type: 'OrExpression', children: [left, right] };\n case TOK_AND:\n right = this.expression(bindingPower.And);\n return { type: 'AndExpression', children: [left, right] };\n case TOK_ADD:\n right = this.expression(bindingPower.Add);\n return { type: 'AddExpression', children: [left, right] };\n case TOK_SUBTRACT:\n right = this.expression(bindingPower.Subtract);\n return { type: 'SubtractExpression', children: [left, right] };\n case TOK_MULTIPLY:\n right = this.expression(bindingPower.Multiply);\n return { type: 'MultiplyExpression', children: [left, right] };\n case TOK_DIVIDE:\n right = this.expression(bindingPower.Divide);\n return { type: 'DivideExpression', children: [left, right] };\n case TOK_UNION:\n right = this.expression(bindingPower.Union);\n return { type: 'UnionExpression', children: [left, right] };\n case TOK_LPAREN:\n if (left.type !== TOK_IDENTIFIER) {\n throw syntaxError('Bad function syntax. Parenthesis must be preceded by an unquoted identifier');\n }\n name = left.name;\n args = this._parseFunctionArgs();\n node = { type: 'Function', name, children: args };\n return node;\n case TOK_FILTER:\n condition = this.expression(0);\n this._match(TOK_RBRACKET);\n right = this._parseProjectionRHS(bindingPower.Filter);\n return { type: 'FilterProjection', children: [left, right, condition] };\n case TOK_FLATTEN:\n leftNode = { type: TOK_FLATTEN, children: [left] };\n rightNode = this._parseProjectionRHS(bindingPower.Flatten);\n return { type: 'Projection', children: [leftNode, rightNode] };\n case TOK_COMPARATOR:\n return this._parseComparator(left, token);\n case TOK_LBRACKET:\n if (this._lookahead(0) === TOK_STAR\n && this._lookahead(1) === TOK_RBRACKET) {\n this._advance();\n this._advance();\n right = this._parseProjectionRHS(bindingPower.Star);\n return { type: 'Projection', children: [left, right], debug: 'Wildcard' };\n }\n right = this._parseIndexExpression();\n return this._projectIfSlice(left, right);\n default:\n this._errorToken(token);\n }\n }\n\n _match(tokenType) {\n const token = this._lookaheadToken(0);\n if (token.type === tokenType) {\n this._advance();\n return token;\n }\n throw syntaxError(`Expected ${tokenType}, got: ${token.type}`);\n }\n\n // eslint-disable-next-line class-methods-use-this\n _errorToken(token) {\n throw syntaxError(`Unexpected token (${\n token.type}): \"${\n token.value || token.name}\"`);\n }\n\n _parseFunctionArgs() {\n let firstExpression = true;\n const args = [];\n while (this._lookahead(0) !== TOK_RPAREN) {\n if (!firstExpression) {\n this._match(TOK_COMMA);\n }\n args.push(this.expression(0));\n firstExpression = false;\n }\n this._match(TOK_RPAREN);\n return args;\n }\n\n _parseSignedInt() {\n const first = this._lookaheadToken(0);\n if (first.type === TOK_UNARY_MINUS) {\n this._advance();\n const value = this._match(TOK_INT);\n return {\n type: 'SignedInt',\n value: -value.value,\n };\n }\n if (first.type !== TOK_INT) this._errorToken(first);\n this._advance();\n return {\n type: 'SignedInt',\n value: first.value,\n };\n }\n\n _parseIndexExpression() {\n const oldIndex = this._getIndex();\n if (this._lookahead(0) === TOK_COLON) {\n return this._parseSliceExpression();\n }\n // look ahead of the first expression to determine the type\n const first = this._parseSignedInt();\n const token = this._lookahead(0);\n if (token === TOK_COLON) {\n // now that we know the type revert back to the old position and parse\n this._setIndex(oldIndex);\n return this._parseSliceExpression();\n }\n this._match(TOK_RBRACKET);\n return {\n type: 'Index',\n value: first,\n };\n }\n\n _projectIfSlice(left, right) {\n const indexExpr = { type: 'BracketExpression', children: [left, right] };\n if (right.type === 'Slice') {\n return {\n type: 'Projection',\n children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)],\n };\n }\n return indexExpr;\n }\n\n _parseSliceExpression() {\n // [start:end:step] where each part is optional, as well as the last\n // colon.\n const parts = [null, null, null];\n let index = 0;\n let currentToken = this._lookahead(0);\n while (currentToken !== TOK_RBRACKET && index < 3) {\n if (currentToken === TOK_COLON && index < 2) { // there can't be more than 2 colons\n index += 1;\n this._advance();\n } else {\n parts[index] = this._parseSignedInt();\n // check next token to be either colon or rbracket\n const t = this._lookahead(0);\n if (t !== TOK_COLON && t !== TOK_RBRACKET) {\n throw syntaxError(`Unexpected token: ${\n t.value}(${t.type})`);\n }\n }\n currentToken = this._lookahead(0);\n }\n this._match(TOK_RBRACKET);\n return {\n type: 'Slice',\n children: parts,\n };\n }\n\n _parseComparator(left, comparator) {\n const right = this.expression(bindingPower[comparator.type]);\n return { type: 'Comparator', value: comparator.value, children: [left, right] };\n }\n\n _parseDotRHS(rbp) {\n const lookahead = this._lookahead(0);\n const exprTokens = [TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];\n if (exprTokens.indexOf(lookahead) >= 0) {\n return this.expression(rbp);\n }\n if (lookahead === TOK_LBRACKET) {\n this._match(TOK_LBRACKET);\n return this._parseArrayExpression();\n }\n if (lookahead === TOK_LBRACE) {\n this._match(TOK_LBRACE);\n return this._parseObjectExpression();\n }\n throw syntaxError('Expecting one of: \"*\", \"[\", \"{\", name or quoted name after a dot');\n }\n\n _parseProjectionRHS(rbp) {\n let right;\n const next = this._lookaheadToken(0, { type: TOK_STAR });\n if (bindingPower[next.type] <= bindingPower[TOK_FLATTEN]) {\n right = { type: 'Identity' };\n } else if (next.type === TOK_LBRACKET) {\n right = this.expression(rbp);\n } else if (next.type === TOK_FILTER) {\n right = this.expression(rbp);\n } else if (next.type === TOK_DOT) {\n this._match(TOK_DOT);\n right = this._parseDotRHS(rbp);\n } else {\n throw syntaxError(`Unexpected token: ${next.value}(${next.type})`);\n }\n return right;\n }\n\n _parseArrayExpression() {\n const expressions = [];\n while (this._lookahead(0) !== TOK_RBRACKET) {\n const expression = this.expression(0);\n expressions.push(expression);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n if (this._lookahead(0) === TOK_RBRACKET) {\n throw syntaxError('Unexpected token Rbracket');\n }\n }\n }\n this._match(TOK_RBRACKET);\n return { type: 'ArrayExpression', children: expressions };\n }\n\n _parseObjectExpression() {\n const pairs = [];\n const identifierTypes = [TOK_IDENTIFIER, TOK_QUOTEDIDENTIFIER];\n let keyToken; let keyName; let value; let\n node;\n if (this._lookahead(0) === TOK_RBRACE) {\n this.debug.push('To create an empty object, use a JSON literal: `{}`');\n throw syntaxError('An empty object expression is not allowed');\n }\n for (;;) {\n keyToken = this._lookaheadToken(0);\n if (identifierTypes.indexOf(keyToken.type) < 0) {\n throw syntaxError(`Expecting an identifier token, got: ${\n keyToken.type}`);\n }\n keyName = keyToken.value;\n this._advance();\n this._match(TOK_COLON);\n value = this.expression(0);\n node = { type: 'KeyValuePair', name: keyName, value };\n pairs.push(node);\n if (this._lookahead(0) === TOK_COMMA) {\n this._match(TOK_COMMA);\n } else if (this._lookahead(0) === TOK_RBRACE) {\n this._match(TOK_RBRACE);\n break;\n }\n }\n return { type: 'ObjectExpression', children: pairs };\n }\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-underscore-dangle */\nimport { dataTypes, typeNameTable } from './dataTypes.js';\nimport {\n getProperty, debugAvailable, toBoolean, strictDeepEqual,\n} from './utils.js';\nimport { evaluationError, functionError, typeError } from './errors.js';\n\nfunction round(num, digits) {\n const precision = 10 ** digits;\n return Math.round(num * precision) / precision;\n}\n\nconst MS_IN_DAY = 24 * 60 * 60 * 1000;\n\nfunction getDateObj(dateNum) {\n return new Date(Math.round(dateNum * MS_IN_DAY));\n}\n\nfunction getDateNum(dateObj) {\n return dateObj / MS_IN_DAY;\n}\n\nfunction validNumber(n, context) {\n if (Number.isNaN(n) || !Number.isFinite(n)) {\n throw evaluationError(`Call to \"${context}()\" resulted in an invalid number`);\n }\n return n;\n}\n\nexport default function functions(\n runtime,\n isObject,\n toNumber,\n getType,\n isArrayType,\n valueOf,\n toString,\n debug,\n) {\n const {\n TYPE_NUMBER,\n TYPE_ANY,\n TYPE_STRING,\n TYPE_ARRAY,\n TYPE_OBJECT,\n TYPE_BOOLEAN,\n TYPE_EXPREF,\n TYPE_NULL,\n TYPE_ARRAY_NUMBER,\n TYPE_ARRAY_STRING,\n TYPE_ARRAY_ARRAY,\n } = dataTypes;\n\n function toInteger(num) {\n let n = valueOf(num);\n // functions that require an integer parameter will have declared\n // the parameters as a number, so any strings will have already been\n // converted to number before the function call.\n // However, a few functions accept a string | integer. Attempt to convert\n // to integer in these cases, but failure isn't an error.\n if (getType(n) === TYPE_STRING) n = toNumber(n);\n n = Math.trunc(num);\n if (Number.isNaN(n)) return num;\n return n;\n }\n\n function toJSON(arg, indent) {\n const value = valueOf(arg);\n if (getType(value) === TYPE_STRING) {\n return arg;\n }\n const offset = indent ? toInteger(indent) : 0;\n return JSON.stringify(value, null, offset);\n }\n\n function balanceArrays(listOfArrays) {\n const maxLen = Math.max(...listOfArrays.map(a => (Array.isArray(a) ? a.length : 0)));\n const allArrays = listOfArrays.map(a => {\n if (Array.isArray(a)) {\n return a.concat(Array(maxLen - a.length).fill(null));\n }\n return Array(maxLen).fill(a);\n });\n // convolve allArrays\n const arrays = [];\n for (let i = 0; i < maxLen; i += 1) {\n const row = [];\n for (let j = 0; j < allArrays.length; j += 1) {\n row.push(allArrays[j][i]);\n }\n arrays.push(row);\n }\n return arrays;\n }\n\n function evaluate(args, fn) {\n if (args.some(Array.isArray)) {\n return balanceArrays(args).map(a => evaluate(a, fn));\n }\n return fn(...args);\n }\n\n function datedifFn(date1Arg, date2Arg, unitArg) {\n const unit = toString(unitArg).toLowerCase();\n const date1 = getDateObj(date1Arg);\n const date2 = getDateObj(date2Arg);\n if (date2 === date1) return 0;\n if (date2 < date1) throw functionError('end_date must be >= start_date in datedif()');\n\n if (unit === 'd') return Math.floor(getDateNum(date2 - date1));\n const yearDiff = date2.getFullYear() - date1.getFullYear();\n let monthDiff = date2.getMonth() - date1.getMonth();\n const dayDiff = date2.getDate() - date1.getDate();\n\n if (unit === 'y') {\n let y = yearDiff;\n if (monthDiff < 0) y -= 1;\n if (monthDiff === 0 && dayDiff < 0) y -= 1;\n return y;\n }\n if (unit === 'm') {\n return yearDiff * 12 + monthDiff + (dayDiff < 0 ? -1 : 0);\n }\n if (unit === 'ym') {\n if (dayDiff < 0) monthDiff -= 1;\n if (monthDiff <= 0 && yearDiff > 0) return 12 + monthDiff;\n return monthDiff;\n }\n if (unit === 'yd') {\n if (dayDiff < 0) monthDiff -= 1;\n if (monthDiff < 0) date2.setFullYear(date1.getFullYear() + 1);\n else date2.setFullYear(date1.getFullYear());\n return Math.floor(getDateNum(date2 - date1));\n }\n throw functionError(`Unrecognized unit parameter \"${unit}\" for datedif()`);\n }\n\n function endsWithFn(searchArg, suffixArg) {\n const searchStr = valueOf(searchArg);\n const suffix = valueOf(suffixArg);\n // make sure the comparison is based on code points\n const search = Array.from(searchStr).reverse();\n const ending = Array.from(suffix).reverse();\n return ending.every((c, i) => c === search[i]);\n }\n\n function eomonthFn(dateArg, monthsArg) {\n const jsDate = getDateObj(dateArg);\n const months = toInteger(monthsArg);\n // We can give the constructor a month value > 11 and it will increment the years\n // Since day is 1-based, giving zero will yield the last day of the previous month\n const newDate = new Date(jsDate.getFullYear(), jsDate.getMonth() + months + 1, 0);\n return getDateNum(newDate);\n }\n\n function findFn(queryArg, textArg, offsetArg) {\n const query = Array.from(toString(queryArg));\n const text = Array.from(toString(textArg));\n const offset = toInteger(offsetArg);\n if (offset < 0) throw evaluationError('find() start position must be >= 0');\n if (query.length === 0) {\n // allow an empty string to be found at any position -- including the end\n if (offset > text.length) return null;\n return offset;\n }\n for (let i = offset; i < text.length; i += 1) {\n if (text.slice(i, i + query.length).every((c, j) => c === query[j])) {\n return i;\n }\n }\n return null;\n }\n\n function properFn(arg) {\n const capitalize = word => `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`;\n const original = toString(arg);\n // split the string by whitespace, punctuation, and numbers\n const wordParts = original.match(/[\\s\\d\\p{P}]+|[^\\s\\d\\p{P}]+/gu);\n if (wordParts !== null) return wordParts.map(w => capitalize(w)).join('');\n return capitalize(original);\n }\n\n function reptFn(textArg, countArg) {\n const text = toString(textArg);\n const count = toInteger(countArg);\n if (count < 0) throw evaluationError('rept() count must be greater than or equal to 0');\n return text.repeat(count);\n }\n\n function searchFn(findTextString, withinTextString, startPosInt = 0) {\n const findText = toString(findTextString);\n const withinText = toString(withinTextString);\n const startPos = toInteger(startPosInt);\n if (startPos < 0) throw functionError('search() startPos must be greater than or equal to 0');\n if (findText === null || withinText === null || withinText.length === 0) return [];\n\n // Process as an array of code points\n // Find escapes and wildcards\n const globString = Array.from(findText).reduce((acc, cur) => {\n if (acc.escape) return { escape: false, result: acc.result.concat(cur) };\n if (cur === '\\\\') return { escape: true, result: acc.result };\n if (cur === '?') return { escape: false, result: acc.result.concat('dot') };\n if (cur === '*') {\n // consecutive * are treated as a single *\n if (acc.result.slice(-1).pop() === 'star') return acc;\n return { escape: false, result: acc.result.concat('star') };\n }\n return { escape: false, result: acc.result.concat(cur) };\n }, { escape: false, result: [] }).result;\n\n const testMatch = (array, glob, match) => {\n // we've consumed the entire glob, so we're done\n if (glob.length === 0) return match;\n // we've consumed the entire array, but there's still glob left -- no match\n if (array.length === 0) return null;\n const testChar = array[0];\n let [globChar, ...nextGlob] = glob;\n const isStar = globChar === 'star';\n if (isStar) {\n // '*' is at the end of the match -- so we're done matching\n if (glob.length === 1) return match;\n // we'll check for a match past the * and if not found, we'll process the *\n [globChar, ...nextGlob] = glob.slice(1);\n }\n if (testChar === globChar || globChar === 'dot') {\n return testMatch(array.slice(1), nextGlob, match.concat(testChar));\n }\n // no match, so consume wildcard *\n if (isStar) return testMatch(array.slice(1), glob, match.concat(testChar));\n\n return null;\n };\n // process code points\n const within = Array.from(withinText);\n for (let i = startPos; i < within.length; i += 1) {\n const result = testMatch(within.slice(i), globString, []);\n if (result !== null) return [i, result.join('')];\n }\n return [];\n }\n\n function splitFn(strArg, separatorArg) {\n const str = toString(strArg);\n const separator = toString(separatorArg);\n // for empty separator, return an array of code points\n return separator.length === 0 ? Array.from(str) : str.split(separator);\n }\n\n function startsWithFn(subjectString, prefixString) {\n const subject = Array.from(toString(subjectString));\n const prefix = Array.from(toString(prefixString));\n if (prefix.length > subject.length) return false;\n for (let i = 0; i < prefix.length; i += 1) {\n if (prefix[i] !== subject[i]) return false;\n }\n return true;\n }\n\n function substituteFn(source, oldString, replacementString, nearest) {\n const src = Array.from(toString(source));\n const old = Array.from(toString(oldString));\n const replacement = Array.from(toString(replacementString));\n\n if (old.length === 0) return source;\n\n // no third parameter? replace all instances\n let replaceAll = true;\n let whch = 0;\n if (nearest > -1) {\n replaceAll = false;\n whch = nearest + 1;\n }\n\n let found = 0;\n const result = [];\n // find the instances to replace\n for (let j = 0; j < src.length;) {\n const match = old.every((c, i) => src[j + i] === c);\n if (match) found += 1;\n if (match && (replaceAll || found === whch)) {\n result.push(...replacement);\n j += old.length;\n } else {\n result.push(src[j]);\n j += 1;\n }\n }\n return result.join('');\n }\n\n function truncFn(number, d) {\n const digits = toInteger(d);\n\n const method = number >= 0 ? Math.floor : Math.ceil;\n return method(number * 10 ** digits) / 10 ** digits;\n }\n\n function weekdayFn(date, type) {\n const jsDate = getDateObj(date);\n const day = jsDate.getDay();\n // day is in range [0-7) with 0 mapping to sunday\n switch (toInteger(type)) {\n case 1:\n // range = [1, 7], sunday = 1\n return day + 1;\n case 2:\n // range = [1, 7] sunday = 7\n return ((day + 6) % 7) + 1;\n case 3:\n // range = [0, 6] sunday = 6\n return (day + 6) % 7;\n default:\n throw functionError(`Unsupported returnType: \"${type}\" for weekday()`);\n }\n }\n\n const functionMap = {\n // name: [function, ]\n // The can be:\n //\n // {\n // args: [[type1, type2], [type1, type2]],\n // variadic: true|false\n // }\n //\n // Each arg in the arg list is a list of valid types\n // (if the function is overloaded and supports multiple\n // types. If the type is \"any\" then no type checking\n // occurs on the argument. Variadic is optional\n // and if not provided is assumed to be false.\n /**\n * Find the absolute (non-negative) value of the provided argument `value`.\n * @param {number|number[]} value A numeric value\n * @return {number|number[]} If `value < 0`, returns `-value`, otherwise returns `value`\n * @function abs\n * @example\n * abs(-1) // returns 1\n */\n abs: {\n _func: args => evaluate(args, Math.abs),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n /**\n * Compute the inverse cosine (in radians) of a number.\n * @param {number|number[]} cosine A number between -1 and 1, inclusive,\n * representing the angle's cosine value.\n * @return {number|number[]} The inverse cosine angle in radians between 0 and PI\n * @function acos\n * @example\n * acos(0) => 1.5707963267948966\n */\n acos: {\n _func: args => evaluate(args, n => validNumber(Math.acos(n), 'acos')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Finds the logical AND result of all parameters.\n * If the parameters are not boolean they will be <<_type_coercion_rules,cast to boolean>>.\n * Note the related <<_and_operator, And Operator>>.\n * @param {any} firstOperand logical expression\n * @param {...any} [additionalOperands] any number of additional expressions\n * @returns {boolean} The logical result of applying AND to all parameters\n * @example\n * and(10 > 8, length(\"foo\") < 5) // returns true\n * and(`null`, length(\"foo\") < 5) // returns false\n * @function and\n */\n and: {\n _func: resolvedArgs => {\n let result = toBoolean(valueOf(resolvedArgs[0]));\n resolvedArgs.slice(1).forEach(arg => {\n result = result && toBoolean(valueOf(arg));\n });\n return result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n\n /**\n * Compute the inverse sine (in radians) of a number.\n * @param {number|number[]} sine A number between -1 and 1, inclusive,\n * representing the angle's sine value.\n * @return {number|number[]} The inverse sine angle in radians between -PI/2 and PI/2\n * @function asin\n * @example\n * Math.asin(0) => 0\n */\n asin: {\n _func: args => evaluate(args, n => validNumber(Math.asin(n), 'asin')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Compute the angle in the plane (in radians) between the positive\n * x-axis and the ray from (0, 0) to the point (x, y)\n * @param {number|number[]} y The y coordinate of the point\n * @param {number|number[]} x The x coordinate of the point\n * @return {number|number[]} The angle in radians (between -PI and PI),\n * between the positive x-axis and the ray from (0, 0) to the point (x, y).\n * @function atan2\n * @example\n * atan2(20,10) => 1.1071487177940904\n */\n atan2: {\n _func: args => evaluate(args, Math.atan2),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds the average of the elements in an array.\n * Non-numeric values (text, boolean, null, object) are ignored.\n * If there are nested arrays, they are flattened.\n * If the array is empty, an evaluation error is thrown\n * @param {any[]} elements array of values\n * @return {number} average value\n * @function avg\n * @example\n * avg([1, 2, 3]) // returns 2\n */\n avg: {\n _func: resolvedArgs => {\n let sum = 0;\n const filtered = resolvedArgs\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (filtered.length === 0) throw evaluationError('avg() requires at least one argument');\n filtered.forEach(a => {\n sum += a;\n });\n return sum / filtered.length;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Finds the average of the elements in an array, converting strings and booleans to number.\n * If any conversions to number fail, a type error is thrown.\n * If there are nested arrays, they are flattened.\n * If the array is empty, an evaluation error is thrown\n * @param {number[]} elements array of numeric values\n * @return {number} average value\n * @function avgA\n * @example\n * avgA([1, 2, \"3\", null()]) // returns 2\n */\n avgA: {\n _func: resolvedArgs => {\n let sum = 0;\n let filtered;\n try {\n filtered = resolvedArgs\n .flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n } catch (_e) {\n throw typeError('avgA() received non-numeric parameters');\n }\n if (filtered.length === 0) throw evaluationError('avg() requires at least one argument');\n filtered.forEach(a => {\n sum += a;\n });\n return sum / filtered.length;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Generates a lower-case string of the `input` string using locale-specific mappings.\n * e.g. Strings with German letter ß (eszett) can be compared to \"ss\"\n * @param {string|string[]} input string to casefold\n * @returns {string|string[]} A new string converted to lower case\n * @function casefold\n * @example\n * casefold(\"AbC\") // returns \"abc\"\n */\n casefold: {\n _func: (args, _data, interpreter) => evaluate(args, s => toString(s)\n .toLocaleUpperCase(interpreter.language)\n .toLocaleLowerCase(interpreter.language)),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Finds the next highest integer value of the argument `num` by rounding up if necessary.\n * i.e. ceil() rounds toward positive infinity.\n * @param {number|number[]} num numeric value\n * @return {integer|integer[]} The smallest integer greater than or equal to num\n * @function ceil\n * @example\n * ceil(10) // returns 10\n * ceil(10.4) // return 11\n\n */\n ceil: {\n _func: args => evaluate(args, Math.ceil),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n /**\n * Retrieve the first code point from a string\n * @param {string|string[]} str source string.\n * @return {integer|integer[]} Unicode code point value.\n * If the input string is empty, returns `null`.\n * @function codePoint\n * @example\n * codePoint(\"ABC\") // 65\n */\n codePoint: {\n _func: args => evaluate(args, arg => {\n const text = toString(arg);\n return text.length === 0 ? null : text.codePointAt(0);\n }),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Determines if the given `subject` contains `search`.\n * If `subject` is an array, this function returns true if one of the elements\n * in the array is equal to the `search` value. If `subject`\n * is a string, return true if the string contains the\n * `search` value.\n * @param {array|string} subject The element to be searched\n * @param {any} search element to find.\n * If `subject` is an array, search for an exact match for `search` in the array.\n * If `subject` is a string, `search` must also be a string.\n * @return {boolean} true if found\n * @function contains\n * @example\n * contains([1, 2, 3, 4], 2) // returns true\n * contains([1, 2, 3, 4], -1) // returns false\n * contains(\"Abcd\", \"d\") // returns true\n * contains(\"Abcd\", \"x\") // returns false\n\n */\n contains: {\n _func: resolvedArgs => {\n const subject = valueOf(resolvedArgs[0]);\n const search = valueOf(resolvedArgs[1]);\n if (isArrayType(resolvedArgs[0])) {\n return subject.some(s => strictDeepEqual(s, search));\n }\n const source = Array.from(subject);\n if (getType(search) !== TYPE_STRING) {\n throw typeError('contains() requires a string search value for string subjects');\n }\n if (search === '') return true;\n const searchLen = Array.from(search).length;\n for (let i = 0; i < source.length; i += 1) {\n if (source.slice(i, i + searchLen).join('') === search) return true;\n }\n return false;\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_ANY] }],\n },\n /**\n * Compute the cosine (in radians) of a number.\n * @param {number|number[]} angle A number representing an angle in radians\n * @return {number|number[]} The cosine of the angle, between -1 and 1, inclusive.\n * @function cos\n * @example\n * cos(1.0471975512) => 0.4999999999970535\n */\n cos: {\n _func: args => evaluate(args, Math.cos),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Return difference between two date values.\n * The measurement of the difference is determined by the `unit` parameter. One of:\n *\n * * `y` the number of whole years between `start_date` and `end_date`\n * * `m` the number of whole months between `start_date` and `end_date`.\n * * `d` the number of days between `start_date` and `end_date`\n * * `ym` the number of whole months between `start_date` and `end_date`\n * after subtracting whole years.\n * * `yd` the number of days between `start_date` and `end_date`, assuming `start_date`\n * and `end_date` were no more than one year apart\n * @param {number|number[]} start_date The starting <<_date_and_time_values, date/time value>>.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {number|number[]} end_date The end <<_date_and_time_values, date/time value>> -- must\n * be greater or equal to start_date. If not, an error will be thrown.\n * @param {string|string[]} unit Case-insensitive string representing the unit of\n * time to measure. An unrecognized unit will result in an error.\n * @returns {integer|integer[]} The number of days/months/years difference\n * @function datedif\n * @example\n * datedif(datetime(2001, 1, 1), datetime(2003, 1, 1), \"y\") // returns 2\n * datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), \"D\") // returns 805\n * // 805 days between June 1, 2001, and August 15, 2003\n * datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), \"YD\") // returns 75\n * // 75 days between June 1 and August 15, ignoring the years of the dates (75)\n */\n datedif: {\n _func: args => evaluate(args, datedifFn),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Generate a date/time value from individual date/time parts.\n * If any of the units are greater than their normal range,\n * the overflow will be added to the next greater unit.\n * e.g. specifying 25 hours will increment the day value by 1.\n * Similarly,\n * negative values will decrement the next greater unit.\n * e.g. datetime(year, month, day - 30) will return a date 30 days earlier.\n * @param {integer} year The year to use for date construction.\n * Values from 0 to 99 map to the years 1900 to 1999. All other values are the actual year\n * @param {integer} month The month: beginning with 1 for\n * January to 12 for December.\n * @param {integer} day The day of the month.\n * @param {integer} [hours=0] Integer value between 0 and 23 representing the hour of the day.\n * @param {integer} [minutes=0] Integer value representing the minute segment of a time.\n * @param {integer} [seconds=0] Integer value representing the second segment of a time.\n * @param {integer} [milliseconds=0] Integer value representing the\n * millisecond segment of a time.\n * @returns {number} A <<_date_and_time_values, date/time value>>\n * to be used with other date/time functions\n * @function datetime\n * @example\n * datetime(2010, 10, 10) // returns representation of October 10, 2010\n * datetime(2010, 2, 28) // returns representation of February 28, 2010\n * datetime(2023,13,5) | year(@) & \"/\" & month(@) // returns 2024/1\n */\n datetime: {\n _func: args => {\n const year = toInteger(args[0]);\n const month = toInteger(args[1]) - 1; // javascript months start from 0\n const day = toInteger(args[2]);\n const hours = args.length > 3 ? toInteger(args[3]) : 0;\n const minutes = args.length > 4 ? toInteger(args[4]) : 0;\n const seconds = args.length > 5 ? toInteger(args[5]) : 0;\n const ms = args.length > 6 ? toInteger(args[6]) : 0;\n\n const baseDate = new Date(year, month, day, hours, minutes, seconds, ms);\n\n return getDateNum(baseDate);\n },\n _signature: [\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the day of the month for a date value\n * @param {number|number[]} date <<_date_and_time_values, date/time value>> generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The day of the month ranging from 1 to 31.\n * @function day\n * @example\n * day(datetime(2008,5,23)) // returns 23\n */\n day: {\n _func: args => evaluate(args, a => getDateObj(a).getDate()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Debug a json-formula expression.\n * The `debug()` function allows users to inspect a sub-expression within a formula.\n * @param {any} arg The expression to return from `debug()` function,\n * and the default expression to be debugged. May be any type except an expression.\n * @param {any|expression} [displayValue=arg] Optionally override the value to be debugged.\n * `displayValue` may be an expression to\n * be evaluated with the context of `arg`.\n * @returns {any} The value of the `arg` parameter\n * @function debug\n * @example\n * avg(([1,2,3] * [2,3,4]).debug(@)).round(@,3) // 6.667\n * avg(debug([1,2,3] * [2,3,4],&\"average of: \" &toString(@))).round(@,3) // 6.667\n */\n debug: {\n _func: resolvedArgs => {\n const arg = resolvedArgs[0];\n if (resolvedArgs.length > 1) {\n if (getType(resolvedArgs[1]) === TYPE_EXPREF) {\n debug.push(runtime.interpreter.visit(resolvedArgs[1], arg));\n } else {\n debug.push(resolvedArgs[1]);\n }\n } else {\n debug.push(toJSON(resolvedArgs[0]));\n }\n return arg;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY, TYPE_EXPREF], optional: true },\n ],\n },\n\n /**\n * Performs a depth-first search of a nested hierarchy to\n * return an array of key values that match a `name`.\n * The name can be either a key into an object or an array index.\n * This is similar to the Descendant Accessor operator (`..`) from [E4X](https://ecma-international.org/publications-and-standards/standards/ecma-357/).\n * @param {object|array|null} object The starting object or array where we start the search\n * @param {string|integer} name The name (or index position) of the elements to find.\n * If `name` is a string, search for nested objects with a matching key.\n * If `name` is an integer, search for nested arrays with a matching index.\n * @returns {any[]} The array of matched elements\n * @function deepScan\n * @example\n * deepScan({a : {b1 : {c : 2}, b2 : {c : 3}}}, \"c\") // returns [2, 3]\n */\n deepScan: {\n _func: resolvedArgs => {\n const [source, n] = resolvedArgs;\n const [name, checkArrays] = getType(n) === TYPE_NUMBER\n ? [toInteger(n), true] : [toString(n), false];\n const items = [];\n function scan(node) {\n if (node === null) return;\n if (isArrayType(node)) {\n if (checkArrays && node[name] !== undefined) items.push(node[name]);\n node.forEach(scan);\n } else if (isObject(node)) {\n Object.entries(node).forEach(([k, v]) => {\n if (!checkArrays && k === name) items.push(v);\n scan(v);\n });\n }\n }\n scan(source);\n return items;\n },\n _signature: [\n { types: [TYPE_OBJECT, TYPE_ARRAY, TYPE_NULL] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n\n /**\n * Determines if the `subject` string ends with a specific `suffix`\n * @param {string|string[]} subject source string in which to search\n * @param {string|string[]} suffix search string\n * @return {boolean|boolean[]} true if the `suffix` value is at the end of the `subject`\n * @function endsWith\n * @example\n * endsWith(\"Abcd\", \"d\") // returns true\n * endsWith(\"Abcd\", \"A\") // returns false\n */\n endsWith: {\n _func: args => evaluate(args, endsWithFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Returns an array of `[key, value]` pairs from an object or array.\n * The `fromEntries()` function may be used to convert an array to an object.\n * @param {object|array} obj source object or array\n * @returns {any[]} an array of arrays where each child array has two elements\n * representing the key and value of a pair\n * @function entries\n * @example\n * entries({a: 1, b: 2}) // returns [[\"a\", 1], [\"b\", 2]]\n * entries([4,5]) // returns [[\"0\", 4],[\"1\", 5]]\n */\n entries: {\n _func: args => {\n const obj = valueOf(args[0]);\n return Object.entries(obj);\n },\n _signature: [\n {\n types: [\n TYPE_ARRAY,\n TYPE_OBJECT,\n ],\n },\n ],\n },\n\n /**\n * Finds the date value of the end of a month, given `startDate` plus `monthAdd` months\n * @param {number|number[]} startDate The base date to start from.\n * <<_date_and_time_values, Date/time values>> can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {integer|integer[]} monthAdd Number of months to add to start date\n * @return {number|number[]} the date of the last day of the month\n * @function eomonth\n * @example\n * eomonth(datetime(2011, 1, 1), 1) | [month(@), day(@)] // returns [2, 28]\n * eomonth(datetime(2011, 1, 1), -3) | [month(@), day(@)] // returns [10, 31]\n */\n eomonth: {\n _func: args => evaluate(args, eomonthFn),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds e (the base of natural logarithms) raised to a power. (i.e. e^x)\n * @param {number|number[]} x A numeric expression representing the power of e.\n * @returns {number|number[]} e (the base of natural logarithms) raised to power x\n * @function exp\n * @example\n * exp(10) // returns 22026.465794806718\n */\n exp: {\n _func: args => evaluate(args, Math.exp),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Return constant boolean false value.\n * Expressions may also use the JSON literal: `` `false` ``\n * @returns {boolean} constant boolean value `false`\n * @function false\n */\n false: {\n _func: () => false,\n _signature: [],\n },\n\n /**\n * Finds and returns the index of query in text from a start position\n * @param {string|string[]} findText string to search\n * @param {string|string[]} withinText text to be searched\n * @param {integer|integer[]} [start=0] zero-based position to start searching.\n * If specified, `start` must be greater than or equal to 0\n * @returns {integer|null|integer[]} The position of the found string, null if not found.\n * @function find\n * @example\n * find(\"m\", \"abm\") // returns 2\n * find(\"M\", \"abMcdM\", 3) // returns 5\n * find(\"M\", \"ab\") // returns `null`\n * find(\"M\", \"abMcdM\", 2) // returns 2\n */\n find: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 3) args.push(0);\n return evaluate(args, findFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the next lowest integer value of the argument `num` by rounding down if necessary.\n * i.e. floor() rounds toward negative infinity.\n * @param {number|number[]} num numeric value\n * @return {integer|integer[]} The largest integer smaller than or equal to num\n * @function floor\n * @example\n * floor(10.4) // returns 10\n * floor(10) // returns 10\n */\n floor: {\n _func: args => evaluate(args, Math.floor),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Create a string from a code point.\n * @param {integer|integer[]} codePoint An integer or array of integers\n * between 0 and 0x10FFFF (inclusive) representing Unicode code point(s).\n * @return {string} A string from the given code point(s)\n * @function fromCodePoint\n * @example\n * fromCodePoint(65) // \"A\"\n * fromCodePoint(65) == \"\\u0041\" // true\n */\n fromCodePoint: {\n _func: args => {\n try {\n const points = Array.isArray(args[0]) ? args[0] : [args[0]];\n return String.fromCodePoint(...points.map(toInteger));\n } catch (e) {\n throw evaluationError(`Invalid code point: \"${args[0]}\"`);\n }\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Returns an object by transforming a list of key-value `pairs` into an object.\n * `fromEntries()` is the inverse operation of `entries()`.\n * If the nested arrays are not of the form: `[key, value]`\n * (where key is a string), an error will be thrown.\n * @param {any[]} pairs A nested array of key-value pairs to create the object from\n * The nested arrays must have exactly two values, where the first value is a string.\n * If a key is specified more than once, the last occurrence will override any previous value.\n * @returns {object} An object constructed from the provided key-value pairs\n * @function fromEntries\n * @example\n * fromEntries([[\"a\", 1], [\"b\", 2]]) // returns {a: 1, b: 2}\n */\n fromEntries: {\n _func: args => {\n const array = args[0];\n // validate beyond the TYPE_ARRAY_ARRAY check\n if (!array.every(a => {\n if (!Array.isArray(a)) return false;\n if (a.length !== 2) return false;\n if (getType(a[0]) !== TYPE_STRING) return false;\n return true;\n })) {\n throw typeError('fromEntries() requires an array of key value pairs');\n }\n return Object.fromEntries(array);\n },\n _signature: [\n { types: [TYPE_ARRAY_ARRAY, TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Compute the nearest 32-bit single precision float representation of a number\n * @param {number|number[]} num input to be rounded\n * @return {number|number[]} The rounded representation of `num`\n * @function fround\n * @example\n * fround(2147483650.987) => 2147483648\n * fround(100.44444444444444444444) => 100.44444274902344\n */\n fround: {\n _func: args => evaluate(args, Math.fround),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Determine if an object has a property or if an array index is in range.\n * @param {object|array|null} subject source object or array.\n * When querying for <<_hidden_properties,hidden properties>>, `subject` may be any data type.\n * @param {string|integer} name The name (or index position) of the element to find.\n * if `subject` is an array, `name` must be an integer;\n * if `subject` is an object, `name` must be a string.\n * @returns {boolean} true if the element exists\n * @function hasProperty\n * @example\n * hasProperty({a: 1, b: 2}, \"a\") // returns true\n * hasProperty([\"apples\", \"oranges\"], 3) // returns false\n * hasProperty(`null`, \"a\") // returns false\n */\n hasProperty: {\n _func: args => {\n let key = args[1];\n const keyType = getType(key);\n\n // if the object/array has a getter for this property then don't validate types\n if (args[0] !== null && Object.getOwnPropertyDescriptor(args[0], key)?.get) return true;\n const obj = valueOf(args[0]);\n if (obj === null) return false;\n const isArray = isArrayType(obj);\n if (!(isArray || getType(obj) === TYPE_OBJECT)) {\n throw typeError('First parameter to hasProperty() must be either an object or array.');\n }\n\n if (isArray) {\n if (keyType !== TYPE_NUMBER) throw TypeError('hasProperty(): Array index must be an integer');\n key = toInteger(key);\n } else if (keyType !== TYPE_STRING) throw TypeError('hasProperty(): Object key must be a string');\n const result = getProperty(obj, key);\n return result !== undefined;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n /**\n * Extract the hour from a <<_date_and_time_values, date/time value>>\n * @param {number|number[]} date The datetime/time for which the hour is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} value between 0 and 23\n * @function hour\n * @example\n * hour(datetime(2008,5,23,12, 0, 0)) // returns 12\n * hour(time(12, 0, 0)) // returns 12\n */\n hour: {\n _func: args => evaluate(args, a => getDateObj(a).getHours()),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Return one of two values `result1` or `result2`, depending on the `condition`\n * @param {any} condition boolean result of a logical expression\n * @param {any} result1 if condition is true\n * @param {any} result2 if condition is false\n * @return {any} either result1 or result2\n * @function if\n\n * @example\n * if(true(), 1, 2) // returns 1\n * if(false(), 1, 2) // returns 2\n */\n if: {\n _func: (unresolvedArgs, data, interpreter) => {\n const conditionNode = unresolvedArgs[0];\n const leftBranchNode = unresolvedArgs[1];\n const rightBranchNode = unresolvedArgs[2];\n unresolvedArgs\n .forEach(arg => {\n if (arg.type === 'ExpressionReference') {\n throw typeError('\"if()\" does not accept an expression reference argument.');\n }\n });\n\n const condition = interpreter.visit(conditionNode, data);\n if (toBoolean(valueOf(condition))) {\n return interpreter.visit(leftBranchNode, data);\n }\n return interpreter.visit(rightBranchNode, data);\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY] },\n { types: [TYPE_ANY] }],\n },\n\n /**\n * Combines all the elements from the provided\n * array, joined together using the `glue` argument as a separator between each array element.\n * @param {any[]} array array of values that will be converted to strings using `toString()`\n * @param {string} glue\n * @return {string} String representation of the array\n * @function join\n * @example\n * join([\"a\", \"b\", \"c\"], \",\") // returns \"a,b,c\"\n * join([\"apples\", \"bananas\"], \" and \") // returns \"apples and bananas\"\n * join([1, 2, 3, null()], \"|\") // returns \"1|2|3|null\"\n */\n join: {\n _func: resolvedArgs => {\n const listJoin = resolvedArgs[0];\n const joinChar = resolvedArgs[1];\n return listJoin.map(a => toJSON(a)).join(joinChar);\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n { types: [TYPE_STRING] },\n ],\n },\n\n /**\n * Generates an array of the keys of the input object. If the\n * object is null, the value return an empty array\n * @param {object} obj the object to examine\n * @return {array} the array of all the key names\n * @function keys\n * @example\n * keys({a : 3, b : 4}) // returns [\"a\", \"b\"]\n */\n keys: {\n _func: resolvedArgs => Object.keys(resolvedArgs[0]),\n _signature: [{ types: [TYPE_OBJECT] }],\n },\n /**\n * Return a substring from the start of a string or the left-most elements of an array\n * @param {string|array} subject The source text/array of code points/elements\n * @param {integer} [elements=1] number of elements to pick\n * @return {string|array}\n * @function left\n * @example\n * left(\"Sale Price\", 4) // returns \"Sale\"\n * left(\"Sweden\") // returns \"S\"\n * left([4, 5, 6], 2) // returns [4, 5]\n */\n left: {\n _func: args => {\n const numEntries = args.length > 1 ? toInteger(args[1]) : 1;\n if (numEntries < 0) throw evaluationError('left() requires a non-negative number of elements');\n if (isArrayType(args[0])) return args[0].slice(0, numEntries);\n const text = Array.from(toString(args[0]));\n return text.slice(0, numEntries).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the length of the input argument based on types:\n *\n * * string: returns the number of unicode code points\n * * array: returns the number of array elements\n * * object: returns the number of key-value pairs\n * @param {string | array | object} subject subject whose length to calculate\n * @return {integer} the length of the input subject\n * @function length\n * @example\n * length(`[]`) // returns 0\n * length(\"\") // returns 0\n * length(\"abcd\") // returns 4\n * length([1, 2, 3, 4]) // returns 4\n * length(`{}`) // returns 0\n * length({a : 3, b : 4}) // returns 2\n */\n length: {\n _func: resolvedArgs => {\n const arg = valueOf(resolvedArgs[0]);\n if (isObject(arg)) return Object.keys(arg).length;\n // Array.from splits a string into code points\n // If we didn't do this, then String.length would return the number of UTF-16 code units\n return isArrayType(arg) ? arg.length : Array.from(toString(arg)).length;\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT] }],\n },\n\n /**\n * Compute the natural logarithm (base e) of a number\n * @param {number|number[]} num A number greater than zero\n * @return {number|number[]} The natural log value\n * @function log\n * @example\n * log(10) // 2.302585092994046\n */\n log: {\n _func: args => evaluate(args, a => validNumber(Math.log(a), 'log')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Compute the base 10 logarithm of a number.\n * @param {number|number[]} num A number greater than or equal to zero\n * @return {number|number[]} The base 10 log result\n * @function log10\n * @example\n * log10(100000) // 5\n */\n log10: {\n _func: args => evaluate(args, a => validNumber(Math.log10(a), 'log10')),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Converts all the alphabetic code points in a string to lowercase.\n * @param {string|string[]} input input string\n * @returns {string|string[]} the lower case value of the input string\n * @function lower\n * @example\n * lower(\"E. E. Cummings\") // returns \"e. e. cummings\"\n */\n lower: {\n _func: args => evaluate(args, a => toString(a).toLowerCase()),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Apply an expression to every element in an array and return the array of results.\n * An input array of length N will return an array of length N.\n * @param {array} elements array of elements to process\n * @param {expression} expr expression to evaluate\n * @return {array} the mapped array\n * @function map\n * @example\n * map([1, 2, 3, 4], &(@ + 1)) // returns [2, 3, 4, 5]\n * map([\"doe\", \"nick\", \"chris\"], &length(@)) // returns [3, 4, 5]\n */\n map: {\n _func: resolvedArgs => {\n const exprefNode = resolvedArgs[1];\n return resolvedArgs[0].map(arg => runtime.interpreter.visit(exprefNode, arg));\n },\n _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }],\n },\n\n /**\n * Calculates the largest value in the input numbers.\n * Any values that are not numbers (null, boolean, strings, objects) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(array|any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function max\n * @example\n * max([1, 2, 3], [4, 5, 6]) // returns 6\n * max([\\\"a\\\", \\\"a1\\\", \\\"b\\\"], null(), true())) // returns 0\n * max(8, 10, 12, \"14\") // returns 12\n */\n max: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => typeof valueOf(a) === 'number');\n\n if (array.length === 0) return 0;\n\n return Math.max(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Calculates the largest value in the input values, coercing parameters to numbers.\n * Null values are ignored.\n * If any parameters cannot be converted to a number,\n * the function will fail with a type error.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function maxA\n * @example\n * maxA([1, 2, 3], [4, 5, 6]) // returns 6\n * maxA([\"a\", \"a1\", \"b\", null()]) // error\n * maxA(8, 10, 12, \"14\") // returns 14\n */\n maxA: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => valueOf(a) !== null)\n .map(toNumber);\n\n if (array.find(a => a === null)) {\n throw evaluationError('maxA() received non-numeric parameters');\n }\n if (array.length === 0) return 0;\n\n return Math.max(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Accepts one or more objects, and returns a single object with\n * all objects merged.\n * The first object is copied, and then\n * and each key value pair from each subsequent object\n * are added to the first object. Duplicate keys in subsequent objects will\n * override those found in earlier objects.\n * @param {...object} args\n * @return {object} The combined object\n * @function merge\n * @example\n * merge({a: 1, b: 2}, {c : 3, d: 4}) // returns {a :1, b: 2, c: 3, d: 4}\n * merge({a: 1, b: 2}, {a : 3, d: 4}) // returns {a :3, b: 2, d: 4}\n */\n merge: {\n _func: resolvedArgs => {\n const merged = {};\n resolvedArgs.forEach(current => {\n if (current === null) return;\n Object.entries(current || {}).forEach(([key, value]) => {\n merged[key] = value;\n });\n });\n return merged;\n },\n _signature: [{ types: [TYPE_OBJECT, TYPE_NULL], variadic: true }],\n },\n\n /**\n * Extracts a substring from text, or a subset from an array.\n * @param {string|array} subject the text string or array of elements from which to extract.\n * @param {integer} startPos the zero-based position of the first code point\n * or element to extract.\n * @param {integer} length The number of code points or elements to return from the\n * string or array.\n * If greater then the length of `subject` the length of the subject is used.\n * @return {string|array} The resulting substring or array subset of elements\n * @function mid\n * @example\n * mid(\"Fluid Flow\", 0, 5) // returns \"Fluid\"\n * mid(\"Fluid Flow\", 6, 20) // returns \"Flow\"\n * mid(\"Fluid Flow\", 20, 5) // returns \"\"\n * mid([0,1,2,3,4,5,6,7,8,9], 2, 3) // returns [2,3,4]\n */\n mid: {\n _func: args => {\n const startPos = toInteger(args[1]);\n const numEntries = toInteger(args[2]);\n if (startPos < 0) throw evaluationError('mid() requires a non-negative start position');\n if (numEntries < 0) throw evaluationError('mid() requires a non-negative length parameter');\n if (isArrayType(args[0])) {\n return args[0].slice(startPos, startPos + numEntries);\n }\n const text = Array.from(toString(args[0]));\n return text.slice(startPos, startPos + numEntries).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n ],\n },\n\n /**\n * Extract the milliseconds of the time value in a <<_date_and_time_values, date/time value>>.\n * @param {number|number[]} date datetime/time for which the millisecond is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The number of milliseconds: 0 through 999\n * @function millisecond\n * @example\n * millisecond(datetime(2008, 5, 23, 12, 10, 53, 42)) // returns 42\n */\n millisecond: {\n _func: args => evaluate(args, a => getDateObj(a).getMilliseconds()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Calculates the smallest value in the input numbers.\n * Any values that are not numbers (null, boolean, string, object) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any[]|any)} collection\n * Values/arrays to search for the minimum value\n * @return {number} the smallest value found\n * @function min\n * @example\n * min([1, 2, 3], [4, 5, 6]) // returns 1\n * min(\"4\", 8, 10, 12, null()) // returns 8\n */\n min: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => typeof valueOf(a) === 'number');\n if (array.length === 0) return 0;\n\n return Math.min(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Calculates the smallest value in the input values, coercing parameters to numbers.\n * Null values are ignored.\n * If any parameters cannot be converted to a number,\n * the function will fail with a type error.\n * If any parameters are arrays, the arrays will be flattened.\n * If no numbers are provided, the function will return zero.\n * @param {...(any[]|any)} collection values/array(s) in which the maximum\n * element is to be calculated\n * @return {number} the largest value found\n * @function minA\n * @example\n * minA([1, 2, 3], [4, 5, 6]) // returns 1\n * minA(\"4\", 8, 10, 12, null()) // returns 4\n */\n minA: {\n _func: args => {\n // flatten the args into a single array\n const array = args\n .flat(Infinity)\n .filter(a => valueOf(a) !== null)\n .map(toNumber);\n\n if (array.find(a => a === null)) {\n throw evaluationError('minA() received non-numeric parameters');\n }\n if (array.length === 0) return 0;\n\n return Math.min(...array);\n },\n _signature: [{\n types: [TYPE_ARRAY, TYPE_ANY],\n variadic: true,\n }],\n },\n\n /**\n * Extract the minute (0 through 59) from a <<_date_and_time_values, date/time value>>\n * @param {number|number[]} date A datetime/time value.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} Number of minutes in the time portion of the date/time value\n * @function minute\n * @example\n * minute(datetime(2008,5,23,12, 10, 0)) // returns 10\n * minute(time(12, 10, 0)) // returns 10\n */\n minute: {\n _func: args => evaluate(args, a => getDateObj(a).getMinutes()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Return the remainder when one number is divided by another number.\n * @param {number|number[]} dividend The number for which to find the remainder.\n * @param {number|number[]} divisor The number by which to divide number.\n * @return {number|number[]} Computes the remainder of `dividend`/`divisor`.\n * If `dividend` is negative, the result will also be negative.\n * If `dividend` is zero, an error is thrown.\n * @function mod\n * @example\n * mod(3, 2) // returns 1\n * mod(-3, 2) // returns -1\n */\n mod: {\n _func: args => evaluate(args, (a, b) => {\n const result = a % b;\n if (Number.isNaN(result)) throw evaluationError(`Bad parameter for mod: '${a} % ${b}'`);\n return result;\n }),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Finds the month of a date.\n * @param {number|number[]} date source <<_date_and_time_values, date/time value>>.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The month number value, ranging from 1 (January) to 12 (December)\n * @function month\n * @example\n * month(datetime(2008,5,23)) // returns 5\n */\n month: {\n // javascript months start from 0\n _func: args => evaluate(args, a => getDateObj(a).getMonth() + 1),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Compute logical NOT of a value. If the parameter is not boolean\n * it will be <<_type_coercion_rules,cast to boolean>>\n * Note the related <<_not_operator, unary NOT operator>>.\n * @param {any} value - any data type\n * @returns {boolean} The logical NOT applied to the input parameter\n * @example\n * not(length(\"bar\") > 0) // returns false\n * not(false()) // returns true\n * not(\"abcd\") // returns false\n * not(\"\") // returns true\n * @function not\n */\n not: {\n _func: resolveArgs => !toBoolean(valueOf(resolveArgs[0])),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Finds the first argument that does not resolve to `null`.\n * This function accepts one or more arguments, and will evaluate\n * them in order until a non-null argument is encountered. If all\n * arguments values resolve to null, then return a null value.\n * @param {...any} argument\n * @return {any}\n * @function notNull\n * @example\n * notNull(1, 2, 3, 4, `null`) // returns 1\n * notNull(`null`, 2, 3, 4, `null`) // returns 2\n */\n notNull: {\n _func: resolvedArgs => {\n const result = resolvedArgs.find(arg => getType(arg) !== TYPE_NULL);\n return result === undefined ? null : result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n /**\n * Retrieve the current date/time.\n * @return {number} representation of the <<_date_and_time_values, current date/time value>>.\n * @function now\n */\n now: {\n _func: () => getDateNum(Date.now()),\n _signature: [],\n },\n\n /**\n * Return constant null value.\n * Expressions may also use the JSON literal: `` `null` ``\n * @returns {boolean} True\n * @function null\n */\n null: {\n _func: () => null,\n _signature: [],\n },\n\n /**\n * Determines the logical OR result of a set of parameters.\n * If the parameters are not boolean they will be <<_type_coercion_rules,cast to\n * boolean>>.\n * Note the related <<_or_operator, Or Operator>>.\n * @param {any} first logical expression\n * @param {...any} [operand] any number of additional expressions\n * @returns {boolean} The logical result of applying OR to all parameters\n * @example\n * or((x / 2) == y, (y * 2) == x) // true\n * @function or\n */\n or: {\n _func: resolvedArgs => {\n let result = toBoolean(valueOf(resolvedArgs[0]));\n resolvedArgs.slice(1).forEach(arg => {\n result = result || toBoolean(valueOf(arg));\n });\n return result;\n },\n _signature: [{ types: [TYPE_ANY], variadic: true }],\n },\n\n /**\n * Computes `a` raised to a power `x`. (a^x)\n * @param {number|number[]} a The base number -- can be any real number.\n * @param {number|number[]} x The exponent to which the base number is raised.\n * @return {number|number[]}\n * @function power\n * @example\n * power(10, 2) // returns 100 (10 raised to power 2)\n */\n power: {\n _func: args => evaluate(args, (a, b) => validNumber(a ** b, 'power')),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Apply proper casing to a string. Proper casing is where the first letter of each\n * word is converted to an\n * uppercase letter and the rest of the letters in the word converted to lowercase.\n * Words are demarcated by whitespace, punctuation, or numbers.\n * Specifically, any character(s) matching the regular expression: `[\\s\\d\\p{P}]+`.\n * @param {string|string[]} text source string\n * @returns {string|string[]} source string with proper casing applied.\n * @function proper\n * @example\n * proper(\"this is a TITLE\") // returns \"This Is A Title\"\n * proper(\"2-way street\") // returns \"2-Way Street\"\n * proper(\"76BudGet\") // returns \"76Budget\"\n */\n proper: {\n _func: args => evaluate(args, properFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Generate a pseudo random number.\n * @returns {number} A value greater than or equal to zero, and less than one.\n * @function random\n * @example\n * random() // 0.022585461160693265\n */\n random: {\n _func: () => Math.random(),\n _signature: [],\n },\n /**\n * Executes a user-supplied reducer expression on each element of an\n * array, in order, passing in the return value from the expression from the preceding element.\n * The final result of running the reducer across all elements of the input array is a\n * single value.\n * The expression can access the following properties of the current object:\n *\n * * accumulated: accumulated value based on the previous expression.\n * For the first array element use the `initialValue` parameter. If not provided, then `null`\n * * current: current element to process\n * * index: index of the current element in the array\n * * array: original array\n * @param {array} elements array of elements on which the expression will be evaluated\n * @param {expression} expr reducer expression to be executed on each element\n * @param {any} initialValue the accumulated value to pass to the first array element\n * @return {any}\n * @function reduce\n * @example\n * reduce([1, 2, 3], &(accumulated + current)) // returns 6\n * // find maximum entry by age\n * reduce(\n * [{age: 10, name: \"Joe\"},{age: 20, name: \"John\"}],\n * &max(@.accumulated.age, @.current.age), @[0].age)\n * reduce([3, 3, 3], &accumulated * current, 1) // returns 27\n */\n reduce: {\n _func: resolvedArgs => {\n const exprefNode = resolvedArgs[1];\n return resolvedArgs[0].reduce(\n (accumulated, current, index, array) => runtime.interpreter.visit(exprefNode, {\n accumulated, current, index, array,\n }),\n resolvedArgs.length === 3 ? resolvedArgs[2] : null,\n );\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n { types: [TYPE_EXPREF] },\n { types: [TYPE_ANY], optional: true },\n ],\n },\n\n /**\n * Register a function. The registered function may take one parameter.\n * If more parameters are needed, combine them in an array or object.\n * A function may not be re-registered with a different definition.\n * Note that implementations are not required to provide `register()` in order to be conformant.\n * Built-in functions may not be overridden.\n * @param {string} functionName Name of the function to register.\n * `functionName` must begin with an underscore or uppercase letter and follow the regular\n * expression pattern:\n * `{caret}{startsb}_A-Z{endsb}{startsb}_a-zA-Z0-9${endsb}{asterisk}$`\n * @param {expression} expr Expression to execute with this function call\n * @return {{}} returns an empty object\n * @function register\n * @example\n * register(\"_product\", &@[0] * @[1]) // can now call: _product([2,21]) => returns 42\n * register(\"_ltrim\", &split(@,\"\").reduce(@, &accumulated & current | if(@ = \" \", \"\", @), \"\"))\n * // _ltrim(\" abc \") => returns \"abc \"\n */\n register: {\n _func: resolvedArgs => {\n const functionName = resolvedArgs[0];\n const exprefNode = resolvedArgs[1];\n\n if (!/^[_A-Z][_a-zA-Z0-9$]*$/.test(functionName)) throw functionError(`Invalid function name: \"${functionName}\"`);\n if (functionMap[functionName]\n && functionMap[functionName]._exprefNode.value !== exprefNode.value) {\n // custom functions can be re-registered as long as the expression is the same\n throw functionError(`Cannot override function: \"${functionName}\" with a different definition`);\n }\n functionMap[functionName] = {\n _func: args => runtime.interpreter.visit(exprefNode, ...args),\n _signature: [{ types: [TYPE_ANY], optional: true }],\n _exprefNode: exprefNode,\n };\n return {};\n },\n _signature: [\n { types: [TYPE_STRING] },\n { types: [TYPE_EXPREF] },\n ],\n },\n\n /**\n * Register a function that accepts multiple parameters.\n * A function may not be re-registered with a different definition.\n * Note that implementations are not required to provide `registerWithParams()`\n * in order to be conformant.\n * Built-in functions may not be overridden.\n * @param {string} functionName Name of the function to register.\n * `functionName` must begin with an underscore or uppercase letter and follow the regular\n * expression pattern:\n * `{caret}{startsb}_A-Z{endsb}{startsb}_a-zA-Z0-9${endsb}{asterisk}$`\n * @param {expression} expr Expression to execute with this function call.\n * Parameters are passed as an array.\n * @return {{}} returns an empty object\n * @function registerWithParams\n * @example\n * registerWithParams(\"Product\", &@[0] * @[1])\n * // can now call: Product(2,21) => returns 42\n * registerWithParams(\n * \"Ltrim\",\n * &split(@[0],\"\").reduce(@, &accumulated & current | if(@ = \" \", \"\", @), \"\")\n * )\n * // Ltrim(\" abc \") => returns \"abc \"\n */\n registerWithParams: {\n _func: resolvedArgs => {\n const functionName = resolvedArgs[0];\n const exprefNode = resolvedArgs[1];\n\n if (!/^[_A-Z][_a-zA-Z0-9$]*$/.test(functionName)) throw functionError(`Invalid function name: \"${functionName}\"`);\n if (functionMap[functionName]\n && functionMap[functionName]._exprefNode.value !== exprefNode.value) {\n // custom functions can be re-registered as long as the expression is the same\n throw functionError(`Cannot override function: \"${functionName}\" with a different definition`);\n }\n functionMap[functionName] = {\n _func: args => runtime.interpreter.visit(exprefNode, args),\n _signature: [{ types: [TYPE_ANY], optional: true, variadic: true }],\n _exprefNode: exprefNode,\n };\n return {};\n },\n _signature: [\n { types: [TYPE_STRING] },\n { types: [TYPE_EXPREF] },\n ],\n },\n\n /**\n * Generates text (or an array) where we substitute elements at a given start position and\n * length, with new text (or array elements).\n * @param {string|array} subject original text or array\n * @param {integer} start zero-based index in the original text\n * from where to begin the replacement. Must be greater than or equal to 0.\n * @param {integer} length number of code points to be replaced.\n * If `start` + `length` is greater than the length of `subject`,\n * all text past `start` will be replaced.\n * @param {any} replacement Replacement to insert at the start index.\n * If `subject` is an array, and `replacement` is an array, the `replacement` array\n * elements will be inserted into the `subject` array.\n * If `subject` is an array and replacement is not an array, the `replacement` will be\n * inserted as a single element in `subject`\n * If `subject` is a string, the `replacement` will be coerced to a string.\n * @returns {string|array} the resulting text or array\n * @function replace\n * @example\n * replace(\"abcdefghijk\", 5, 5, \"*\") // returns abcde*k\n * replace(\"2009\",2,2,\"10\") // returns 2010\n * replace(\"123456\",0,3,\"@\") // returns @456\n * replace([\"blue\",\"black\",\"white\",\"red\"], 1, 2, [\"green\"]) // returns [\"blue\",\"green\",\"red\"]\n */\n replace: {\n _func: args => {\n const startPos = toInteger(args[1]);\n const numElements = toInteger(args[2]);\n if (startPos < 0) throw evaluationError('replace() start position must be greater than or equal to 0');\n if (numElements < 0) throw evaluationError('replace() length must be greater than or equal to 0');\n if (isArrayType(args[0])) {\n const sourceArray = valueOf(args[0]);\n let replacement = valueOf(args[3]);\n if (!isArrayType(replacement)) replacement = [replacement];\n sourceArray.splice(startPos, numElements, ...replacement);\n return sourceArray;\n }\n const subject = Array.from(toString(args[0]));\n if (isArrayType(args[3]) || getType(args[3]) === TYPE_OBJECT) throw typeError('replace() replacement must not be an array or object');\n const newText = toString(args[3]);\n\n subject.splice(startPos, numElements, newText);\n return subject.join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_ANY] },\n ],\n },\n\n /**\n * Return text repeated `count` times.\n * @param {string|string[]} text text to repeat\n * @param {integer|integer[]} count number of times to repeat the text.\n * Must be greater than or equal to 0.\n * @returns {string|string[]} Text generated from the repeated text.\n * if `count` is zero, returns an empty string.\n * @function rept\n * @example\n * rept(\"x\", 5) // returns \"xxxxx\"\n */\n rept: {\n _func: args => evaluate(args, reptFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Reverses the order of an array or the order of code points in a string\n * @param {string|array} subject the source to be reversed\n * @return {array} The resulting reversed array or string\n * @function reverse\n * @example\n * reverse([\"a\", \"b\", \"c\"]) // returns [\"c\", \"b\", \"a\"]\n */\n reverse: {\n _func: resolvedArgs => {\n const originalStr = valueOf(resolvedArgs[0]);\n const typeName = getType(originalStr);\n if (typeName === TYPE_STRING) {\n return Array.from(originalStr).reverse().join('');\n }\n const reversedArray = resolvedArgs[0].slice(0);\n return reversedArray.reverse();\n },\n _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] }],\n },\n\n /**\n * Generates a string from the right-most code points of a string or\n * a subset of elements from the end of an array\n * @param {string|array} subject The text/array containing the code points/elements to extract\n * @param {integer} [elements=1] number of elements to pick\n * @return {string|array} The extracted substring or array subset\n * Returns null if the number of elements is less than 0\n * @function right\n * @example\n * right(\"Sale Price\", 4) // returns \"rice\"\n * right(\"Sweden\") // returns \"n\"\n * right([4, 5, 6], 2) // returns [5, 6]\n */\n right: {\n _func: args => {\n const numEntries = args.length > 1 ? toInteger(args[1]) : 1;\n if (numEntries < 0) throw evaluationError('right() count must be greater than or equal to 0');\n if (args[0] instanceof Array) {\n if (numEntries === 0) return [];\n return args[0].slice(numEntries * -1);\n }\n if (numEntries === 0) return '';\n const text = Array.from(toString(args[0]));\n return text.slice(numEntries * -1).join('');\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Round a number to a specified precision:\n *\n * * If `precision` is greater than zero, round to the specified number of decimal places.\n * * If `precision` is 0, round to the nearest integer.\n * * If `precision` is less than 0, round to the left of the decimal point.\n * @param {number|number[]} num number to round\n * @param {integer|integer[]} [precision=0] precision to use for the rounding operation.\n * @returns {number|number[]} rounded value. Rounding a half value will round up.\n * @function round\n * @example\n * round(2.15, 1) // returns 2.2\n * round(626.3,-3) // returns 1000 (Rounds 626.3 to the nearest multiple of 1000)\n * round(626.3, 0) // returns 626\n * round(1.98,-1) // returns 0 (Rounds 1.98 to the nearest multiple of 10)\n * round(-50.55,-2) // -100 (round -50.55 to the nearest multiple of 100)\n * round(1.95583) // 2\n * round(-1.5) // -1\n */\n round: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2)args.push(0);\n return evaluate(args, (a, n) => {\n const digits = toInteger(n);\n return round(a, digits);\n });\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Perform a wildcard search. The search is case-sensitive and supports two forms of wildcards:\n * `{asterisk}` finds a sequence of code points and `?` finds a single code point.\n * To use `{asterisk}` or `?` or `{backslash}` as text values,\n * precede them with an escape (`{backslash}`) character.\n * Note that the wildcard search is not greedy.\n * e.g. `search(\"a{asterisk}b\", \"abb\")` will return `[0, \"ab\"]` Not `[0, \"abb\"]`\n * @param {string|string[]} findText the search string -- which may include wild cards.\n * @param {string|string[]} withinText The string to search.\n * @param {integer|integer[]} [startPos=0] The zero-based position of withinText\n * to start searching.\n * A negative value is not allowed.\n * @returns {array} returns an array with two values:\n *\n * * The start position of the found text and the text string that was found.\n * * If a match was not found, an empty array is returned.\n * @function search\n * @example\n * search(\"a?c\", \"acabc\") // returns [2, \"abc\"]\n */\n search: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(0);\n return evaluate(args, searchFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n\n },\n\n /**\n * Extract the seconds of the time value in a <<_date_and_time_values, date/time value>>.\n * @param {number|number[]} date datetime/time for which the second is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The number of seconds: 0 through 59\n * @function second\n * @example\n * second(datetime(2008,5,23,12, 10, 53)) // returns 53\n * second(time(12, 10, 53)) // returns 53\n */\n second: {\n _func: args => evaluate(args, a => getDateObj(a).getSeconds()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Computes the sign of a number passed as argument.\n * @param {number|number[]} num any number\n * @return {number|number[]} returns 1 or -1, indicating the sign of `num`.\n * If the `num` is 0, it will return 0.\n * @function sign\n * @example\n * sign(5) // 1\n * sign(-5) // -1\n * sign(0) // 0\n */\n sign: {\n _func: args => evaluate(args, Math.sign),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Computes the sine of a number in radians\n * @param {number|number[]} angle A number representing an angle in radians.\n * @return {number|number[]} The sine of `angle`, between -1 and 1, inclusive\n * @function sin\n * @example\n * sin(0) // 0\n * sin(1) // 0.8414709848078965\n */\n sin: {\n _func: args => evaluate(args, Math.sin),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * This function accepts an array values and returns an\n * array with the elements in sorted order.\n * If there are mixed data types, the values will be grouped in order:\n * numbers, strings, booleans, nulls\n * String sorting is based on code points and is not locale-sensitive.\n * If the sort encounters any objects or arrays, it will throw an evaluation error.\n * @param {any[]} list to be sorted\n * @return {any[]} The ordered result\n * @function sort\n * @example\n * sort([1, 2, 4, 3, 1]) // returns [1, 1, 2, 3, 4]\n * sort([\"20\", 20, true(), \"100\", null(), 100]) // returns [20, 100, \"100\", \"20\", true, null]\n */\n sort: {\n _func: resolvedArgs => {\n /*\n numbers sort first\n strings sort second\n Booleans sort third\n nulls sort last\n */\n const typeVals = resolvedArgs[0].map(value => {\n const type = getType(value);\n if (![TYPE_NUMBER, TYPE_STRING, TYPE_BOOLEAN, TYPE_NULL].includes(type)) {\n throw evaluationError('Bad datatype for sort');\n }\n return { type, value };\n });\n\n const sortFunction = (a, b) => {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n };\n\n const sorted = typeVals\n .filter(v => v.type === TYPE_NUMBER)\n .map(v => v.value)\n .sort(sortFunction);\n\n sorted.push(\n ...typeVals\n .filter(v => v.type === TYPE_STRING)\n .map(v => v.value)\n .sort(),\n );\n\n sorted.push(...typeVals.filter(v => v.type === TYPE_BOOLEAN).map(v => v.value));\n sorted.push(...typeVals.filter(v => v.type === TYPE_NULL).map(v => v.value));\n return sorted;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Sort an array using an expression to find the sort key. For each element\n * in the array, the expression is applied and the resulting\n * value is used as the sort value. If the result of\n * evaluating the expression against the current array element results in type\n * other than a number or a string, a <<_errors, TypeError>> will occur.\n * @param {array} elements Array to be sorted\n * @param {expression} expr The comparison expression\n * @return {array} The sorted array\n * @function sortBy\n * @example\n * // returns [\"e\", \"def\", \"abcd\"]\n * sortBy([\"abcd\", \"e\", \"def\"], &length(@))\n *\n * // returns [{year: 1910}, {year: 2010}, {year: 2020}]\n * sortBy([{year: 2010}, {year: 2020}, {year: 1910}], &year)\n *\n * // returns [5, -10, -11, -15, 30]\n * sortBy([-15, 30, -10, -11, 5], &abs(@))\n */\n sortBy: {\n _func: resolvedArgs => {\n const sortedArray = resolvedArgs[0].slice(0);\n if (sortedArray.length === 0) {\n return sortedArray;\n }\n const exprefNode = resolvedArgs[1];\n const requiredType = getType(\n runtime.interpreter.visit(exprefNode, sortedArray[0]),\n );\n if (![TYPE_NUMBER, TYPE_STRING].includes(requiredType)) {\n throw typeError('Bad data type for sortBy()');\n }\n // In order to get a stable sort out of an unstable\n // sort algorithm, we decorate/sort/undecorate (DSU)\n // by creating a new list of [index, element] pairs.\n // In the cmp function, if the evaluated elements are\n // equal, then the index will be used as the tiebreaker.\n // After the decorated list has been sorted, it will be\n // undecorated to extract the original elements.\n const decorated = [];\n for (let i = 0; i < sortedArray.length; i += 1) {\n decorated.push([i, sortedArray[i]]);\n }\n decorated.sort((a, b) => {\n const exprA = runtime.interpreter.visit(exprefNode, a[1]);\n const typeA = getType(exprA);\n const exprB = runtime.interpreter.visit(exprefNode, b[1]);\n const typeB = getType(exprB);\n if (typeA !== requiredType) {\n throw typeError(`sortBy expected ${typeNameTable[requiredType]}, received ${typeNameTable[typeA]}`);\n } else if (typeB !== requiredType) {\n throw typeError(`sortyBy expected ${typeNameTable[requiredType]}, received ${typeNameTable[typeB]}`);\n }\n if (exprA > exprB) return 1;\n if (exprA < exprB) return -1;\n // If they\"re equal compare the items by their\n // order to maintain relative order of equal keys\n // (i.e. to get a stable sort).\n return a[0] - b[0];\n });\n // Undecorate: extract out the original list elements.\n for (let j = 0; j < decorated.length; j += 1) {\n [, sortedArray[j]] = decorated[j];\n }\n return sortedArray;\n },\n _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }],\n },\n\n /**\n * Split a string into an array, given a separator\n * @param {string|string[]} string string to split\n * @param {string|string[]} separator separator where the split(s) should occur\n * @return {string[]|string[][]} The array of separated strings\n * @function split\n * @example\n * split(\"abcdef\", \"\") // returns [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n * split(\"abcdef\", \"e\") // returns [\"abcd\", \"f\"]\n */\n split: {\n _func: args => evaluate(args, splitFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Find the square root of a number\n * @param {number|number[]} num source number\n * @return {number|number[]} The calculated square root value\n * @function sqrt\n * @example\n * sqrt(4) // returns 2\n */\n sqrt: {\n _func: args => evaluate(args, arg => validNumber(Math.sqrt(arg), 'sqrt')),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Determine if a string starts with a prefix.\n * @param {string|string[]} subject string to search\n * @param {string|string[]} prefix prefix to search for\n * @return {boolean|boolean[]} true if `prefix` matches the start of `subject`\n * @function startsWith\n * @example\n * startsWith(\"jack is at home\", \"jack\") // returns true\n */\n startsWith: {\n _func: args => evaluate(args, startsWithFn),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n /**\n * Estimates standard deviation based on a sample.\n * `stdev` assumes that its arguments are a sample of the entire population.\n * If your data represents a entire population,\n * then compute the standard deviation using [stdevp]{@link stdevp}.\n * Non-numeric values (text, boolean, null etc) are ignored.\n * If there are nested arrays, they are flattened.\n * @param {any[]} values The array containing numbers comprising the population.\n * Array size must be greater than 1.\n * @returns {number} [Standard deviation](https://en.wikipedia.org/wiki/Standard_deviation)\n * @function stdev\n * @example\n * stdev([1345, 1301, 1368]) // returns 34.044089061098404\n * stdevp([1345, 1301, 1368]) // returns 27.797\n */\n stdev: {\n _func: args => {\n const values = args.flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (values.length <= 1) throw evaluationError('stdev() must have at least two values');\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const sumSquare = values.reduce((a, b) => a + b * b, 0);\n const result = Math.sqrt((sumSquare - values.length * mean * mean) / (values.length - 1));\n return validNumber(result, 'stdev');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Estimates standard deviation based on a sample.\n * `stdev` assumes that its arguments are a sample of the entire population.\n * If your data represents a entire population,\n * then compute the standard deviation using [stdevpA]{@link stdevpA}.\n * Nested arrays are flattened.\n * Null values are ignored. All other parameters are converted to number.\n * If conversion to number fails, a type error is thrown.\n * @param {number[]} numbers The array of numbers comprising the population.\n * Array size must be greater than 1.\n * @returns {number} [Standard deviation](https://en.wikipedia.org/wiki/Standard_deviation)\n * @function stdevA\n * @example\n * stdevA([1345, \"1301\", 1368]) // returns 34.044089061098404\n * stdevpA([1345, 1301, \"1368\"]) // returns 27.797\n */\n stdevA: {\n _func: args => {\n let values;\n try {\n values = args.flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n } catch (_e) {\n throw evaluationError('stdevA() received non-numeric parameters');\n }\n\n if (values.length <= 1) throw evaluationError('stdevA() must have at least two values');\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const sumSquare = values.reduce((a, b) => a + b * b, 0);\n const result = Math.sqrt((sumSquare - values.length * mean * mean) / (values.length - 1));\n return validNumber(result, 'stdevA');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Calculates standard deviation based on the entire population given as arguments.\n * `stdevp` assumes that its arguments are the entire population.\n * If your data represents a sample of the population,\n * then compute the standard deviation using [stdev]{@link stdev}.\n * Non-numeric values (text, boolean, null etc) are ignored.\n * If there are nested arrays, they are flattened.\n * @param {any[]} values The array containing numbers comprising the population.\n * An empty array is not allowed.\n * @returns {number} Calculated standard deviation\n * @function stdevp\n * @example\n * stdevp([1345, 1301, 1368]) // returns 27.797\n * stdev([1345, 1301, 1368]) // returns 34.044\n */\n stdevp: {\n _func: args => {\n const values = args[0]\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER);\n\n if (values.length === 0) throw evaluationError('stdevp() must have at least one value');\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const meanSumSquare = values.reduce((a, b) => a + b * b, 0) / values.length;\n const result = Math.sqrt(meanSumSquare - mean * mean);\n return validNumber(result, 'stdevp');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Calculates standard deviation based on the entire population given as arguments.\n * `stdevpA` assumes that its arguments are the entire population.\n * If your data represents a sample of the population,\n * then compute the standard deviation using [stdevA]{@link stdevA}.\n * Nested arrays are flattened.\n * Null values are ignored. All other parameters are converted to number.\n * If conversion to number fails, a type error is thrown.\n * @param {number[]} numbers The array of numbers comprising the population.\n * An empty array is not allowed.\n * @returns {number} Calculated standard deviation\n * @function stdevp\n * @example\n * stdevpA([1345, \"1301\", 1368]) // returns 27.797\n * stdevA([1345, 1301, \"1368\"]) // returns 34.044\n */\n stdevpA: {\n _func: args => {\n const values = args[0]\n .flat(Infinity)\n .filter(a => getType(a) !== TYPE_NULL)\n .map(toNumber);\n\n if (values.length === 0) throw evaluationError('stdevp() must have at least one value');\n\n const mean = values.reduce((a, b) => a + b, 0) / values.length;\n const meanSumSquare = values.reduce((a, b) => a + b * b, 0) / values.length;\n const result = Math.sqrt(meanSumSquare - mean * mean);\n return validNumber(result, 'stdevp');\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Generates a string from the input `text`,\n * with text `old` replaced by text `new` (when searching from the left).\n * If there is no match, or if `old` has length 0, `text` is returned unchanged.\n * Note that `old` and `new` may have different lengths.\n * @param {string|string[]} text The text for which to substitute code points.\n * @param {string|string[]} old The text to replace.\n * @param {string|string[]} new The text to replace `old` with.\n * If `new` is an empty string, then occurrences of `old` are removed from `text`.\n * @param {integer|integer[]} [which]\n * The zero-based occurrence of `old` text to replace with `new` text.\n * If `which` parameter is omitted, every occurrence of `old` is replaced with `new`.\n * @returns {string|string[]} replaced string\n * @function substitute\n * @example\n * substitute(\"Sales Data\", \"Sales\", \"Cost\") // returns \"Cost Data\"\n * substitute(\"Quarter 1, 2001\", \"1\", \"2\", 1)\" // returns \"Quarter 1, 2002\"\n * substitute(\"Quarter 1, 2011\", \"1\", \"2\", 2)\" // returns \"Quarter 1, 2012\"\n */\n substitute: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n let n;\n if (args.length > 3) {\n if (Array.isArray(args[3])) {\n n = args[3].map(toInteger);\n if (n.find(o => o < 0) !== undefined) throw evaluationError('substitute() which parameter must be greater than or equal to 0');\n } else {\n n = toInteger(args[3]);\n if (n < 0) throw evaluationError('substitute() which parameter must be greater than or equal to 0');\n }\n args[3] = n;\n }\n return evaluate(args, substituteFn);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Calculates the sum of the provided array.\n * An empty array will produce a return value of 0.\n * Any values that are not numbers (null, boolean, strings, objects) will be ignored.\n * If any parameters are arrays, the arrays will be flattened.\n * @param {any[]} collection array of values\n * @return {number} The computed sum\n * @function sum\n * @example\n * sum([1, 2, 3]) // returns 6\n */\n sum: {\n _func: resolvedArgs => {\n let sum = 0;\n resolvedArgs[0]\n .flat(Infinity)\n .filter(a => getType(a) === TYPE_NUMBER)\n .forEach(arg => {\n sum += arg * 1;\n });\n\n return sum;\n },\n _signature: [{ types: [TYPE_ARRAY] }],\n },\n\n /**\n * Computes the tangent of a number in radians\n * @param {number|number[]} angle A number representing an angle in radians.\n * @return {number|number[]} The tangent of `angle`\n * @function tan\n * @example\n * tan(0) // 0\n * tan(1) // 1.5574077246549023\n */\n tan: {\n _func: args => evaluate(args, Math.tan),\n _signature: [{ types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] }],\n },\n\n /**\n * Construct and returns a <<_date_and_time_values, time value>>.\n * If any of the units are greater or less than their normal range,\n * the overflow/underflow will be added/subtracted from the next greater unit.\n * @param {integer} hours Zero-based integer value between 0 and 23 representing\n * the hour of the day.\n * @param {integer} [minutes=0] Zero-based integer value representing\n * the minute segment of a time.\n * @param {integer} [seconds=0] Zero-based integer value representing the seconds\n * segment of a time.\n * @return {number} Returns a date/time value representing the fraction\n * of the day consumed by the given time\n * @function time\n * @example\n * time(12, 0, 0) | [hour(@), minute(@), second(@)] // returns [12, 0, 0]\n */\n time: {\n _func: args => {\n const hours = toInteger(args[0]);\n const minutes = args.length > 1 ? toInteger(args[1]) : 0;\n const seconds = args.length > 2 ? toInteger(args[2]) : 0;\n // Since time values are interchangeable with date and datetime values, it\"s consistent\n // to create them at the epoch\n const epochTime = new Date(1970, 0, 1, hours, minutes, seconds);\n return getDateNum(epochTime);\n },\n _signature: [\n { types: [TYPE_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Converts the provided argument to an array.\n * The conversion happens as per the following rules:\n *\n * * array - Returns the provided value.\n * * number/string/object/boolean/null - Returns a one element array containing the argument.\n * @param {any} arg parameter to turn into an array\n * @return {array} The resulting array\n * @function toArray\n * @example\n * toArray(1) // returns [1]\n * toArray(null()) // returns [`null`]\n */\n toArray: {\n _func: resolvedArgs => (isArrayType(resolvedArgs[0]) ? resolvedArgs[0] : [resolvedArgs[0]]),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Converts the provided string to a date/time value.\n *\n * @param {string} ISOString An [ISO8601 formatted string]{@link https://www.iso.org/iso-8601-date-and-time-format.html}.\n * (limited to the [RFC 3339]{@link https://www.rfc-editor.org/rfc/rfc3339} profile)\n * If the string does not include a timezone offset (or trailing 'Z'),\n * it will be assumed to be local time\n * @return {number} The resulting <<_date_and_time_values, date/time number>>.\n * If conversion fails, return null.\n * @function toDate\n * @example\n * toDate(\"20231110T130000+04:00\") // returns 19671.375\n * toDate(\"2023-11-10T13:00:00+04:00\") // returns 19671.375\n * toDate(\"20231110\") | year(@) & \"/\" & month(@) // returns \"2023/11\"\n */\n toDate: {\n _func: resolvedArgs => {\n // expand compact notation so that the Date() constructor will\n // accept the value\n const iso = toString(resolvedArgs[0])\n .replace(/(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)/, '$1-$2-$3')\n .replace(/T(\\d\\d)(\\d\\d)(\\d\\d)/, 'T$1:$2:$3');\n const dateparts = iso.split(/[\\D,zZ]+/);\n let d;\n if (dateparts.length <= 3) {\n if (dateparts.length < 3 || dateparts.find(x => x === '') === '') {\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n return null;\n }\n }\n if (dateparts.length < 7) {\n // no timezone component, so assume local time\n // The date constructor always parses an ISO string as\n // UTC -- with or without a trailing 'z'\n // But if there's no timezone component, it needs to be local time\n\n const range = [99999, 12, 31, 23, 59, 59, 999];\n // check that the date parts are in range\n for (let i = 0; i < dateparts.length; i += 1) {\n if (dateparts[i] > range[i]) {\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n return null;\n }\n }\n // account for zero-based date month parts\n d = new Date(...dateparts.map((x, i) => (i === 1 ? x - 1 : x * 1)));\n } else {\n d = new Date(iso);\n }\n if (d instanceof Date && Number.isFinite(d.getTime())) return getDateNum(d);\n debug.push(`Failed to convert \"${resolvedArgs[0]}\" to a date`);\n\n return null;\n },\n _signature: [{ types: [TYPE_STRING] }],\n },\n\n /**\n * Returns a <<_date_and_time_values, date/time>> value representing\n * the start of the current day. i.e. midnight\n * @return {number} today at midnight\n * @function today\n */\n today: {\n _func: () => {\n const now = new Date(Date.now());\n // We used to take the floor() to truncate h/m/s from Date.now(), but that would return\n // today at UTC time. We want today in local time.\n // i.e. UTC time could be a day ahead or behind\n // But note that means that the result is not an integer.\n const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());\n return getDateNum(today);\n },\n _signature: [],\n },\n\n /**\n * Converts the provided arg to a number.\n * The conversions follow the <<_type_coercion_rules,type coercion rules>> but will also:\n * * Convert non-numeric strings to zero\n * * Convert arrays to arrays of numbers\n *\n * @param {any|any[]} value to convert to number\n * @param {integer|integer[]} [base=10] If the input `arg` is a string,\n * the base to use to convert to number.\n * One of: 2, 8, 10, 16. Defaults to 10.\n * @return {number} The resulting number. If conversion to number fails, return null.\n * @function toNumber\n * @example\n * toNumber(1) // returns 1\n * toNumber(\"10\") // returns 10\n * toNumber({a: 1}) // returns null\n * toNumber(true()) // returns 1\n * toNumber(\"10f\") // returns null\n * toNumber(\"FF\", 16) // returns 255\n */\n toNumber: {\n _func: resolvedArgs => {\n const toNumberFn = (value, base) => {\n const num = valueOf(value);\n if (getType(num) === TYPE_STRING && base !== 10) {\n let digitCheck;\n if (base === 2) digitCheck = /^\\s*(\\+|-)?[01.]+\\s*$/;\n else if (base === 8) digitCheck = /^\\s*(\\+|-)?[0-7.]+\\s*$/;\n else if (base === 16) digitCheck = /^\\s*(\\+|-)?[0-9A-Fa-f.]+\\s*$/;\n else throw evaluationError(`Invalid base: \"${base}\" for toNumber()`);\n\n if (num === '') return 0;\n if (!digitCheck.test(num)) {\n debug.push(`Failed to convert \"${num}\" base \"${base}\" to number`);\n return null;\n }\n const parts = num.split('.').map(p => p.trim());\n\n let decimal = 0;\n if (parts.length > 1) {\n decimal = parseInt(parts[1], base) * base ** -parts[1].length;\n }\n\n const result = parseInt(parts[0], base) + decimal;\n if (parts.length > 2 || Number.isNaN(result)) {\n debug.push(`Failed to convert \"${num}\" base \"${base}\" to number`);\n return null;\n }\n return result;\n }\n try {\n return toNumber(num);\n } catch (e) {\n const errorString = arg => {\n const v = toJSON(arg);\n return v.length > 50 ? `${v.substring(0, 20)} ...` : v;\n };\n\n debug.push(`Failed to convert \"${errorString(num)}\" to number`);\n return null;\n }\n };\n let base = 10;\n if (resolvedArgs.length > 1) {\n base = Array.isArray(resolvedArgs[1])\n ? resolvedArgs.map(toInteger)\n : toInteger(resolvedArgs[1]);\n }\n return evaluate([resolvedArgs[0], base], toNumberFn);\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Returns the argument converted to a string.\n * If the argument is a string, it will be returned unchanged.\n * Otherwise, returns the JSON encoded value of the argument.\n * @param {any} arg Value to be converted to a string\n * @param {integer} [indent=0] Indentation to use when converting\n * objects and arrays to a JSON string\n * @return {string} The result string.\n * @function toString\n * @example\n * toString(1) // returns \"1\"\n * toString(true()) // returns \"true\"\n * toString({sum: 12 + 13}) // \"{\"sum\":25}\"\n * toString(\"hello\") // returns \"hello\"\n */\n toString: {\n _func: resolvedArgs => toJSON(resolvedArgs[0], resolvedArgs.length > 1 ? resolvedArgs[1] : 0),\n _signature: [{ types: [TYPE_ANY] }, { types: [TYPE_NUMBER], optional: true }],\n },\n\n /**\n * Remove leading and trailing spaces (U+0020), and replace all internal multiple spaces\n * with a single space. Note that other whitespace characters are left intact.\n * @param {string|string[]} text string to trim\n * @return {string|string[]} trimmed string\n * @function trim\n * @example\n * trim(\" ab c \") // returns \"ab c\"\n */\n trim: {\n _func: args => evaluate(args, s => toString(s).split(' ').filter(x => x).join(' ')),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Return constant boolean true value.\n * Expressions may also use the JSON literal: `` `true` ``\n * @returns {boolean} True\n * @function true\n */\n true: {\n _func: () => true,\n _signature: [],\n },\n\n /**\n * Truncates a number to an integer by removing the fractional part of the number.\n * i.e. it rounds towards zero.\n * @param {number|number[]} numA number to truncate\n * @param {integer|integer[]} [numB=0]\n * A number specifying the number of decimal digits to preserve.\n * @return {number|number[]} Truncated value\n * @function trunc\n * @example\n * trunc(8.9) // returns 8\n * trunc(-8.9) // returns -8\n * trunc(8.912, 2) // returns 8.91\n */\n trunc: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(0);\n return evaluate(args, truncFn);\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the type name of the given `subject` argument as a string value.\n * The return value will be one of the following:\n *\n * * number\n * * string\n * * boolean\n * * array\n * * object\n * * null\n * @param {any} subject type to evaluate\n * @return {string} The type name\n *\n * @function type\n * @example\n * type(1) // returns \"number\"\n * type(\"\") // returns \"string\"\n */\n type: {\n _func: resolvedArgs => ({\n [TYPE_NUMBER]: 'number',\n [TYPE_STRING]: 'string',\n [TYPE_ARRAY]: 'array',\n [TYPE_ARRAY_NUMBER]: 'array',\n [TYPE_ARRAY_STRING]: 'array',\n [TYPE_ARRAY_ARRAY]: 'array',\n [TYPE_OBJECT]: 'object',\n [TYPE_BOOLEAN]: 'boolean',\n [TYPE_EXPREF]: 'expref',\n [TYPE_NULL]: 'null',\n }[getType(resolvedArgs[0])]),\n _signature: [{ types: [TYPE_ANY] }],\n },\n\n /**\n * Find the set of unique elements within an array\n * @param {array} input input array\n * @return {array} array with duplicate elements removed\n * @function unique\n * @example\n * unique([1, 2, 3, 4, 1, 1, 2]) // returns [1, 2, 3, 4]\n */\n unique: {\n _func: args => {\n // create an array of values for searching. That way if the array elements are\n // represented by class objects with a valueOf(), we'll locate them in the valueArray\n // but return the original class object.\n const valueArray = args[0].map(a => valueOf(a));\n return args[0]\n .filter(\n (v, index) => valueArray.findIndex(\n lookup => strictDeepEqual(lookup, valueOf(v)),\n ) === index,\n );\n },\n _signature: [\n { types: [TYPE_ARRAY] },\n ],\n },\n\n /**\n * Converts all the alphabetic code points in a string to uppercase.\n * @param {string|string[]} input input string\n * @returns {string|string[]} the upper case value of the input string\n * @function upper\n * @example\n * upper(\"abcd\") // returns \"ABCD\"\n */\n upper: {\n _func: args => evaluate(args, a => toString(a).toUpperCase()),\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n ],\n },\n\n /**\n * Perform an indexed lookup on an object or array\n * @param {object | array | null} subject on which to perform the lookup.\n * When querying for <<_hidden_properties,hidden properties>>, `subject` may be any data type.\n * @param {string | integer} index if `subject` is an object, `index` must be a string\n * indicating the key name to search for.\n * If `subject` is an array, then index must be an integer indicating the offset into the array\n * @returns {any} the result of the lookup -- or `null` if not found.\n * @function value\n * @example\n * value({a: 1, b:2, c:3}, \"a\") // returns 1\n * value([1, 2, 3, 4], 2) // returns 3\n */\n value: {\n _func: args => {\n const indexType = getType(args[1]);\n let index = args[1];\n const subjectArray = isArrayType(args[0]);\n // if the object/array has a getter for this property then don't validate types\n // just return the value.\n if (args[0] !== null && Object.getOwnPropertyDescriptor(args[0], index)?.get) {\n return getProperty(args[0], index);\n }\n const obj = valueOf(args[0]);\n if (obj === null) return null;\n if (!(getType(obj) === TYPE_OBJECT || subjectArray)) {\n throw typeError('First parameter to value() must be one of: object, array, null.');\n }\n if (subjectArray) {\n if (indexType !== TYPE_NUMBER) throw typeError('value() requires an integer index for arrays');\n index = toInteger(index);\n } else if (indexType !== TYPE_STRING) {\n throw typeError('value() requires a string index for objects');\n }\n const result = getProperty(args[0], index);\n if (result === undefined) {\n if (subjectArray) {\n debug.push(\n `Index: ${index} out of range for array size: ${obj.length}`,\n );\n } else debugAvailable(debug, obj, index);\n return null;\n }\n return result;\n },\n _signature: [\n { types: [TYPE_ANY] },\n { types: [TYPE_STRING, TYPE_NUMBER] },\n ],\n },\n\n /**\n * Generates an array of the values of the provided object.\n * Note that because JSON objects are\n * inherently unordered, the values associated with the provided object are\n * also unordered.\n * @param {object} obj source object\n * @return {array} array of the values\n * @function values\n * @example\n * values({a : 3, b : 4}) // returns [3, 4]\n */\n values: {\n _func: resolvedArgs => Object.values(resolvedArgs[0]),\n _signature: [{ types: [TYPE_OBJECT] }],\n },\n\n /**\n * Extract the day of the week from a date.\n * The specific numbering of the day of week is controlled by the `returnType` parameter:\n *\n * * 1 : Sunday (1), Monday (2), ..., Saturday (7)\n * * 2 : Monday (1), Tuesday (2), ..., Sunday(7)\n * * 3 : Monday (0), Tuesday (1), ...., Sunday(6)\n * @param {number|number[]} date <<_date_and_time_values, date/time value>> for\n * which the day of the week is to be returned.\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @param {integer|integer[]} [returnType=1] Determines the\n * representation of the result.\n * An unrecognized returnType will result in a error.\n * @returns {integer|integer[]} day of the week\n * @function weekday\n * @example\n * weekday(datetime(2006,5,21)) // 1\n * weekday(datetime(2006,5,21), 2) // 7\n * weekday(datetime(2006,5,21), 3) // 6\n */\n weekday: {\n _func: resolvedArgs => {\n const args = resolvedArgs.slice();\n if (args.length < 2) args.push(1);\n return evaluate(args, weekdayFn);\n },\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n { types: [TYPE_NUMBER], optional: true },\n ],\n },\n\n /**\n * Finds the year of a datetime value\n * @param {number|number[]} date input <<_date_and_time_values, date/time value>>\n * Date/time values can be generated using the\n * [datetime]{@link datetime}, [toDate]{@link todate}, [today]{@link today}, [now]{@link now}\n * and [time]{@link time} functions.\n * @return {integer|integer[]} The year value\n * @function year\n * @example\n * year(datetime(2008,5,23)) // returns 2008\n */\n year: {\n _func: args => evaluate(args, a => getDateObj(a).getFullYear()),\n _signature: [\n { types: [TYPE_NUMBER, TYPE_ARRAY_NUMBER] },\n ],\n },\n\n /**\n * Generates a convolved (zipped) array containing grouped arrays of values from\n * the array arguments from index 0, 1, 2, etc.\n * This function accepts a variable number of arguments.\n * The length of the returned array is equal to the length of the shortest array.\n * @param {...array} arrays array of arrays to zip together\n * @return {array} An array of arrays with elements zipped together\n * @function zip\n * @example\n * zip([1, 2, 3], [4, 5, 6, 7]) // returns [[1, 4], [2, 5], [3, 6]]\n */\n zip: {\n _func: args => {\n const count = args.reduce((min, current) => Math.min(min, current.length), args[0].length);\n const result = new Array(count);\n for (let i = 0; i < count; i += 1) {\n result[i] = [];\n args.forEach(a => {\n result[i].push(a[i]);\n });\n }\n return result;\n },\n _signature: [{ types: [TYPE_ARRAY], variadic: true }],\n },\n };\n return functionMap;\n}\n","/*\nCopyright 2014 James Saryerwinnie\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable max-classes-per-file */\n/* eslint-disable no-underscore-dangle */\nimport TreeInterpreter from './TreeInterpreter.js';\nimport Parser from './Parser.js';\nimport { dataTypes } from './dataTypes.js';\nimport { matchType, getType, isArrayType } from './matchType.js';\nimport functions from './functions.js';\nimport {\n isObject, strictDeepEqual, getValueOf,\n} from './utils.js';\nimport {\n evaluationError, typeError, functionError,\n} from './errors.js';\n\n// Type constants used to define functions.\nconst { TYPE_OBJECT } = dataTypes;\n\nfunction getToNumber(stringToNumber) {\n return value => {\n const n = getValueOf(value); // in case it's an object that implements valueOf()\n if (n === null) return 0;\n if (n instanceof Array) {\n throw typeError('Failed to convert array to number');\n }\n const type = typeof n;\n if (type === 'number') return n;\n if (type === 'string') return stringToNumber(n);\n if (type === 'boolean') return n ? 1 : 0;\n throw typeError('Failed to convert object to number');\n };\n}\nfunction toString(a) {\n if (a === null || a === undefined) return '';\n const type = getType(a);\n if (isArrayType(type)) {\n throw typeError('Failed to convert array to string');\n }\n if (type === TYPE_OBJECT) {\n throw typeError('Failed to convert object to string');\n }\n return a.toString();\n}\n\nconst defaultStringToNumber = (str => {\n const n = +str;\n return Number.isNaN(n) ? 0 : n;\n});\n\nclass Runtime {\n constructor(debug, toNumber, customFunctions = {}) {\n this.strictDeepEqual = strictDeepEqual;\n this.toNumber = toNumber;\n this.functionTable = functions(\n this,\n isObject,\n toNumber,\n getType,\n isArrayType,\n getValueOf,\n toString,\n debug,\n );\n\n Object.entries(customFunctions).forEach(([fname, func]) => {\n // Provide the runtime to custom functions so that\n // they can implement lambda functions\n // eslint-disable-next-line no-param-reassign\n func._runtime = this;\n this.functionTable[fname] = func;\n });\n }\n\n // eslint-disable-next-line class-methods-use-this\n _validateArgs(argName, args, signature, bResolved) {\n // Validating the args requires validating\n // the correct arity and the correct type of each arg.\n // If the last argument is declared as variadic, then we need\n // a minimum number of args to be required. Otherwise it has to\n // be an exact amount.\n if (signature.length === 0 && args.length > 0) {\n throw functionError(`${argName}() does not accept parameters`);\n }\n\n if (signature.length === 0) {\n return;\n }\n let pluralized;\n const argsNeeded = signature.filter(arg => !arg.optional).length;\n const lastArg = signature[signature.length - 1];\n if (lastArg.variadic) {\n if (args.length < signature.length && !lastArg.optional) {\n pluralized = signature.length === 1 ? ' argument' : ' arguments';\n throw functionError(`${argName}() takes at least ${signature.length}${pluralized\n } but received ${args.length}`);\n }\n } else if (args.length < argsNeeded || args.length > signature.length) {\n pluralized = signature.length === 1 ? ' argument' : ' arguments';\n throw functionError(`${argName}() takes ${signature.length}${pluralized\n } but received ${args.length}`);\n }\n // if the arguments are unresolved, there's no point in validating types\n if (!bResolved) return;\n let currentSpec;\n const limit = signature[signature.length - 1].variadic ? args.length\n : Math.min(signature.length, args.length);\n\n for (let i = 0; i < limit; i += 1) {\n currentSpec = i > signature.length - 1 ? signature[signature.length - 1].types\n : signature[i].types;\n // eslint-disable-next-line no-param-reassign\n args[i] = matchType(currentSpec, args[i], argName, this.toNumber, toString);\n }\n }\n\n callFunction(name, resolvedArgs, data, interpreter, bResolved = true) {\n // this check will weed out 'valueOf', 'toString' etc\n if (!Object.prototype.hasOwnProperty.call(this.functionTable, name)) {\n throw functionError(`No such function: ${name}()`);\n }\n\n const functionEntry = this.functionTable[name];\n this._validateArgs(name, resolvedArgs, functionEntry._signature, bResolved);\n return functionEntry._func.call(this, resolvedArgs, data, interpreter);\n }\n}\n\nexport default class Formula {\n constructor(debug, customFunctions, stringToNumberFn) {\n this.debug = debug;\n this.toNumber = getToNumber(stringToNumberFn || defaultStringToNumber);\n this.runtime = new Runtime(debug, this.toNumber, customFunctions);\n }\n\n compile(stream, allowedGlobalNames = []) {\n const parser = new Parser(allowedGlobalNames);\n return parser.parse(stream, this.debug);\n }\n\n search(node, data, globals = {}, language = 'en-US') {\n // This needs to be improved. Both the interpreter and runtime depend on\n // each other. The runtime needs the interpreter to support exprefs.\n // There's likely a clean way to avoid the cyclic dependency.\n this.runtime.interpreter = new TreeInterpreter(\n this.runtime,\n globals,\n this.toNumber,\n toString,\n this.debug,\n language,\n );\n\n try {\n return this.runtime.interpreter.search(node, data);\n } catch (e) {\n this.debug.push(e.message || e.toString());\n if (e.name === 'Error') throw evaluationError(e.message || e.toString());\n throw e;\n }\n }\n}\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport Formula from './interpreter.js';\n\n// data type constants re-exported from dataTypes.js\n// which represent the various data types supported by json-formula function params\nexport { dataTypes } from './dataTypes.js';\n/**\n@enum {Number}\n // Type constants used to define functions.\n const dataTypes = {\n TYPE_NUMBER: 0,\n TYPE_ANY: 1,\n TYPE_STRING: 2,\n TYPE_ARRAY: 3,\n TYPE_OBJECT: 4,\n TYPE_BOOLEAN: 5,\n TYPE_EXPREF: 6,\n TYPE_NULL: 7,\n TYPE_ARRAY_NUMBER: 8,\n TYPE_ARRAY_STRING: 9,\n TYPE_ARRAY_ARRAY: 10,\n TYPE_EMPTY_ARRAY: 11,\n };\n */\n\n/**\n * @typedef {object} CustomFunctionDefinition\n * @property {Function} _func - The function implementation\n * @property {array} [_signature] - Function signature metadata\n * @example\n // simple custom functions definition\n const customFunctions = {\n true_fn: {\n _func: () => true,\n _signature: [],\n },\n false_fn: {\n _func: () => false,\n _signature: [],\n },\n };\n @example\n // custom function with a signature for its parameters\n const customFunctions = {\n padEnd: {\n _func: args => {\n const src = args[0];\n const length = args[1];\n const padChar = args[2];\n if (Array.isArray(src)) return src.map(s => s.padEnd(length, padChar));\n return src.padEnd(length, padChar);\n },\n _signature: [\n { types: [TYPE_STRING, TYPE_ARRAY_STRING] },\n { types: [TYPE_NUMBER] },\n { types: [TYPE_STRING] },\n ],\n }\n }\n // May also register functions is via the `register()` or `registerWithParams()` methods. e.g.\n\n const regFormula = `${register(\"${fn_name}\", &${code})`;\n // Run the registration formula after which, the registered function may be called\n this.search(regFormula, {});\n*/\n\n/**\n * Class represents an instance of a JsonFormula Expression that can be executed later on with\n * multiple instances of JSON Data. The instance of the class has a search\n * function that can be used to evaluate the expression on a json payload.\n */\nclass JsonFormula {\n /**\n * @param {object} [customFunctions={}] custom functions needed by a hosting application.\n * @param {function} [stringToNumber='null'] A function that converts string values to numbers.\n * Can be used to convert currencies/dates to numbers\n * @param {array} [debug=[]] will be populated with any errors/warnings\n */\n constructor(\n customFunctions = {},\n stringToNumber = null,\n debug = [],\n ) {\n this.customFunctions = { ...customFunctions };\n this.stringToNumber = stringToNumber;\n this.debug = debug;\n this.formula = new Formula(debug, customFunctions, stringToNumber);\n }\n\n /**\n * @typedef {object} globals\n * An object where each key **MUST** begin with a `$` character, representing global variables\n * that can be accessed inside a json-formula expression.\n * The value of each key can be of any data type supported by json.\n *\n * @example\n * const globals = {\n * $num: 42,\n * $arr: [1, 2, 3],\n * $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n * };\n * jsonFormula({}, globals, '$arr * $num') // returns [42, 84, 126]\n */\n\n /**\n * Evaluates the JsonFormula on a particular json payload and return the result\n * @param {string} expression the json-formula expression to evaluate\n * @param {object|array} json the json data on which the expression needs to be evaluated\n * @param {object} [globals={}] global objects that can be accessed via custom functions.\n * @param {string} [language=en-US] BCP-47 language tag\n * @returns {*} the result of the expression being evaluated\n * @example\n * const jf = new JsonFormula();\n * const result = jf.search('toDate(d) | day(@) & \"/\" & month(@)', {d: \"2025-11-12\"});\n * // returns \"12/11\"\n */\n search(expression, json, globals = {}, language = 'en-US') {\n const ast = this.compile(expression, Object.keys(globals));\n return this.run(ast, json, language, globals);\n }\n\n /**\n * Execute a previously compiled expression against a json object and return the result.\n * Use this method for better performance when you will evaluate the same expression\n * multiple times with different data.\n * @param {object} ast The abstract syntax tree returned from compile()\n * @param {object|array} json the json data on which the expression needs to be evaluated\n * @param {string} [language=en-US] BCP-47 language tag\n * @param globals {*} set of objects available in global scope\n * @returns {*} the result of the expression being evaluated\n * @example\n * const globals = {\n * $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n * };\n * const jf = new JsonFormula();\n * const ast = jf.compile('value($days, num)', ['$days']); // compile the expression once\n * const result1 = jf.run(ast, {num: 2}, 'en-US', globals); // returns \"Wed\"\n * const result2 = jf.run(ast, {num: 3}, 'en-US', globals); // returns \"Thu\"\n */\n run(ast, json, language, globals) {\n return this.formula.search(\n ast,\n json,\n globals,\n language,\n );\n }\n\n /**\n * Creates a compiled expression that can be executed later on with some data.\n * @param {string} expression the expression to evaluate\n * @param {string[]} [allowedGlobalNames=[]] An array of names of the global variables\n * being used in the expression.\n */\n compile(expression, allowedGlobalNames = []) {\n this.debug.length = 0;\n return this.formula.compile(expression, allowedGlobalNames);\n }\n}\n\n/**\n * Compile and execute a json-formula expression.\n * If executing the same expression multiple times, it is more efficient to create a\n * class instance of JsonFormula and call the search() method or the compile()/run() methods\n * multiple times.\n* @param {object|array} json the json data on which the expression needs to be evaluated\n* @param {object} globals global objects that can be accessed via custom functions.\n* @param {string} expression the expression to evaluate\n* @param {object} [customFunctions={}] custom functions needed by a hosting application.\n* @param {function} [stringToNumber='null'] A function that converts string values to numbers.\n* Can be used to convert currencies/dates to numbers\n* @param {string} [language=en-US]\n* @param {array} [debug=[]] will be populated with any errors/warnings\n* @returns {*} the result of the expression being evaluated\n */\n\nexport function jsonFormula(\n json,\n globals,\n expression,\n customFunctions = {},\n stringToNumber = null,\n debug = [],\n language = 'en-US',\n) {\n return new JsonFormula(customFunctions, stringToNumber, debug)\n .search(expression, json, globals, language);\n}\n\nexport default JsonFormula;\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable no-param-reassign */\n/* eslint-disable max-classes-per-file */\n/* eslint-disable class-methods-use-this */\n/* eslint-disable no-underscore-dangle */\n/*\n Field class allows objects to evaluate correctly according to context.\n - if used in an expression, will return a value or string.\n - for JSON.stringify() returns a scalar\n - BUT also allows explicit access to properties. e.g. field.required, field.name etc.\n\n Should allow us to eliminate getFieldProperty()\n */\nclass ArrayClass extends Array {}\nclass ObjectClass {}\n\nfunction createField(name, value, readonly = false, required = true) {\n class Field extends ObjectClass {\n valueOf() { return value; }\n\n toString() { return value.toString(); }\n\n toJSON() { return value; }\n }\n const f = new Field();\n Object.defineProperty(f, '$name', { get: () => name });\n Object.defineProperty(f, '$value', { get: () => value });\n Object.defineProperty(f, '$readonly', { get: () => readonly });\n Object.defineProperty(f, '$required', { get: () => required });\n\n return f;\n}\n\nfunction createFieldset(fsname, isObj, fields, children) {\n class FieldsetObj extends ObjectClass {\n _add(k, v) {\n this[k] = v;\n children.push(v);\n }\n }\n class FieldsetArray extends ArrayClass {\n _add(k, v) {\n this[k] = v;\n children.push(v);\n }\n }\n const fieldset = isObj ? new FieldsetObj() : new FieldsetArray();\n Object.defineProperty(fieldset, '$name', { get: () => fsname });\n Object.defineProperty(fieldset, '$fields', { get: () => fields });\n Object.defineProperty(fieldset, '$value', { get: () => fieldset.valueOf() });\n\n return fieldset;\n}\n\nfunction createFields(parent, childref, child) {\n const result = [];\n if (child instanceof Array) {\n // parent._add(childref, createFieldset(childref, false));\n parent._add(childref, createFieldset(childref, false, result, []));\n child.forEach((item, index) => {\n const fields = createFields(parent[childref], index, item);\n result.push(...fields);\n });\n } else if (child !== null && typeof child === 'object') {\n parent._add(childref, createFieldset(childref, true, result, []));\n Object.keys(child).forEach(k => {\n const fields = createFields(parent[childref], k, child[k]);\n result.push(...fields);\n });\n } else {\n const field = createField(childref, child);\n parent._add(childref, field);\n result.push(field);\n }\n return result;\n}\n\nexport default function createForm(dataRoot) {\n // if it's not an object or array (a scalar) then don't bother trying to create a form\n if (dataRoot === null || typeof dataRoot !== 'object') return dataRoot;\n\n const allFields = [];\n const form = createFieldset('', !Array.isArray(dataRoot), allFields, []);\n Object.entries(dataRoot).forEach(([k, v]) => {\n allFields.push(...createFields(form, k, v));\n });\n return form;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { typeError } from './errors.js';\n\nexport default function stringToNumber(n) {\n if (!/^\\s*(-|\\+)?(\\d*)(\\.\\d+)?(e(\\+|-)?\\d+)?\\s*$/i.test(n)) throw typeError(`Failed to convert \"${n}\" to number`);\n const ret = +n;\n if (Number.isNaN(ret)) {\n throw typeError(`Failed to convert \"${n}\" to number`);\n }\n return ret;\n}\n","/*\nCopyright 2021 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* global window, document */\nimport Formula from '../src/json-formula.js';\nimport createForm from './Form.js';\nimport stringToNumber from '../src/stringToNumber.js';\n\nwindow.addEventListener('load', () => {\n const dataElement = document.getElementById('data');\n const expression = document.getElementById('expression');\n const result = document.getElementById('result');\n const debug = document.getElementById('debug');\n const debugInfo = [];\n // keep one instance active for the entire session so that any registered\n // functions are retained\n const formula = new Formula({}, stringToNumber, debugInfo);\n const defaultData = `{\n \"address\": {\n \"street\": \"12 Oak St\",\n \"city\": \"San Jose\",\n \"state\": \"CA\",\n \"country\": \"USA\",\n \"phone\": \"1234561234\"\n },\n \"items\": [\n {\n \"desc\": \"pens\",\n \"quantity\": 2,\n \"price\": 3.23\n },\n {\n \"desc\": \"pencils\",\n \"quantity\": 3,\n \"price\": 1.34\n }\n ],\n \"tax\": 1.13\n }`;\n\n const params = new URLSearchParams(document.location.search);\n if (params.has('sample')) {\n const sampleJSON = JSON.parse(atob(params.get('sample')));\n if (sampleJSON.data) dataElement.value = JSON.stringify(sampleJSON.data, null, 2);\n if (sampleJSON.expression) expression.value = sampleJSON.expression;\n if (sampleJSON.description) {\n document.getElementById('description-row').style.display = 'table-row';\n document.getElementById('description').innerText = sampleJSON.description;\n }\n Array.from(document.getElementsByClassName('controls')).forEach(c => c.classList.add('hidden'));\n } else {\n const d = window.localStorage.getItem('data');\n if (d) dataElement.value = d;\n else dataElement.value = defaultData;\n const exp = window.localStorage.getItem('expression');\n if (exp) expression.value = exp;\n else expression.value = 'sum(items[*].price * items[*].quantity)';\n }\n\n function run() {\n // save for next time...\n window.localStorage.setItem('data', dataElement.value);\n window.localStorage.setItem('expression', expression.value);\n const input = expression.value;\n const useFields = document.getElementById('use-fields').checked;\n let jsonData;\n try {\n jsonData = JSON.parse(dataElement.value);\n if (useFields) {\n jsonData = createForm(jsonData);\n }\n } catch (e) {\n result.value = e.toString();\n return;\n }\n\n try {\n const jsonResult = formula.search(input, jsonData, {});\n debug.innerHTML = debugInfo.join('\\n');\n let r = jsonResult;\n if (jsonResult !== null && jsonResult !== undefined) {\n r = jsonResult.valueOf.call(jsonResult);\n }\n if (typeof r === 'object') {\n result.value = JSON.stringify(r, null, 2);\n } else {\n result.value = r;\n }\n } catch (e) {\n result.value = e.toString();\n debug.innerHTML = debugInfo.join('\\n');\n }\n }\n\n dataElement.addEventListener('blur', run);\n expression.addEventListener('blur', run);\n document.getElementById('data-reset').addEventListener(\n 'click',\n () => {\n dataElement.value = defaultData;\n if (params.has('sample')) {\n expression.value = 'sum(items[*].price * items[*].quantity)';\n document.getElementById('description-row').style.display = 'none';\n Array.from(document.getElementsByClassName('controls')).forEach(c => c.classList.remove('hidden'));\n window.history.pushState({}, document.title, '/');\n run();\n }\n },\n );\n document.getElementById('canned').addEventListener('change', e => {\n expression.value = e.target.value;\n run();\n });\n run();\n\n fetch('../antlr/JsonFormula.g4').then(r => {\n r.text().then(g4 => {\n // remove comments and processing directives.\n const strippedGrammar = g4\n .replace(/[\\s\\S.]*grammar/m, 'grammar')\n .replace(/#.*/g, '');\n document.getElementById('grammar-out').innerHTML = strippedGrammar;\n });\n });\n});\n"],"names":["__webpack_require__","exports","Symbol","toStringTag","Object","defineProperty","value","dataTypes","TYPE_NUMBER","TYPE_ANY","TYPE_STRING","TYPE_ARRAY","TYPE_OBJECT","TYPE_BOOLEAN","TYPE_EXPREF","TYPE_NULL","TYPE_ARRAY_NUMBER","TYPE_ARRAY_STRING","TYPE_ARRAY_ARRAY","TYPE_EMPTY_ARRAY","typeNameTable","TOK_EOF","TOK_IDENTIFIER","TOK_QUOTEDIDENTIFIER","TOK_RBRACKET","TOK_RPAREN","TOK_COMMA","TOK_COLON","TOK_CONCATENATE","TOK_RBRACE","TOK_NUMBER","TOK_CURRENT","TOK_GLOBAL","TOK_EXPREF","TOK_PIPE","TOK_OR","TOK_AND","TOK_ADD","TOK_SUBTRACT","TOK_UNARY_MINUS","TOK_MULTIPLY","TOK_UNION","TOK_DIVIDE","TOK_COMPARATOR","TOK_FLATTEN","TOK_STAR","TOK_FILTER","TOK_DOT","TOK_NOT","TOK_LBRACE","TOK_LBRACKET","TOK_LPAREN","TOK_JSON","TOK_STRING","TOK_INT","typeError","desc","TypeError","syntaxError","e","Error","name","functionError","evaluationError","tokenDefinitions","isArray","t","includes","getType","inputObj","simpleType","obj","Array","length","flat","Infinity","every","a","jmespathType","type","JSON","parse","stringify","isArrayType","getTypeName","arg","matchType","expectedList","argValue","context","toNumber","toString","actual","isObject","some","match","expect","found","filteredList","filter","supportedConversion","to","exactMatch","expected","wrongType","map","join","keys","toArray","coerceString","coerceNumber","prototype","call","getValueOf","i","valueOf","toBoolean","param","val","strictDeepEqual","lhs","rhs","first","second","f","key","hasOwnProperty","getProperty","getOwnPropertyDescriptor","enumerable","get","for","debugAvailable","debug","chainStart","available","push","entries","getOwnPropertyDescriptors","k","test","startsWith","balanceArrayOperands","opLeft","opRight","shorter","diff","Math","abs","fill","TreeInterpreter","constructor","runtime","globals","language","this","visitFunctions","initVisitFunctions","debugChainStart","search","node","visit","field","undefined","Identifier","bind","QuotedIdentifier","ChainedExpression","result","children","BracketExpression","left","Index","index","Slice","sliceParams","start","stop","step","computeSliceParams","Projection","base","collected","forEach","b","current","ValueProjection","projection","values","FilterProjection","filtered","finalResults","Comparator","type1","type2","_e","original","merged","Identity","_node","ArrayExpression","child","ObjectExpression","OrExpression","matched","AndExpression","AddExpression","applyOperator","ConcatenateExpression","UnionExpression","concat","SubtractExpression","MultiplyExpression","DivideExpression","NotExpression","UnaryMinusExpression","minus","Number","isNaN","String","Literal","Integer","Function","callFunction","resolvedArgs","ExpressionReference","refNode","n","v","arrayLength","capSliceRange","arrayLen","stp","actualValue","stepValueNegative","operator","n1","n2","isFinite","basicTokens","operatorStartToken","skipChars","isAlphaNum","ch","isIdentifier","stream","pos","Lexer","allowedGlobalNames","_allowedGlobalNames","tokenize","tokens","identifier","token","_current","prev","slice","_isGlobal","_consumeGlobal","_consumeUnquotedIdentifier","_isNumber","_consumeNumber","_consumeLBracket","_consumeQuotedIdentifier","_consumeRawStringLiteral","json","_consumeJson","_consumeOperator","_consumeUnaryMinus","maxLength","foundNonAlpha","replace","substring","literal","num","toLowerCase","parseFloat","parseInt","global","startingChar","literalString","trimStart","replaceAll","bindingPower","Parser","expression","_loadTokens","ast","_lookahead","_lookaheadToken","rbp","leftToken","_advance","nud","currentToken","led","number","previous","next","_lookAheadIndex","idx","_getIndex","_setIndex","right","args","Not","UnaryMinus","_parseProjectionRHS","Star","_parseObjectExpression","Flatten","_parseIndexExpression","_projectIfSlice","_parseArrayExpression","Expref","_match","_errorToken","condition","leftNode","rightNode","Concatenate","Dot","_parseDotRHS","Pipe","Or","And","Add","Subtract","Multiply","Divide","Union","_parseFunctionArgs","Filter","_parseComparator","tokenType","firstExpression","_parseSignedInt","oldIndex","_parseSliceExpression","indexExpr","parts","comparator","lookahead","indexOf","expressions","pairs","identifierTypes","keyToken","keyName","MS_IN_DAY","getDateObj","dateNum","Date","round","getDateNum","dateObj","validNumber","defaultStringToNumber","str","Runtime","customFunctions","functionTable","toInteger","trunc","toJSON","indent","offset","evaluate","fn","listOfArrays","maxLen","max","allArrays","arrays","row","j","balanceArrays","datedifFn","date1Arg","date2Arg","unitArg","unit","date1","date2","floor","yearDiff","getFullYear","monthDiff","getMonth","dayDiff","getDate","y","setFullYear","endsWithFn","searchArg","suffixArg","searchStr","suffix","from","reverse","c","eomonthFn","dateArg","monthsArg","jsDate","months","findFn","queryArg","textArg","offsetArg","query","text","properFn","capitalize","word","charAt","toUpperCase","wordParts","w","reptFn","countArg","count","repeat","searchFn","findTextString","withinTextString","startPosInt","findText","withinText","startPos","globString","reduce","acc","cur","escape","pop","testMatch","array","glob","testChar","globChar","nextGlob","isStar","within","splitFn","strArg","separatorArg","separator","split","startsWithFn","subjectString","prefixString","subject","prefix","substituteFn","source","oldString","replacementString","nearest","src","old","replacement","whch","truncFn","d","digits","ceil","weekdayFn","date","day","getDay","functionMap","_func","_signature","types","acos","and","variadic","asin","atan2","avg","sum","avgA","casefold","_data","interpreter","s","toLocaleUpperCase","toLocaleLowerCase","codePoint","codePointAt","contains","searchLen","cos","datedif","datetime","year","month","hours","minutes","seconds","ms","optional","deepScan","checkArrays","items","scan","endsWith","eomonth","exp","false","find","fromCodePoint","points","fromEntries","fround","hasProperty","keyType","hour","getHours","if","unresolvedArgs","data","conditionNode","leftBranchNode","rightBranchNode","listJoin","joinChar","numEntries","log","log10","lower","exprefNode","maxA","merge","mid","millisecond","getMilliseconds","min","minA","minute","getMinutes","mod","not","resolveArgs","notNull","now","null","or","power","proper","random","accumulated","register","functionName","_exprefNode","registerWithParams","numElements","sourceArray","splice","newText","rept","originalStr","precision","getSeconds","sign","sin","sort","typeVals","sorted","sortFunction","sortBy","sortedArray","requiredType","decorated","exprA","typeA","exprB","typeB","sqrt","stdev","mean","sumSquare","stdevA","stdevp","meanSumSquare","stdevpA","substitute","o","tan","time","toDate","iso","dateparts","x","range","getTime","today","toNumberFn","digitCheck","p","trim","decimal","errorString","true","unique","valueArray","findIndex","lookup","upper","indexType","subjectArray","weekday","zip","functions","fname","func","_runtime","_validateArgs","argName","signature","bResolved","pluralized","argsNeeded","lastArg","currentSpec","limit","functionEntry","Formula","stringToNumberFn","stringToNumber","getToNumber","compile","message","formula","run","ArrayClass","ObjectClass","createFieldset","fsname","isObj","fields","fieldset","_add","createFields","parent","childref","item","readonly","required","createField","ret","window","addEventListener","dataElement","document","getElementById","debugInfo","defaultData","params","URLSearchParams","location","has","sampleJSON","atob","description","style","display","innerText","getElementsByClassName","classList","add","localStorage","getItem","setItem","input","useFields","checked","jsonData","dataRoot","allFields","form","createForm","jsonResult","innerHTML","r","remove","history","pushState","title","target","fetch","then","g4","strippedGrammar"],"sourceRoot":""} \ No newline at end of file diff --git a/doc/output/JSDOCS.md b/doc/output/JSDOCS.md index f895c3dd..562ccccd 100644 --- a/doc/output/JSDOCS.md +++ b/doc/output/JSDOCS.md @@ -8,25 +8,24 @@ function that can be used to evaluate the expression on a json payload. **Kind**: global class * [JsonFormula](#JsonFormula) - * [new JsonFormula([customFunctions], [stringToNumber], [language], [debug])](#new_JsonFormula_new) - * [.search(json, [globals])](#JsonFormula+search) ⇒ \* - * [.run(ast, json, globals)](#JsonFormula+run) ⇒ \* - * [.compile(expression, [allowedGlobalNames], [debug])](#JsonFormula+compile) + * [new JsonFormula([customFunctions], [stringToNumber], [debug])](#new_JsonFormula_new) + * [.search(expression, json, [globals], [language])](#JsonFormula+search) ⇒ \* + * [.run(ast, json, [language], globals)](#JsonFormula+run) ⇒ \* + * [.compile(expression, [allowedGlobalNames])](#JsonFormula+compile) -### new JsonFormula([customFunctions], [stringToNumber], [language], [debug]) +### new JsonFormula([customFunctions], [stringToNumber], [debug]) | Param | Type | Default | Description | | --- | --- | --- | --- | | [customFunctions] | object | {} | custom functions needed by a hosting application. | | [stringToNumber] | function | 'null' | A function that converts string values to numbers. Can be used to convert currencies/dates to numbers | -| [language] | string | "en-US" | | | [debug] | array | [] | will be populated with any errors/warnings | -### jsonFormula.search(json, [globals]) ⇒ \* +### jsonFormula.search(expression, json, [globals], [language]) ⇒ \* Evaluates the JsonFormula on a particular json payload and return the result **Kind**: instance method of [JsonFormula](#JsonFormula) @@ -34,26 +33,47 @@ Evaluates the JsonFormula on a particular json payload and return the result | Param | Type | Default | Description | | --- | --- | --- | --- | +| expression | string | | the json-formula expression to evaluate | | json | object \| array | | the json data on which the expression needs to be evaluated | | [globals] | object | {} | global objects that can be accessed via custom functions. | - +| [language] | string | "en-US" | BCP-47 language tag | + +**Example** +```js +const jf = new JsonFormula(); +const result = jf.search('toDate(d) | day(@) & "/" & month(@)', {d: "2025-11-12"}); +// returns "12/11" +``` -### jsonFormula.run(ast, json, globals) ⇒ \* -Execute a previously compiled expression against a json object and return the result +### jsonFormula.run(ast, json, [language], globals) ⇒ \* +Execute a previously compiled expression against a json object and return the result. +Use this method for better performance when you will evaluate the same expression +multiple times with different data. **Kind**: instance method of [JsonFormula](#JsonFormula) **Returns**: \* - the result of the expression being evaluated -| Param | Type | Description | -| --- | --- | --- | -| ast | object | The abstract syntax tree returned from compile() | -| json | object \| array | the json data on which the expression needs to be evaluated | -| globals | \* | set of objects available in global scope | - +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| ast | object | | The abstract syntax tree returned from compile() | +| json | object \| array | | the json data on which the expression needs to be evaluated | +| [language] | string | "en-US" | BCP-47 language tag | +| globals | \* | | set of objects available in global scope | + +**Example** +```js +const globals = { + $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] +}; +const jf = new JsonFormula(); +const ast = jf.compile('value($days, num)', ['$days']); // compile the expression once +const result1 = jf.run(ast, {num: 2}, 'en-US', globals); // returns "Wed" +const result2 = jf.run(ast, {num: 3}, 'en-US', globals); // returns "Thu" +``` -### jsonFormula.compile(expression, [allowedGlobalNames], [debug]) +### jsonFormula.compile(expression, [allowedGlobalNames]) Creates a compiled expression that can be executed later on with some data. **Kind**: instance method of [JsonFormula](#JsonFormula) @@ -61,15 +81,15 @@ Creates a compiled expression that can be executed later on with some data. | Param | Type | Default | Description | | --- | --- | --- | --- | | expression | string | | the expression to evaluate | -| [allowedGlobalNames] | Array.<string> | [] | A list of names of the global variables being used in the expression. | -| [debug] | array | [] | will be populated with any errors/warnings | +| [allowedGlobalNames] | Array.<string> | [] | An array of names of the global variables being used in the expression. | -## jsonFormula(json, globals, expression, [customFunctions], [stringToNumber], [language], [debug]) ⇒ \* +## jsonFormula(json, globals, expression, [customFunctions], [stringToNumber], [debug], [language]) ⇒ \* Compile and execute a json-formula expression. If executing the same expression multiple times, it is more efficient to create a -class instance of {JsonFormula} and call the search method multiple times. +class instance of JsonFormula and call the search() method or the compile()/run() methods +multiple times. **Kind**: global function **Returns**: \* - the result of the expression being evaluated @@ -81,6 +101,74 @@ class instance of {JsonFormula} and call the search method multiple times. | expression | string | | the expression to evaluate | | [customFunctions] | object | {} | custom functions needed by a hosting application. | | [stringToNumber] | function | 'null' | A function that converts string values to numbers. Can be used to convert currencies/dates to numbers | -| [language] | string | "en-US" | | | [debug] | array | [] | will be populated with any errors/warnings | +| [language] | string | "en-US" | BCP-47 language tag | + + +## CustomFunctionDefinition : object +**Kind**: global typedef +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| _func | function | The function implementation | +| [_signature] | array | Function signature metadata | + +**Example** +```js +// simple custom functions definition + const customFunctions = { + true_fn: { + _func: () => true, + _signature: [], + }, + false_fn: { + _func: () => false, + _signature: [], + }, + }; + +``` +**Example** +```js +// custom function with a signature for its parameters + const customFunctions = { + padEnd: { + _func: args => { + const src = args[0]; + const length = args[1]; + const padChar = args[2]; + if (Array.isArray(src)) return src.map(s => s.padEnd(length, padChar)); + return src.padEnd(length, padChar); + }, + _signature: [ + { types: [TYPE_STRING, TYPE_ARRAY_STRING] }, + { types: [TYPE_NUMBER] }, + { types: [TYPE_STRING] }, + ], + } + } + // May also register functions is via the `register()` or `registerWithParams()` methods. e.g. + + const regFormula = `${register("${fn_name}", &${code})`; + // Run the registration formula after which, the registered function may be called + this.search(regFormula, {}); +``` + + +## globals : object +An object where each key **MUST** begin with a `$` character, representing global variables +that can be accessed inside a json-formula expression. +The value of each key can be of any data type supported by json. + +**Kind**: global typedef +**Example** +```js +const globals = { + $num: 42, + $arr: [1, 2, 3], + $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] +}; +jsonFormula({}, globals, '$arr * $num') // returns [42, 84, 126] +``` diff --git a/doc/output/json-formula-specification-2.0.0.html b/doc/output/json-formula-specification-2.0.0.html new file mode 100644 index 00000000..088c4126 --- /dev/null +++ b/doc/output/json-formula-specification-2.0.0.html @@ -0,0 +1,8276 @@ + + + + + + + + +json-formula Specification + + + + + +
+ +
+

Scope

+
+
+

This document is the specification for json-formula, an expression grammar that operates on JSON (JavaScript Object Notation) documents. The referenced JSON documents and JSON literals must conform to RFC 8259.

+
+
+

The grammar borrows from

+
+
+
    +
  • +

    OpenFormula for spreadsheet operators and function

    +
  • +
  • +

    JMESPath for JSON query semantics

    +
  • +
+
+
+

The intended audience are both end-users of json-formula as well as implementers; the contents are then both a user guide and a specification.

+
+
+
+
+

1. Notation

+
+
+

In the specification, examples are shown through the use of a search function called eval. The syntax for this function is:

+
+
+
+
eval(<json-formula expr>, <JSON document>) -> <return value>
+
+
+
+

For simplicity, the json-formula expression and the JSON document are not quoted. For example:

+
+
+
+
eval(foo, {"foo": "bar"}) -> "bar"
+
+
+
+

The result of applying a json-formula expression against a JSON document will result in valid JSON, provided there are no errors during the evaluation process.

+
+
+
+
+

2. Data Types

+
+
+

json-formula supports all the JSON types:

+
+
+
    +
  • +

    number: All numbers are internally represented as double-precision floating-point

    +
  • +
  • +

    string

    +
  • +
  • +

    boolean: true or false

    +
  • +
  • +

    array: an ordered, sequence of values

    +
  • +
  • +

    object: an unordered collection of key value pairs

    +
  • +
  • +

    null

    +
  • +
+
+
+

There is an additional type that is not a JSON type that’s used in json-formula functions:

+
+
+
    +
  • +

    expression: A string prefixed with an ampersand (&) character

    +
  • +
+
+
+

This specification uses the term "scalar" to refer to any value that is not an array, object or expression. Scalars include numbers, strings, booleans, and null values.

+
+
+

2.1. Type Coercion

+
+

If the supplied data is not correct for the execution context, json-formula will attempt to coerce the data to the correct type. Coercion will occur in these contexts:

+
+
+
    +
  • +

    Operands of the concatenation operator (&) shall be coerced to a string, except when an operand is an array. Arrays shall be coerced to an array of strings.

    +
  • +
  • +

    Operands of numeric operators (+, -, *, /) shall be coerced to numbers except when the operand is an array. Arrays shall be coerced to an array of numbers.

    +
  • +
  • +

    Operands of the union operator (~) shall be coerced to an array

    +
  • +
  • +

    The left-hand operand of ordering comparison operators (>, >=, <, <=) must be a string or number. Any other type shall be coerced to a number.

    +
  • +
  • +

    If the operands of an ordering comparison are different, they shall both be coerced to a number

    +
  • +
  • +

    Parameters to functions shall be coerced when there is a single viable coercion available. For example, if a null value is provided to a function that accepts a number or string, then coercion shall not happen, since a null value can be coerced to both types. Conversely if a string is provided to a function that accepts a number or array of numbers, then the string shall be coerced to a number, since there is no supported coercion to convert it to an array of numbers.

    +
  • +
+
+
+

The equality and inequality operators (=, ==, !=, <>) do not perform type coercion. If operands are different types, the values are considered not equal.

+
+
+

If an ordering comparison requires coercion, and the coercion is not possible (including the case where a string cannot be coerced to a number), the comparison will return false. e.g., {a: 12} < 12 and "12a" < 13 will each return false.

+
+
+

In all cases except ordering comparison, if the coercion is not possible, a TypeError error shall be raised.

+
+

Examples

+
+
+
    eval("abc" & 123, {}) -> "abc123"
+    eval("123" * 2, {}) -> 246
+    eval([1,2,3] ~ 4, {}) -> [1,2,3,4]
+    eval(123 < "124", {}) -> true
+    eval("23" > 111, {}) -> false
+    eval(avgA(["2", "3", "4"]), {}) -> 3
+    eval(1 == "1", {}) -> false
+
+
+
+
+

2.2. Type Coercion Rules

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Provided TypeExpected TypeResult

number

string

number converted to a string, following the JavaScript toString() rules.

boolean

string

"true" or "false"

array

string

Not supported

object

string

Not supported

null

string

"" (empty string)

string

number

Parse the string to a number. An empty string converts to zero. If the string is not a well-formed number, the coercion will fail.

boolean

number

true → 1 false → 0

array

number

Not supported

object

number

Not supported

null

number

0

number

array

create a single-element array with the number

string

array

create a single-element array with the string

boolean

array

create a single-element array with the boolean

object

array

Not supported

null

array

Not supported

number

object

Not supported

string

object

Not supported

boolean

object

Not supported

array

object

Not supported. Use: fromEntries(entries(array))

null

object

Not supported

number

boolean

zero is false, all other numbers are true

string

boolean

Empty string is false, populated strings are true

array

boolean

Empty array is false, populated arrays are true

object

boolean

Empty object is false, populated objects are true

null

boolean

false

+
+

An array may be coerced to another type of array as long as there is a supported coercion for the array content. For example, just as a string can be coerced to a number, an array of strings may be coerced to an array of numbers.

+
+
+

Note that while strings, numbers and booleans may be coerced to arrays, they may not be coerced to a different type within that array. For example, a number cannot be coerced to an array of strings — even though a number can be coerced to a string, and a string can be coerced to an array of strings.

+
+

Examples

+
+
+
    eval("\"$123.00\" + 1", {}) -> TypeError
+    eval("truth is " & `true`, {}) -> "truth is true"
+    eval(2 + `true`, {}) -> 3
+    eval(minA(["20", "30"]), {}) -> 20
+
+
+
+
+

2.3. Date and Time Values

+
+

In order to support date and time functions, json-formula represents date and time values as numbers where:

+
+
+
    +
  • +

    The integral portion of the number represents the number of days since the epoch: January 1, 1970, UTC

    +
  • +
  • +

    The fractional portion of the number represents the fractional portion of the day

    +
  • +
  • +

    The date/time value is offset from the current time zone to UTC

    +
  • +
  • +

    The current time zone is determined by the host operating system

    +
  • +
+
+
+

The preferred ways to create a date/time value are by using one of these functions:

+
+
+ +
+
+

Functions that operate on a date/time value will convert the date/time value back to the local time zone.

+
+

Examples

+
+
+
    eval(datetime(1970,1,2,0,0,0) - datetime(1970,1,1,0,0,0), {}) -> 1
+    eval(datetime(2010,1,21,12,0,0) |
+      {month: month(@), day: day(@), hour: hour(@)}, {}) ->
+        {"month": 1, "day": 21, "hour": 12}
+
+
+
+
+

2.4. Integers

+
+

Some functions and operators accept numeric parameters that are expected to be integers. In these contexts, if a non-numeric or non-integer value is provided, it will be coerced to a number and then truncated. The specific truncation behaviour is to remove any fractional value without rounding.

+
+
+
+

2.5. Floating Point Precision

+
+

Numbers are represented in double-precision floating-point format. As with any system that uses this level of precision, results of expressions may be off by a tiny fraction. e.g. +10 * 1.44 → 14.399999999999999

+
+
+

Authors should mitigate this behavior:

+
+
+
    +
  • +

    When comparing fractional results, do not compare for exact equality. Instead, compare within a range. e.g.: instead of: a == b, use: abs(a-b) < 0.000001

    +
  • +
  • +

    leverage the built-in functions that manipulate fractional values:

    +
    + +
    +
  • +
+
+
+
+
+
+

3. Errors

+
+
+

Errors may be raised during the json-formula evaluation process. +The following errors are defined:

+
+
+
    +
  • +

    EvaluationError is raised when an unexpected runtime condition occurs. For example, divide by zero.

    +
  • +
  • +

    FunctionError is raised when an unknown function is encountered or when a function receives invalid arguments.

    +
  • +
  • +

    SyntaxError is raised when the supplied expression does not conform to the json-formula grammar.

    +
  • +
  • +

    TypeError is raised when coercion is required for the current evaluation context, but the coercion is not possible.

    +
  • +
+
+
+
+
+

4. Grammar

+
+
+

The grammar is specified using Antlr. For a machine-readable version of the grammar, see the grammar.g4 file in the source repository.

+
+
+
+
grammar JsonFormula;
+
+formula : expression EOF ;
+
+expression
+  : '(' expression ')' 
+  | expression bracketExpression 
+  | bracketExpression 
+  | objectExpression 
+  | expression '.' chainedExpression 
+  | '!' expression 
+  | '-' expression 
+  | expression ('*' | '/') expression	
+  | expression ('+' | '-' | '~') expression	
+  | expression '&' expression	
+  | expression COMPARATOR expression 
+  | expression '&&' expression 
+  | expression '||' expression 
+  | expression '|' expression 
+  | identifier 
+  | wildcard 
+  | arrayExpression 
+  | JSON_LITERAL 
+  | functionExpression 
+  | STRING 
+  | (REAL_OR_EXPONENT_NUMBER | INT) 
+  | currentNode 
+  ;
+
+chainedExpression
+  : identifier
+  | arrayExpression
+  | objectExpression
+  | functionExpression
+  | wildcard
+  ;
+
+wildcard : '*' ;
+
+arrayExpression : '[' expression (',' expression)* ']' ;
+
+objectExpression
+  : '{' keyvalExpr (',' keyvalExpr)* '}'  
+  ;
+
+keyvalExpr : identifier ':' expression ;
+
+bracketExpression
+  : '[' '*' ']' 
+  | '[' slice ']' 
+  | '[' ']' 
+  | '[?' expression ']' 
+  | '[' signedInt ']' 
+  ;
+
+slice : start=signedInt? ':' stop=signedInt? (':' step=signedInt?)? ;
+
+COMPARATOR
+  : '<'
+  | '<='
+  | '=='
+  | '='
+  | '>='
+  | '>'
+  | '!='
+  | '<>'
+  ;
+
+functionExpression
+  : NAME '(' functionArg (',' functionArg)* ')'
+  | NAME '(' ')'
+  ;
+
+functionArg
+  : expression
+  | expressionType
+  ;
+
+currentNode : '@' ;
+
+expressionType : '&' expression ;
+
+identifier
+  : NAME
+  | QUOTED_NAME
+  ;
+
+signedInt
+  : '-'? INT+
+  ;
+
+NAME : [a-zA-Z_$] [a-zA-Z0-9_$]* ;
+
+QUOTED_NAME : '\'' (ESC | ~ ['\\])* '\'';
+
+JSON_LITERAL
+  : '`' (ESC | ~ [\\`]+)* '`'
+  ;
+
+STRING : '"' (ESC | ~["\\])* '"' ;
+
+fragment ESC : '\\' (UNICODE | [bfnrt\\`'"/]);
+
+fragment UNICODE
+  : 'u' HEX HEX HEX HEX
+  ;
+
+fragment HEX
+  : [0-9a-fA-F]
+  ;
+
+REAL_OR_EXPONENT_NUMBER
+  : INT? '.' [0-9] + EXP?
+  | INT EXP
+  ;
+
+INT
+  : [0-9]+
+  ;
+
+fragment EXP
+  : [Ee] [+\-]? INT
+  ;
+
+WS
+  : [ \t\n\r] + -> skip
+  ;
+
+
+
+

4.1. Operator Precedence

+
+

The antlr grammar defines operator precedence by the order of expressions in the grammar. These are the operators listed from strongest to weakest binding:

+
+
+
    +
  • +

    Parenthesis ()

    +
  • +
  • +

    Bracket Expression […​]

    +
  • +
  • +

    Braces {}

    +
  • +
  • +

    Dot . (chained expressions)

    +
  • +
  • +

    Flatten: []

    +
  • +
  • +

    Unary not !, unary minus: -

    +
  • +
  • +

    multiply: *, divide: /

    +
  • +
  • +

    add: +, subtract: -, union: ~

    +
  • +
  • +

    concatenate: &

    +
  • +
  • +

    Comparison operators: =, ==, >, <, >=, <=, !=, <>

    +
  • +
  • +

    and: &&

    +
  • +
  • +

    or: ||

    +
  • +
  • +

    pipe: |

    +
  • +
+
+
+
+
+
+

5. Literals

+
+
+

5.1. JSON Literals

+
+
+
  JSON_LITERAL: '`' (ESC | ~ [\\`]+)* '`';
+
+
+
+

A JSON literal expression allows arbitrary JSON objects to be +specified anywhere an expression is permitted. Implementations should +use a JSON parser to parse these literals. Note that the backtick character +( ` ) character must be escaped in a JSON literal which means +implementations need to handle this case before passing the resulting string to +a JSON parser.

+
+

Examples

+
+
+
  eval(`"foo"`, {}) -> "foo"
+  eval(`"foo\`bar"`, {}) -> "foo`bar"
+  eval(`[1, 2]`, {}) -> [1, 2]
+  eval(`true`, {}) -> true
+  eval(`{"a": "b"}`.a, {}) -> "b"
+  eval({first: a, type: `"mytype"`}, {"a": "b", "c": "d"})
+       -> {"first": "b", "type": "mytype"}
+
+
+
+
+

5.2. String Literals

+
+
+
STRING : '"' (ESC | ~["\\])* '"' ;
+
+fragment ESC : '\\' (UNICODE | [bfnrt\\`'"/]);
+
+fragment UNICODE
+  : 'u' HEX HEX HEX HEX
+  ;
+
+fragment HEX
+  : [0-9a-fA-F]
+  ;
+
+
+
+

A STRING literal is a value enclosed in double quotes and supports the same character escape sequences as strings in JSON, as encoded by the ESC fragment. +e.g., a character 'A' could be specified as the unicode sequence: \u0041.

+
+
+

A string literal can also be expressed as a JSON literal. For example, the following expressions both +evaluate to the same value: "foo"

+
+
+
+
    eval(`"foo"`, {}) -> "foo"
+    eval("foo", {}) -> "foo"
+
+
+
+
+

5.3. Number literals

+
+
+
numberLiteral = REAL_OR_EXPONENT_NUMBER | INT
+
+REAL_OR_EXPONENT_NUMBER
+  : INT? '.' [0-9] + EXP?
+  | INT EXP
+  ;
+
+INT
+  : [0-9]+
+  ;
+
+fragment EXP
+  : [Ee] [+\-]? INT
+  ;
+
+
+
+

Number literals follow the same syntax rules as numeric values in JSON with three exceptions:

+
+
+
    +
  1. +

    Number literals may omit a leading zero before the decimal point. For example, .123 is not valid JSON, but is allowed as a number literal.

    +
  2. +
  3. +

    Number literals may include leading zeros ahead of the integral part of the number. For example, 0123 is not valid JSON, but is allowed as a number literal.

    +
  4. +
  5. +

    The grammar construction for a number literal does not include a minus sign. Literal expressions are made negative by prefixing them with a unary minus.

    +
  6. +
+
+
+

Note that number literals (and JSON numbers) allow scientific notation.

+
+

Examples

+
+
+
  eval(44, {}) -> 44
+  eval([12, 13], {}) -> [12, 13]
+  eval({a: 12, b: 13}, {}) -> {"a": 12, "b": 13}
+  eval(foo | [1], {"foo": [3,4,5]}) -> 4
+  eval(foo | @[-1], {"foo": [3,4,5]}) -> 5
+  eval(foo | [1, 2], {"foo": [3,4,5]}) -> [1, 2]
+  eval(6 / 3, {}) -> 2
+  eval(1e2, {}) -> 100
+
+
+
+
+
+
+

6. Identifiers

+
+
+
+
identifier
+  : NAME
+  | QUOTED_NAME
+  ;
+
+NAME : [a-zA-Z_$] [a-zA-Z0-9_$]* ;
+
+QUOTED_NAME : '\'' (ESC | ~ ['\\])* '\'';
+
+
+
+

An identifier is the most basic expression and can be used to extract a +single element from a JSON document. The return value for an identifier is the value associated with the identifier. If the identifier does not exist in the JSON document, then a null value is returned.

+
+
+

Using the NAME token grammar rule, identifiers can be one or more characters, +and must start with a character in the range: A-Za-z_$.

+
+
+

When an identifier has a +character sequence that does not match a NAME token, an identifier shall follow the QUOTED_NAME token rule where an identifier is specified with a single quote ('), followed by +any number of characters, followed by another single quote. Any valid string can be placed between single quotes, including JSON escape sequences.

+
+

Examples

+
+
+
   eval(foo, {"foo": "value"}) -> "value"
+   eval(bar, {"foo": "value"}) -> null
+   eval(foo, {"foo": [0, 1, 2]}) -> [0, 1, 2]
+   eval('with space', {"with space": "value"}) -> "value"
+   eval('special chars: !@#"', {"special chars: !@#": "value"}) -> "value"
+   eval('quote\'char', {"quote'char": "value"}) -> "value"
+   eval('\u2713', {"\u2713": "value"}) -> "value"
+
+
+
+
+
+

7. Operators

+
+
+

7.1. Comparison Operators

+
+

The following comparison operators are supported:

+
+
+
    +
  • +

    = , ==: test for equality

    +
  • +
  • +

    !=, <>: test for inequality

    +
  • +
  • +

    <: less than

    +
  • +
  • +

    <=: less than or equal to

    +
  • +
  • +

    >: greater than

    +
  • +
  • +

    >=: greater than or equal to

    +
  • +
+
+
+

7.1.1. Equality Operators

+
+

Two representations of the equality and inequality operators are supported: = and == are equivalent in functionality. Both variations are supported in order to provide familiarity to users with experience with similar grammars. Similarly, != and <> function identically. Note that there is no ambiguity with the = operator, since json-formula does not have an assignment operator.

+
+
+
    +
  • +

    A string is equal to another string if they they have the exact same sequence +of code points

    +
  • +
  • +

    number values are compared for an exact match. When comparing fractional values, authors should take into account floating point precision considerations.

    +
  • +
  • +

    The literal values true/false/null are equal only to their +own literal values

    +
  • +
  • +

    Two JSON objects are equal if they have the same set of +keys and values. Two JSON objects x and y, are consider equal if they have the same number of key/value pairs and if, for each key value +pair (i, j) in x, there exists an equivalent pair (i, j) in y

    +
  • +
  • +

    Two JSON arrays are equal if they have equal elements in the same order. Two arrays x and y are considered equal if they have the same length and, for each i from 0 until length(x), x[i] == y[i]

    +
  • +
  • +

    The comparison of array and objects is a deep comparison. That is, where nested arrays or objects are found, the nested elements will included in the comparison.

    +
  • +
+
+
+
+

7.1.2. Ordering Operators

+
+

Ordering comparisons follow these rules:

+
+
+
    +
  • +

    If both operands are numbers, a numeric comparison is performed

    +
  • +
  • +

    If both operands are strings, they are compared as strings, based on the values of the Unicode code points they contain

    +
  • +
  • +

    If operands are mixed types, type coercion to number is applied before performing the comparison

    +
  • +
+
+
+
+
+

7.2. Numeric Operators

+
+

The following operators work with numeric operands:

+
+
+
    +
  • +

    addition: +

    +
  • +
  • +

    subtraction: -

    +
  • +
  • +

    multiplication *

    +
  • +
  • +

    division: /

    +
  • +
+
+
+
+
  eval(left + right, {"left": 8, "right": 12 }) -> 20
+  eval(right - left - 10, {"left": 8, "right": 12 }) -> -6
+  eval(4 + 2 * 4, {}) -> 12
+  eval(10 / 2 * 3, {}) -> 15
+
+
+
+
+

7.3. Concatenation Operator

+
+

The concatenation operator (&) takes two string operands and combines them to form a single string.

+
+
+
+
  eval(left & value & right,
+    {"left": "[", "right": "]", "value": "abc" }) -> "[abc]"
+  eval(map(values, &"$" & @), {"values": [123.45, 44.32, 99.00] }) ->
+      ["$123.45", "$44.32", "$99"]
+
+
+
+
+

7.4. Array Operands

+
+

The numeric and concatenation operators (+, -, *, /, &) have special behavior when applied to arrays.

+
+
+
    +
  • +

    When both operands are arrays, a new array is returned where the elements are populated by applying the operator on each element of the left operand array with the corresponding element from the right operand array

    +
  • +
  • +

    If both operands are arrays and they do not have the same size, the shorter array is padded with null values

    +
  • +
  • +

    If one operand is an array and one is a scalar value, the scalar operand will be converted to an array by repeating the value to the same size array as the other operand

    +
  • +
+
+
+
+
  eval([1,2,3] + [2,3,4], {}) -> [3,5,7]
+  eval([1,2,3,4] * [1,2,3], {}) -> [1,4,9,0]
+  eval([1,2,3,4] & "%", {}) -> ["1%", "2%", "3%", "4%"]
+
+
+
+

7.4.1. Union Operator

+
+

The union operator (~) returns an array formed by concatenating the contents of two arrays.

+
+
+
+
  eval(a ~ b, {"a": [0,1,2], "b": [3,4,5]}) -> [0,1,2,3,4,5]
+  eval(a ~ b, {"a": [[0,1,2]], "b": [[3,4,5]]}) -> [[0,1,2],[3,4,5]]
+  eval(a[] ~ b[], {"a": [[0,1,2]], "b": [[3,4,5]]}) -> [0,1,2,3,4,5]
+  eval(a ~ 10, {"a": [0,1,2]}) -> [0,1,2,10]
+  eval(a ~ `null`, {"a": [0,1,2]}) -> [0,1,2,null]
+
+
+
+
+
+

7.5. Boolean Operators

+
+

7.5.1. Or Operator

+
+

The OR operator (||) will evaluate to either the left operand or the right +operand. If the left operand can be coerced to a true value, it is used +as the return value. If the left operand cannot be coerced to a true value, then the right operand is used as the return value. +If the left operand is a truth-like value, then the right operand is not evaluated. For example, the expression: if() will result in a FunctionError (missing arguments), but the expression true() || if() will not result in a FunctionError because the right operand is not evaluated.

+
+
+

The following conditions cannot be coerced to true:

+
+
+
    +
  • +

    Empty array: []

    +
  • +
  • +

    Empty object: {}

    +
  • +
  • +

    Empty string: ""

    +
  • +
  • +

    False boolean: false

    +
  • +
  • +

    Null value: null

    +
  • +
  • +

    zero value: 0

    +
  • +
+
+
Examples
+
+
+
  eval(foo || bar, {"foo": "foo-value"}) -> "foo-value"
+  eval(foo || bar, {"bar": "bar-value"}) -> "bar-value"
+  eval(foo || bar, {"foo": "foo-value", "bar": "bar-value"}) -> "foo-value"
+  eval(foo || bar, {"baz": "baz-value"}) -> null
+  eval(foo || bar || baz, {"baz": "baz-value"}) -> "baz-value"
+  eval(override || myarray[-1], {"myarray": ["one", "two"]}) -> "two"
+  eval(override || myarray[-1], {"myarray": ["one", "two"], "override": "yes"})
+       -> "yes"
+
+
+
+
+

7.5.2. And Operator

+
+

The AND operator (&&) will evaluate to either the left operand or the right +operand. If the left operand is a truth-like value, +then the right operand is returned. Otherwise the left operand is returned. This reduces to the +expected truth table:

+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LHSRHSResult

True

True

True

True

False

False

False

True

False

False

False

False

+
+

This is the standard truth table for a +logical conjunction.

+
+
+

If the left operand is not a truth-like value, then the right operand is not evaluated. For example, the expression: true() && if() will result in a FunctionError (missing arguments), but the expression false() && if() will not result in an error because the right operand is not evaluated.

+
+
Examples
+
+
+
  eval(True && False, {"True": true, "False": false}) -> false
+  eval(Number && EmptyList, {"Number": 5, "EmptyList": []}) -> []
+  eval(foo[?a == `1` && b == `2`],
+         {"foo": [{"a": 1, "b": 2}, {"a": 1, "b": 3}]}) -> [{"a": 1, "b": 2}]
+
+
+
+
+
+

7.6. Unary Operators

+
+

7.6.1. Not Operator

+
+

A unary NOT operator (!) is a boolean operator that negates the result of an expression. If the expression +results in a truth-like value, NOT operator will change this value to +false. If the expression results in a false-like value, a +NOT operator will change the value to true.

+
+
Examples
+
+
+
  eval(!True, {"True": true}) -> false
+  eval(!False, {"False": false}) -> true
+  eval(!Number, {"Number": 5}) -> false
+  eval(!EmptyList, {"EmptyList": []}) -> true
+
+
+
+
+

7.6.2. Minus Operator

+
+

A unary Minus operator (-) is a numeric operator that negates the value of an operand.

+
+
Examples
+
+
+
  eval(-11, {}) -> -11
+  eval(-n, {"n": 5, "nn": -10}) -> -5
+  eval(-nn, {"n": 5, "nn": -10}) -> 10
+  eval(--n, {"n": 5, "nn": -10}) -> 5
+
+
+
+
+
+
+
+

8. Expressions

+
+
+

8.1. Chained Expressions

+
+
+
expression: expression '.' chainedExpression
+
+chainedExpression
+  : identifier
+  | arrayExpression
+  | objectExpression
+  | functionExpression
+  | wildcard
+  ;
+
+wildcard : '*' ;
+
+
+
+

A chained expression is a combination of two expressions separated by the dot (.) char. +A chained expression is evaluated as follows:

+
+
+
    +
  • +

    Evaluate the expression on the left against the source JSON document

    +
  • +
  • +

    Evaluate the expression on the right against the result of the left expression +evaluation

    +
  • +
+
+
+

In pseudo-code

+
+
+
+
  left-evaluation = eval(left-expression, original-json-document)
+  result = eval(right-expression, left-evaluation)
+
+
+
+

A chained expression is itself an expression, so there can be multiple levels of +chained expressions: grandparent.parent.child.

+
+

Examples

+
+

Given a JSON document: {"foo": {"bar": "baz"}}, and a json-formula expression: +foo.bar, the evaluation process would be

+
+
+
+
  left-evaluation = eval(foo, {"foo": {"bar": "baz"}}) -> {"bar": "baz"}
+  result = eval(bar, {"bar": "baz"}) -> "baz"
+
+
+
+

The final result in this example is "baz".

+
+
+

Additional examples

+
+
+
+
   eval(foo.bar, {"foo": {"bar": "value"}}) -> "value"
+   eval(foo.'bar', {"foo": {"bar": "value"}}) -> "value"
+   eval(foo.bar, {"foo": {"baz": "value"}}) -> null
+   eval(foo.bar.baz, {"foo": {"bar": {"baz": "value"}}}) -> "value"
+
+
+
+
+

8.2. Bracket Expressions

+
+
+
expression: expression bracketExpression
+
+bracketExpression
+  : '[' '*' ']'
+  | '[?' expression ']'
+  | '[' signedInt ']'
+  | '[' slice ']'
+  | '[' ']'
+  ;
+
+signedInt
+  : '-'? INT+
+  ;
+
+
+
+

From the bracketExpression construction, the bracketed contents provide access to the elements in an array.

+
+
+
    +
  • +

    The wildcard: ('[' '*' ']') variation is discussed in the Wildcard Expressions section

    +
  • +
  • +

    The filtering: ('[?' expression ']') variation is discussed in the Filter Expressions section

    +
  • +
+
+
+

8.2.1. Index Expressions

+
+

When brackets enclose a signed integer ('[' signedInt ']'), the integer value is used to index into an array. +Indexing is 0 based where an index of 0 refers to the first element of the array. A negative index indicates that indexing is relative to the end of the array, specifically:

+
+
+
+
  negative-index == (length of array) + negative-index
+
+
+
+

Given an array of length N, an index of -1 would be equal to a positive +index of N - 1, which is the last element of the array. +An index value is outside the bounds of the array when the value is greater than or equal to the length of the array or less than the negative length of the array. +If an index is outside the bounds of the array then a value of null is returned.

+
+
Examples
+
+
+
  eval(a[1], {a: [5,6,7,8,9]}) -> 6
+  eval(a[-2], {a: [5,6,7,8,9]}) -> 8
+  eval([0], ["first", "second", "third"]) -> "first"
+  eval([-1], ["first", "second", "third"]) -> "third"
+  eval([100], ["first", "second", "third"]) -> null
+  eval(foo[0], {"foo": ["first", "second", "third"]}) -> "first"
+  eval(foo[100], {"foo": ["first", "second", "third"]}) -> null
+  eval(foo[0][0], {"foo": [[0, 1], [1, 2]]}) -> 0
+
+
+
+
+

8.2.2. Slices

+
+
+
  slice : start=signedInt? ':' stop=signedInt? (':' step=signedInt?)? ;
+
+
+
+

A slice expression allows you to select a contiguous subset of an array. A +slice has a start, stop, and step value. The general form of a +slice is [start:stop:step]. Each component of the slice is optional and can +be omitted, but there must be at least one colon (:) character.

+
+
+
+
+

Slices in json-formula have the same semantics as python slices. If you’re +familiar with python slices, you’re familiar with json-formula slices.

+
+
+
+
+

Given a start, stop, and step value, the sub elements in an array +are extracted as follows:

+
+
+
    +
  • +

    The first element in the extracted array is the index denoted by start.

    +
  • +
  • +

    The last element in the extracted array is the index denoted by stop - 1.

    +
  • +
  • +

    The step value determines the amount by which the index increases or decreases. The default step value is 1. For example, a step value of 2 will return every second value from the array. If step is negative, slicing is performed in reverse — from the last (stop) element to the start.

    +
  • +
+
+
+

Slice expressions adhere to the following rules:

+
+
+
    +
  • +

    If a negative start position is given, it is calculated as the total length +of the array plus the given start position.

    +
  • +
  • +

    If no start position is given, it is assumed to be 0 if the given step is +greater than 0 or the end of the array if the given step is less than 0.

    +
  • +
  • +

    If a negative stop position is given, it is calculated as the total length +of the array plus the given stop position.

    +
  • +
  • +

    If no stop position is given and the given step is greater than 0 then the stop is assumed to be the length of the array.

    +
  • +
  • +

    If no stop position is given and the given step is less than 0, then the stop is assumed to be negative (length+1).

    +
  • +
  • +

    If the given step is omitted, it is assumed to be 1.

    +
  • +
  • +

    If the given step is 0, an EvaluationError error must be raised.

    +
  • +
  • +

    If the element being sliced is not an array, the result is null.

    +
  • +
  • +

    If the element being sliced is an array and yields no results, the result +must be an empty array.

    +
  • +
+
+

Examples

+
+
+
  eval([0:4:1], [0, 1, 2, 3]) -> [0, 1, 2, 3]
+  eval([0:4], [0, 1, 2, 3]) -> [0, 1, 2, 3]
+  eval([0:3], [0, 1, 2, 3]) -> [0, 1, 2]
+  eval([:2], [0, 1, 2, 3]) -> [0, 1]
+  eval([::2], [0, 1, 2, 3]) -> [0, 2]
+  eval([::-1], [0, 1, 2, 3]) -> [3, 2, 1, 0]
+  eval([-2:], [0, 1, 2, 3]) -> [2, 3]
+
+
+
+
+

8.2.3. Flatten Operator

+
+

When the character sequence [] is provided as a bracket specifier, then +a flattening operation occurs on the current result. The flattening operator +will merge one level of sub-arrays in the current result into a single array. The flattening +operator follows these processing steps:

+
+
+
    +
  • +

    Create an empty result array

    +
  • +
  • +

    Iterate over the elements of the current result

    +
  • +
  • +

    If the current element is not an array, add to the end of the result array

    +
  • +
  • +

    If the current element is an array, add each element of the current element +to the end of the result array

    +
  • +
  • +

    The result array is returned as a projection

    +
  • +
+
+
+

Once the flattening operation has been performed, subsequent operations +are projected onto the flattened array.

+
+
+

A bracketed wildcard ([*]) and flatten ([]) behave similarly in that they produce a projection from an array. The only difference is that a bracketed wildcard preserves the original array structure while flatten collapses one level of array structure.

+
+

Examples

+
+
+
  eval(foo[], {"foo": [[0, 1], [1, 2], 3]}) -> [0,1,1,2,3]
+  eval(foo[], {"foo": [[0, 1], [1, 2], [3,[4,5]]]}) -> [0,1,1,2,3,[4,5]]
+  eval(foo[][], {"foo": [[0, 1], [1, 2], [3,[4,5]]]}) -> [0,1,1,2,3,4,5]
+
+
+
+
+
+

8.3. Projections

+
+

Projections allow you to apply an expression to a collection of elements. Projections are created when any form of a Bracket Expression transforms a source array or when a wildcard is applied to an object:

+
+
+

Given the source JSON:

+
+
+
+
{
+  "items": [
+    {
+      "desc": "pens",
+      "price": 3.23
+    },
+    {
+      "desc": "pencils",
+      "price": 1.34
+    },
+    {
+      "desc": "staplers",
+      "price": 10.79
+    }
+  ]
+}
+
+
+
+

These expressions will create a projection:

+
+
+
    +
  • +

    items[*]

    +
  • +
  • +

    items[]

    +
  • +
  • +

    items[0:2]

    +
  • +
  • +

    items[?expr]

    +
  • +
  • +

    items[0].*

    +
  • +
+
+
+

When a chained expression or bracket expression is applied to a projection, their behavior is changed so that the expression is applied to each element of the projection, rather than the underlying array itself.

+
+

Examples

+
+
+
  eval(items[*].desc, items) -> ["pens", "pencils", "staplers"]
+  eval(items[*].desc.upper(@), items) -> ["PENS", "PENCILS", "STAPLERS"]
+  eval(items[].*, items) -> [
+                                ["pens", 3.23],
+                                ["pencils", 1.34],
+                                ["staplers", 10.79]
+                              ]
+  eval(items[0:2].price * 2, items) -> [6.46, 2.68]
+  eval(items[?price < 3], items) -> [{"desc": "pencils", "price": 1.34}]
+
+
+
+

A pipe expression will stop the current projection and process it as a normal array.

+
+
+

For example, if you wanted to sum the price values, this expression: items[*].price.sum(@) will sum each individual price, returning: [3.23,1.34,10.79]. Whereas using a pipe operator will sum the array: items[*].price | sum(@) → 15.36.

+
+
+
+

8.4. Paren Expressions

+
+
+
  parenExpression = '(' expression ')'
+
+
+
+

A parenExpression allows a user to override the precedence order of +an expression
+e.g. (a || b) && c

+
+

Examples

+
+
+
  eval(foo[?(a == 1 || b == 2) && c == 5],
+         {"foo": [{"a": 1, "b": 2, "c": 3}, {"a": 3, "b": 4}]}) -> []
+
+
+
+
+

8.5. Array Expression

+
+
+
    arrayExpression : '[' expression (',' expression)* ']' ;
+
+
+
+

An array expression is used to extract a subset of elements from the JSON document into an array. +Within the start and closing +brackets are one or more expressions separated by a comma. Each +expression will be evaluated against the JSON document, and each result will be added to the array

+
+
+

An arrayExpression with N expressions will result in an array of length N. Given an array +expression [expr-1,expr-2,…​,expr-n], the evaluated expression will return +[evaluate(expr-1), evaluate(expr-2), …​, evaluate(expr-n)].

+
+
+

Given an array expression: [n, "doubled", n * 2] and the +data {"n": 4}, the expression is evaluated as follows:

+
+
+
    +
  1. +

    An empty array is created: []

    +
  2. +
  3. +

    The expression n is evaluated against the source document and the result (4) is appended to the array

    +
  4. +
  5. +

    The literal expression "doubled" is appended to the array

    +
  6. +
  7. +

    The expression n * 2 is evaluated against the source document and the result (8) is appended to the array

    +
  8. +
+
+
+

The final result will be: [4, "doubled", 8].

+
+

Examples

+
+
+
  eval([foo,bar], {"foo": "a", "bar": "b", "baz": "c"}) -> ["a", "b"]
+  eval([foo,bar[0]], {"foo": "a", "bar": ["b"], "baz": "c"}) -> ["a", "b"]
+  eval([foo,bar.baz], {"foo": "a", "bar": {"baz": "b"}}) -> ["a", "b"]
+  eval([foo,baz], {"foo": "a", "bar": "b"}) -> ["a", null]
+
+
+
+

The grammar contains one ambiguity: a bracket with a single signed digit e.g., [0] can be interpreted as a flatten operation or an arrayExpression with the number zero. To resolve this ambiguity, the grammar sets a precedence order so that [-?[0-9]] is treated as a an index expression. To explicitly express an array with one element, use a JSON literal: `[0]`

+
+
+
+

8.6. Object Expression

+
+
+
    objectExpression = "{" ( keyvalExpr ( "," keyvalExpr )*)? "}"
+    keyvalExpr = identifier ":" expression
+
+
+
+

An object expression is used to extract a subset of elements from the JSON document into an object. +An objectExpression requires key names to be provided, as +specified in the keyvalExpr rule. Given the following rule

+
+
+
+
    keyvalExpr = identifier ":" expression
+
+
+
+

The identifier is used as the key name and the result of evaluating the +expression is the value associated with the identifier key.

+
+
+

Each keyvalExpr within the objectExpression will correspond to a +single key value pair in the created object. If a key is specified more than once, the last value will be used. +Consistent with an arrayExpression, an objectExpression may not be empty. To create an empty object, use a JSON literal: {} .

+
+

Examples

+
+

Given an object expression {foo: one.two, bar: bar} and the +data {"bar": "bar", {"one": {"two": "one-two"}}}, the expression is +evaluated as follows:

+
+
+
    +
  1. +

    An object is created: {}

    +
  2. +
  3. +

    A key foo is created whose value is the result of evaluating one.two +against the provided JSON document: {"foo": evaluate(one.two, <data>)}

    +
  4. +
  5. +

    A key bar is created whose value is the result of evaluating the +expression bar against the provided JSON document. If key bar already exists, it is replaced.

    +
  6. +
+
+
+

The final result will be: {"foo": "one-two", "bar": "bar"}.

+
+
+

Additional examples:

+
+
+
+
  eval({foo: foo, bar: bar}, {"foo": "a", "bar": "b", "baz": "c"})
+                -> {"foo": "a", "bar": "b"}
+  eval({foo: foo, firstbar: bar[0]}, {"foo": "a", "bar": ["b"]})
+                -> {"foo": "a", "firstbar": "b"}
+  eval({foo: foo, 'bar.baz': bar.baz}, {"foo": "a", "bar": {"baz": "b"}})
+                -> {"foo": "a", "bar.baz": "b"}
+  eval({foo: foo, baz: baz}, {"foo": "a", "bar": "b"})
+                -> {"foo": "a", "baz": null}
+  eval({foo: foo, foo: 42}, {"foo": "a", "bar": "b"})
+                -> {"foo": 42}
+
+
+
+
+

8.7. Wildcard Expressions

+
+

There are two forms of wildcard expression:

+
+
+
    +
  1. +

    [*] from the bracketExpression construction:

    +
    +
    +
    bracketExpression
    +  : '[' '*' ']'
    +  | '[' slice ']'
    +  | '[' ']'
    +  | '[?' expression ']'
    +  | '[' expression ']'
    +  ;
    +
    +
    +
  2. +
  3. +

    .* from the chainedExpression construction:

    +
  4. +
+
+
+
+
expression : expression '.' chainedExpression
+
+chainedExpression
+  : identifier
+  | arrayExpression
+  | objectExpression
+  | functionExpression
+  | wildcard
+  ;
+
+wildcard : '*' ;
+
+
+
+

The [*] syntax (referred to as an array wildcard expression) may be applied to arrays, and will return a projection with all +the elements of the source array. If an array +wildcard expression is applied to any other JSON type, a value of null is +returned.

+
+
+

The .* syntax (referred to as an object wildcard expression) may be applied to objects and will return an array +of the values from the object key/value pairs. +If an object wildcard expression is applied to any other JSON type, a value of +null is returned.

+
+
+

Note that JSON objects are explicitly defined as +unordered. Therefore an object wildcard expression can return the values +associated with the object in any order.

+
+

Examples

+
+
+
  eval([*].foo, [{"foo": 1}, {"foo": 2}, {"foo": 3}]) -> [1, 2, 3]
+  eval([*].foo, [{"foo": 1}, {"foo": 2}, {"bar": 3}]) -> [1, 2, null]
+  eval(*.foo, {"a": {"foo": 1}, "b": {"foo": 2}, "c": {"bar": 1}}) ->
+      [1, 2, null]
+
+
+
+
+

8.8. currentNode

+
+
+
currentNode : '@' ;
+
+
+
+

The currentNode token represents the node being +evaluated in the current context. The currentNode token is commonly used for:

+
+
+
    +
  • +

    Functions that require the current node as an argument

    +
  • +
  • +

    Filter Expressions that examine elements of an array

    +
  • +
  • +

    Access to the current context in projections.

    +
  • +
+
+
+

json-formula assumes that all expressions operate on the current node. Because of this, an +expression such as @.name would be equivalent to just name.

+
+
+

8.8.1. currentNode state

+
+

At the start of an expression, the value of the current node is the data +being evaluated by the json-formula expression. As an expression is evaluated, currentNode must change to reflect the node +being evaluated. When in a projection, the current node value must be changed +to the node being evaluated by the projection.

+
+

Examples

+
+
+
Given:
+{
+  "family": [
+    {"name": "frank", "age": 22},
+    {"name": "jane", "age": 23}
+  ]
+}
+
+eval(@.family[0].name, {...}) -> "frank"
+
+eval(family[].[left(@.name), age], {...}) ->
+   [["f", 22], ["j", 23]]
+
+eval(family[?@.age == 23], {...}) -> [{"name": "jane", "age": 23}]
+
+eval(family[?age == 23], {...}) -> [{"name": "jane", "age": 23}]
+
+eval(family[].name.proper(@), {...}) -> ["Frank", "Jane"]
+
+eval(family[].age | avg(@), {...}) -> 22.5
+
+
+
+
+
+

8.9. Filter Expressions

+
+
+
bracketExpression
+  : '[' '*' ']'
+  | '[' slice ']'
+  | '[' ']'
+  | '[?' expression ']'
+  | '[' expression ']'
+  ;
+
+
+
+

A filter expression is defined by a bracketExpression where the bracket contents are prefixed with a question mark character (?). +A filter expression provides a way to select array elements based on a +comparison to another expression. A filter expression is evaluated as follows:

+
+
+
    +
  • +

    For each element in an array evaluate the expression against the +element.

    +
  • +
  • +

    If the expression evaluates to a truth-like value, the item (in its +entirety) is added to the result array.

    +
  • +
  • +

    If the expression does not evaluate to a truth-like value it is excluded from the +result array.

    +
  • +
+
+
+

A filter expression may be applied to arrays. Attempting +to evaluate a filter expression against any other type will return null.

+
+

Examples

+
+
+
eval(
+  foo[?a < b],
+  {
+    "foo": [
+      {"a": "char", "b": "bar"},
+      {"a": 2, "b": 1},
+      {"a": 1, "b": 2},
+      {"a": false, "b": "1"},
+      {"a": 10, "b": "12"}
+    ]
+  })
+  ->
+  [ {"a": 1, "b": 2},
+    {"a": false, "b": "1"},
+    {"a": 10, "b": "12"} ]
+
+
+
+

The five elements in the foo array are evaluated against a < b:

+
+
+
    +
  • +

    The first element resolves to the comparison "char" < "bar", and because these types are string, the comparison of code points returns false, and the first element is excluded from the result array.

    +
  • +
  • +

    The second element resolves to 2 < 1, +which is false, so the second element is excluded from the result array.

    +
  • +
  • +

    The third expression resolves to 1 < 2 which evaluates to true, so the third element is included in the result array.

    +
  • +
  • +

    The fourth expression resolves to false < "1". Since the left hand operand is boolean, both operands are coerced to numbers and evaluated as: 0 < 1 and so the fourth element included in the result array.

    +
  • +
  • +

    The final expression resolves to 10 < "12". Since we have mixed operands, the operands are coerced to numbers and evaluated as: 10 < 12 and the last element is included in the result array.

    +
  • +
+
+

Examples

+
+
+
  eval(foo[?bar==10], {"foo": [{"bar": 1}, {"bar": 10}]}) -> [{"bar": 10}]
+  eval([?bar==10], [{"bar": 1}, {"bar": 10}]}) -> [{"bar": 10}]
+  eval(foo[?a==b], {"foo": [{"a": 1, "b": 2}, {"a": 2, "b": 2}]})
+       -> [{"a": 2, "b": 2}]
+
+
+
+
+

8.10. Pipe Expressions

+
+
+
    pipeExpression = expression '|' expression
+
+
+
+

A pipe expression combines two expressions, separated by the pipe (|) character. +It is similar to a chained expression with two distinctions:

+
+
+
    +
  1. +

    Any expression can be used on the right hand side. A chained expression +restricts the type of expression that can be used on the right hand side.

    +
  2. +
  3. +

    A pipe expression stops projections on the left hand side from +propagating to the right hand side. If the left expression creates a +projection, the right hand side will receive the array underlying the projection.

    +
  4. +
+
+
+

For example, given the following data

+
+
+
+
    {"foo": [{"bar": ["first1", "second1"]}, {"bar": ["first2", "second2"]}]}
+
+
+
+

The expression foo[*].bar gives the result of

+
+
+
+
    [
+        [
+            "first1",
+            "second1"
+        ],
+        [
+            "first2",
+            "second2"
+        ]
+    ]
+
+
+
+

The first part of the expression, foo[*], creates a projection. At this +point, the remaining expression, bar is projected onto each element of the +array created from foo[*]. If you project the [0] expression, you will +get the first element from each sub array. The expression foo[*].bar[0] +will return

+
+
+
+
    ["first1", "first2"]
+
+
+
+

If you instead wanted only the first sub array, ["first1", "second1"], you +can use a pipe expression.

+
+
+
+
    foo[*].bar[0] -> ["first1", "first2"]
+    foo[*].bar | [0] -> ["first1", "second1"]
+
+
+

Examples

+
+
+
   eval(foo | bar, {"foo": {"bar": "baz"}}) -> "baz"
+   eval(foo[*].bar | [0], {
+       "foo": [{"bar": ["first1", "second1"]},
+               {"bar": ["first2", "second2"]}]}) -> ["first1", "second1"]
+   eval(foo | [0], {"foo": [0, 1, 2]}) -> 0
+
+
+
+
+
+
+

9. Functions

+
+
+
+
functionExpression
+  : NAME '(' functionArg (',' functionArg)* ')'
+  | NAME '(' ')'
+  ;
+
+functionArg
+  : expression
+  | expressionType
+  ;
+
+expressionType : '&' expression ;
+
+
+
+

json-formula has a robust set of built-in functions. Each function has a signature +that defines the expected types of the input and the type of the returned +output.

+
+
+
+
    return_type function_name(type $argname)
+    return_type function_name2(type1|type2 $argname)
+
+
+
+

9.1. Function parameters

+
+

Functions support the set of standard json-formula data types. If the parameters cannot be coerced to match the types specified in the signature, a TypeError error occurs.

+
+
+

As a shorthand, the type any is used to indicate that the function argument can be +any of (array|object|number|string|boolean|null).

+
+
+

The expression type, (denoted by &expression), is used to specify an +expression that is not immediately evaluated. Instead, a reference to that +expression is provided to the function. The function can then apply the expression reference as needed. It is semantically similar +to an anonymous function. See the sortBy() function for an example of the expression type.

+
+
+

Function parameters can either have a specific arity or be variadic with a minimum +number of arguments. If a functionExpression is encountered where the +arity does not match, or the minimum number of arguments for a variadic function +is not provided, or too many arguments are provided, then a +FunctionError error is raised.

+
+
+

The result of the functionExpression is the result returned by the +function call. If a functionExpression is evaluated for a function that +does not exist, a FunctionError error is raised.

+
+
+

9.1.1. Array Parameters

+
+

Many functions that process scalar values also allow for the processing of arrays of values. For example, the round() function may be called to process a single value: round(1.2345, 2) or to process an array of values: round([1.2345, 2.3456], 2). The first call will return a single value, the second call will return an array of values. +When processing arrays of values, and where there is more than one parameter, each parameter is converted to an array so that the function processes each value in the set of arrays. From our example above, the call to round([1.2345, 2.3456], 2) would be processed as if it were round([1.2345, 2.3456], [2, 2]), and the result would be the same as: [round(1.2345, 2), round(2.3456, 2)].

+
+
+

Functions that accept array parameters will also accept nested arrays. Aggregating functions (min(), max(), avg(), sum(), etc.) will flatten nested arrays. e.g. avg([2.1, 3.1, [4.1, 5.1]]) will be processed as avg([2.1, 3.1, 4.1, 5.1]) and return 3.6.

+
+
+

Non-aggregating functions will return the same array hierarchy. e.g.

+
+
+

upper(["a", ["b"]]) ⇒ ["A", ["B"]] +round([2.12, 3.12, [4.12, 5.12]], 1) will be processed as round([2.12, 3.12, [4.12, 5.12]], [1, 1, [1, 1]]) and return [2.1, 3.1, [4.1, 5.1]]

+
+
+

These array balancing rules apply when any parameter is an array:

+
+
+
    +
  • +

    All parameters will be treated as arrays

    +
  • +
  • +

    Any scalar parameters will be converted to an array by repeating the scalar value to the length of the longest array

    +
  • +
  • +

    All array parameters will be padded to the length of the longest array by adding null values

    +
  • +
  • +

    The function will return an array which is the result of iterating over the elements of the arrays and applying the function logic on the values at the same index.

    +
  • +
+
+
+

With nested arrays:

+
+
+
    +
  • +

    Nested arrays will be flattened for aggregating functions

    +
  • +
  • +

    Non-aggregating functions will preserve the array hierarchy and will apply the balancing rules to each element of the nested arrays

    +
  • +
+
+
+
+
+

9.2. Function evaluation

+
+

Functions are evaluated in applicative order: +- Each argument must be an expression +- Each argument expression must be evaluated before evaluating the function +- Each argument expression result must be coerced to the expected type +- If coercion is not possible, a TypeError error is raised +- The function is then called with the evaluated function arguments.

+
+
+

The one exception to this rule is the if(expr, result1, result2) function. In this case either the result1 expression or the result2 expression is evaluated, depending on the outcome of expr.

+
+
+

Consider this example using the abs() function. Given:

+
+
+
+
    {"foo": -1, "bar": "2"}
+
+
+
+

Evaluating abs(foo) works as follows:

+
+
+
    +
  1. +

    Evaluate the input argument against the current data:

    +
    +
    +
         eval(foo, {"foo": -1, "bar": "2"}) -> -1
    +
    +
    +
  2. +
  3. +

    Coerce the type of the resolved argument if needed. In this case -1 is of type number so no coercion is needed.

    +
  4. +
  5. +

    Validate the type of the coerced argument. In this case -1 is of type number so it passes the type check.

    +
  6. +
  7. +

    Call the function with the resolved argument:

    +
    +
    +
         abs(-1) -> 1
    +
    +
    +
  8. +
+
+
+

Below is the same steps for evaluating abs(bar):

+
+
+
    +
  1. +

    Evaluate the input argument against the current data:

    +
    +
    +
         eval(bar, {"foo": -1, "bar": "2"}) -> "2"
    +
    +
    +
  2. +
  3. +

    Attempt to coerce the result to the required number type. In this case, coerce "2" to 2.

    +
  4. +
  5. +

    Validate the type of the coerced argument. In this case 2 is of type number so it passes the type check.

    +
  6. +
  7. +

    Call the function with the resolved and coerced argument:

    +
    +
    +
         abs(2) -> 2
    +
    +
    +
  8. +
+
+
+

Function expressions are allowed as the child element of a chained expression. +The function is then evaluated in the context of the parent expression result. For example: [1,2,3].sum(@) → 6.

+
+
+

When the parent expression is a projection a chained function expression +will be applied to every element in the projection. For example, given the input +data of ["1", "2", "3", "notanumber", true], the following expression can +be used to convert all elements to numbers:

+
+
+
+
    eval([].toNumber(@), ["1", "2", "3", "notanumber", null, true]) -> [1,2,3,null,0,1]
+
+
+
+
+

9.3. Function Reference

+ +
+

9.3.1. abs

+
+

abs(value) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Find the absolute (non-negative) value of the provided +argument value.

+
+
Returns
+
+

number | Array.<number> - If value < 0, returns +-value, otherwise returns value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

value

number | Array.<number>

A numeric value

+
+
+
+
+

Example

+
+
+
+
abs(-1) // returns 1
+
+
+
+
+

9.3.2. acos

+
+

acos(cosine) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the inverse cosine (in radians) of a number.

+
+
Returns
+
+

number | Array.<number> - The inverse cosine angle in +radians between 0 and PI

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

cosine

number | Array.<number>

A number between -1 and 1, +inclusive, representing the angle’s cosine value.

+
+
+
+
+

Example

+
+
+
+
acos(0) => 1.5707963267948966
+
+
+
+
+

9.3.3. and

+
+

and(firstOperand, […additionalOperands]) ⇒ boolean

+
+
+
+
Description
+
+

Finds the logical AND result of all parameters. If the +parameters are not boolean they will be cast to +boolean. Note the related And Operator.

+
+
Returns
+
+

boolean - The logical result of applying AND to all +parameters

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

firstOperand

any

logical expression

[…additionalOperands]

any

any number of additional expressions

+
+
+
+
+

Example

+
+
+
+
and(10 > 8, length("foo") < 5) // returns true
+and(`null`, length("foo") < 5) // returns false
+
+
+
+
+

9.3.4. asin

+
+

asin(sine) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the inverse sine (in radians) of a number.

+
+
Returns
+
+

number | Array.<number> - The inverse sine angle in +radians between -PI/2 and PI/2

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

sine

number | Array.<number>

A number between -1 and 1, +inclusive, representing the angle’s sine value.

+
+
+
+
+

Example

+
+
+
+
Math.asin(0) => 0
+
+
+
+
+

9.3.5. atan2

+
+

atan2(y, x) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the angle in the plane (in radians) between the +positive x-axis and the ray from (0, 0) to the point (x, y)

+
+
Returns
+
+

number | Array.<number> - The angle in radians (between +-PI and PI), between the positive x-axis and the ray from (0, 0) to the +point (x, y).

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

y

number | Array.<number>

The y coordinate of the point

x

number | Array.<number>

The x coordinate of the point

+
+
+
+
+

Example

+
+
+
+
atan2(20,10) => 1.1071487177940904
+
+
+
+
+

9.3.6. avg

+
+

avg(elements) ⇒ number

+
+
+
+
Description
+
+

Finds the average of the elements in an array. Non-numeric +values (text, boolean, null, object) are ignored. If there are nested +arrays, they are flattened. If the array is empty, an evaluation error +is thrown

+
+
Returns
+
+

number - average value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

elements

Array.<any>

array of values

+
+
+
+
+

Example

+
+
+
+
avg([1, 2, 3]) // returns 2
+
+
+
+
+

9.3.7. avgA

+
+

avgA(elements) ⇒ number

+
+
+
+
Description
+
+

Finds the average of the elements in an array, converting +strings and booleans to number. If any conversions to number fail, a +type error is thrown. If there are nested arrays, they are flattened. If +the array is empty, an evaluation error is thrown

+
+
Returns
+
+

number - average value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

elements

Array.<number>

array of numeric values

+
+
+
+
+

Example

+
+
+
+
avgA([1, 2, "3", null()]) // returns 2
+
+
+
+
+

9.3.8. casefold

+
+

casefold(input) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Generates a lower-case string of the input string using +locale-specific mappings. e.g. Strings with German letter ß (eszett) can +be compared to "ss"

+
+
Returns
+
+

string | Array.<string> - A new string converted to +lower case

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

input

string | Array.<string>

string to casefold

+
+
+
+
+

Example

+
+
+
+
casefold("AbC") // returns "abc"
+
+
+
+
+

9.3.9. ceil

+
+

ceil(num) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Finds the next highest integer value of the argument num +by rounding up if necessary. i.e. ceil() rounds toward positive +infinity.

+
+
Returns
+
+

integer | Array.<integer> - The smallest integer +greater than or equal to num

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

numeric value

+
+
+
+
+

Example

+
+
+
+
ceil(10) // returns 10
+ceil(10.4) // return 11
+
+
+
+
+

9.3.10. codePoint

+
+

codePoint(str) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Retrieve the first code point from a string

+
+
Returns
+
+

integer | Array.<integer> - Unicode code point value. +If the input string is empty, returns null.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

str

string | Array.<string>

source string.

+
+
+
+
+

Example

+
+
+
+
codePoint("ABC") // 65
+
+
+
+
+

9.3.11. contains

+
+

contains(subject, search) ⇒ boolean

+
+
+
+
Description
+
+

Determines if the given subject contains search. If +subject is an array, this function returns true if one of the elements +in the array is equal to the search value. If subject is a string, +return true if the string contains the search value.

+
+
Returns
+
+

boolean - true if found

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

array | string

The element to be searched

search

any

element to find. If subject is an array, search for an +exact match for search in the array. If subject is a string, +search must also be a string.

+
+
+
+
+

Example

+
+
+
+
contains([1, 2, 3, 4], 2) // returns true
+contains([1, 2, 3, 4], -1) // returns false
+contains("Abcd", "d") // returns true
+contains("Abcd", "x") // returns false
+
+
+
+
+

9.3.12. cos

+
+

cos(angle) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the cosine (in radians) of a number.

+
+
Returns
+
+

number | Array.<number> - The cosine of the angle, +between -1 and 1, inclusive.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

angle

number | Array.<number>

A number representing an angle in +radians

+
+
+
+
+

Example

+
+
+
+
cos(1.0471975512) => 0.4999999999970535
+
+
+
+
+

9.3.13. datedif

+
+

datedif(start_date, end_date, unit) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Return difference between two date values. The measurement +of the difference is determined by the unit parameter. One of:

+
+
    +
  • +

    y the number of whole years between start_date and end_date

    +
  • +
  • +

    m the number of whole months between start_date and end_date.

    +
  • +
  • +

    d the number of days between start_date and end_date

    +
  • +
  • +

    ym the number of whole months between start_date and end_date +after subtracting whole years.

    +
  • +
  • +

    yd the number of days between start_date and end_date, assuming +start_date and end_date were no more than one year apart

    +
  • +
+
+
+
Returns
+
+

integer | Array.<integer> - The number of +days/months/years difference

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

start_date

number | Array.<number>

The starting +date/time value. Date/time values can be +generated using the datetime, toDate, +today, now and time functions.

end_date

number | Array.<number>

The end +date/time value – must be greater or equal to +start_date. If not, an error will be thrown.

unit

string | Array.<string>

Case-insensitive string +representing the unit of time to measure. An unrecognized unit will +result in an error.

+
+
+
+
+

Example

+
+
+
+
datedif(datetime(2001, 1, 1), datetime(2003, 1, 1), "y") // returns 2
+datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), "D") // returns 805
+// 805 days between June 1, 2001, and August 15, 2003
+datedif(datetime(2001, 6, 1), datetime(2003, 8, 15), "YD") // returns 75
+// 75 days between June 1 and August 15, ignoring the years of the dates (75)
+
+
+
+
+

9.3.14. datetime

+
+

datetime(year, month, day, [hours], [minutes], [seconds], +[milliseconds]) ⇒ number

+
+
+
+
Description
+
+

Generate a date/time value from individual date/time +parts. If any of the units are greater than their normal range, the +overflow will be added to the next greater unit. e.g. specifying 25 +hours will increment the day value by 1. Similarly, negative values will +decrement the next greater unit. e.g. datetime(year, month, day - 30) +will return a date 30 days earlier.

+
+
Returns
+
+

number - A date/time value to be +used with other date/time functions

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

year

integer

The year to use for date construction. Values from 0 +to 99 map to the years 1900 to 1999. All other values are the actual +year

month

integer

The month: beginning with 1 for January to 12 for +December.

day

integer

The day of the month.

[hours]

integer

0

Integer value between 0 and 23 representing the +hour of the day.

[minutes]

integer

0

Integer value representing the minute segment of +a time.

[seconds]

integer

0

Integer value representing the second segment of +a time.

[milliseconds]

integer

0

Integer value representing the millisecond +segment of a time.

+
+
+
+
+

Example

+
+
+
+
datetime(2010, 10, 10) // returns representation of October 10, 2010
+datetime(2010, 2, 28) // returns representation of February 28, 2010
+datetime(2023,13,5) | year(@) & "/" & month(@) // returns 2024/1
+
+
+
+
+

9.3.15. day

+
+

day(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Finds the day of the month for a date value

+
+
Returns
+
+

integer | Array.<integer> - The day of the month +ranging from 1 to 31.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

date/time +value generated using the datetime, +toDate, today, now and +time functions.

+
+
+
+
+

Example

+
+
+
+
day(datetime(2008,5,23)) // returns 23
+
+
+
+
+

9.3.16. debug

+
+

debug(arg, [displayValue]) ⇒ any

+
+
+
+
Description
+
+

Debug a json-formula expression. The debug() function +allows users to inspect a sub-expression within a formula.

+
+
Returns
+
+

any - The value of the arg parameter

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

arg

any

The expression to return from debug() function, and the +default expression to be debugged. May be any type except an expression.

[displayValue]

any | expression

arg

Optionally override the +value to be debugged. displayValue may be an expression to be +evaluated with the context of arg.

+
+
+
+
+

Example

+
+
+
+
avg(([1,2,3] * [2,3,4]).debug(@)).round(@,3) // 6.667
+avg(debug([1,2,3] * [2,3,4],&"average of: " &toString(@))).round(@,3) // 6.667
+
+
+
+
+

9.3.17. deepScan

+
+

deepScan(object, name) ⇒ Array.<any>

+
+
+
+
Description
+
+

Performs a depth-first search of a nested hierarchy to +return an array of key values that match a name. The name can be +either a key into an object or an array index. This is similar to the +Descendant Accessor operator (..) from +E4X.

+
+
Returns
+
+

Array.<any> - The array of matched elements

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

object

object | array | null

The starting object or array +where we start the search

name

string | integer

The name (or index position) of the +elements to find. If name is a string, search for nested objects with +a matching key. If name is an integer, search for nested arrays with a +matching index.

+
+
+
+
+

Example

+
+
+
+
deepScan({a : {b1 : {c : 2}, b2 : {c : 3}}}, "c") // returns [2, 3]
+
+
+
+
+

9.3.18. endsWith

+
+

endsWith(subject, suffix) ⇒ boolean | Array.<boolean>

+
+
+
+
Description
+
+

Determines if the subject string ends with a specific +suffix

+
+
Returns
+
+

boolean | Array.<boolean> - true if the suffix value +is at the end of the subject

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | Array.<string>

source string in which to +search

suffix

string | Array.<string>

search string

+
+
+
+
+

Example

+
+
+
+
endsWith("Abcd", "d") // returns true
+endsWith("Abcd", "A") // returns false
+
+
+
+
+

9.3.19. entries

+
+

entries(obj) ⇒ Array.<any>

+
+
+
+
Description
+
+

Returns an array of [key, value] pairs from an object or +array. The fromEntries() function may be used to convert an array to +an object.

+
+
Returns
+
+

Array.<any> - an array of arrays where each child array has +two elements representing the key and value of a pair

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

obj

object | array

source object or array

+
+
+
+
+

Example

+
+
+
+
entries({a: 1, b: 2}) // returns [["a", 1], ["b", 2]]
+entries([4,5]) // returns [["0", 4],["1", 5]]
+
+
+
+
+

9.3.20. eomonth

+
+

eomonth(startDate, monthAdd) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Finds the date value of the end of a month, given +startDate plus monthAdd months

+
+
Returns
+
+

number | Array.<number> - the date of the last day of +the month

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

startDate

number | Array.<number>

The base date to start from. +Date/time values can be generated using the +datetime, toDate, today, +now and time functions.

monthAdd

integer | Array.<integer>

Number of months to add to +start date

+
+
+
+
+

Example

+
+
+
+
eomonth(datetime(2011, 1, 1), 1) | [month(@), day(@)] // returns [2, 28]
+eomonth(datetime(2011, 1, 1), -3) | [month(@), day(@)] // returns [10, 31]
+
+
+
+
+

9.3.21. exp

+
+

exp(x) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Finds e (the base of natural logarithms) raised to a +power. (i.e. e^x)

+
+
Returns
+
+

number | Array.<number> - e (the base of natural +logarithms) raised to power x

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

x

number | Array.<number>

A numeric expression representing the +power of e.

+
+
+
+
+

Example

+
+
+
+
exp(10) // returns 22026.465794806718
+
+
+
+
+

9.3.22. false

+
+

false() ⇒ boolean

+
+
+
+
Description
+
+

Return constant boolean false value. Expressions may also +use the JSON literal: `false`

+
+
Returns
+
+

boolean - constant boolean value false

+
+
+
+
+
+

9.3.23. find

+
+

find(findText, withinText, [start]) ⇒ integer | null | +Array.<integer>

+
+
+
+
Description
+
+

Finds and returns the index of query in text from a start +position

+
+
Returns
+
+

integer | null | Array.<integer> - The position +of the found string, null if not found.

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

findText

string | Array.<string>

string to search

withinText

string | Array.<string>

text to be searched

[start]

integer | Array.<integer>

0

zero-based position to +start searching. If specified, start must be greater than or equal to +0

+
+
+
+
+

Example

+
+
+
+
find("m", "abm") // returns 2
+find("M", "abMcdM", 3) // returns 5
+find("M", "ab") // returns `null`
+find("M", "abMcdM", 2) // returns 2
+
+
+
+
+

9.3.24. floor

+
+

floor(num) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Calculates the next lowest integer value of the argument +num by rounding down if necessary. i.e. floor() rounds toward negative +infinity.

+
+
Returns
+
+

integer | Array.<integer> - The largest integer smaller +than or equal to num

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

numeric value

+
+
+
+
+

Example

+
+
+
+
floor(10.4) // returns 10
+floor(10) // returns 10
+
+
+
+
+

9.3.25. fromCodePoint

+
+

fromCodePoint(codePoint) ⇒ string

+
+
+
+
Description
+
+

Create a string from a code point.

+
+
Returns
+
+

string - A string from the given code point(s)

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

codePoint

integer | Array.<integer>

An integer or array of +integers between 0 and 0x10FFFF (inclusive) representing Unicode code +point(s).

+
+
+
+
+

Example

+
+
+
+
fromCodePoint(65) // "A"
+fromCodePoint(65) == "\u0041" // true
+
+
+
+
+

9.3.26. fromEntries

+
+

fromEntries(pairs) ⇒ object

+
+
+
+
Description
+
+

Returns an object by transforming a list of key-value +pairs into an object. fromEntries() is the inverse operation of +entries(). If the nested arrays are not of the form: [key, value] +(where key is a string), an error will be thrown.

+
+
Returns
+
+

object - An object constructed from the provided key-value +pairs

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

pairs

Array.<any>

A nested array of key-value pairs to create the +object from The nested arrays must have exactly two values, where the +first value is a string. If a key is specified more than once, the last +occurrence will override any previous value.

+
+
+
+
+

Example

+
+
+
+
fromEntries([["a", 1], ["b", 2]]) // returns {a: 1, b: 2}
+
+
+
+
+

9.3.27. fround

+
+

fround(num) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the nearest 32-bit single precision float +representation of a number

+
+
Returns
+
+

number | Array.<number> - The rounded representation of +num

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

input to be rounded

+
+
+
+
+

Example

+
+
+
+
fround(2147483650.987) => 2147483648
+fround(100.44444444444444444444) => 100.44444274902344
+
+
+
+
+

9.3.28. hasProperty

+
+

hasProperty(subject, name) ⇒ boolean

+
+
+
+
Description
+
+

Determine if an object has a property or if an array index +is in range.

+
+
Returns
+
+

boolean - true if the element exists

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

object | array | null

source object or array. +When querying for hidden properties, subject +may be any data type.

name

string | integer

The name (or index position) of the +element to find. if subject is an array, name must be an integer; if +subject is an object, name must be a string.

+
+
+
+
+

Example

+
+
+
+
hasProperty({a: 1, b: 2}, "a") // returns true
+hasProperty(["apples", "oranges"], 3) // returns false
+hasProperty(`null`, "a") // returns false
+
+
+
+
+

9.3.29. hour

+
+

hour(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Extract the hour from a date/time +value

+
+
Returns
+
+

integer | Array.<integer> - value between 0 and 23

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

The datetime/time for which the +hour is to be returned. Date/time values can be generated using the +datetime, toDate, today, +now and time functions.

+
+
+
+
+

Example

+
+
+
+
hour(datetime(2008,5,23,12, 0, 0)) // returns 12
+hour(time(12, 0, 0)) // returns 12
+
+
+
+
+

9.3.30. if

+
+

if(condition, result1, result2) ⇒ any

+
+
+
+
Description
+
+

Return one of two values result1 or result2, depending +on the condition

+
+
Returns
+
+

any - either result1 or result2

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

condition

any

boolean result of a logical expression

result1

any

if condition is true

result2

any

if condition is false

+
+
+
+
+

Example

+
+
+
+
if(true(), 1, 2) // returns 1
+if(false(), 1, 2) // returns 2
+
+
+
+
+

9.3.31. join

+
+

join(array, glue) ⇒ string

+
+
+
+
Description
+
+

Combines all the elements from the provided array, joined +together using the glue argument as a separator between each array +element.

+
+
Returns
+
+

string - String representation of the array

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

array

Array.<any>

array of values that will be converted to strings +using toString()

glue

string

+
+
+
+
+

Example

+
+
+
+
join(["a", "b", "c"], ",") // returns "a,b,c"
+join(["apples", "bananas"], " and ") // returns "apples and bananas"
+join([1, 2, 3, null()], "|") // returns "1|2|3|null"
+
+
+
+
+

9.3.32. keys

+
+

keys(obj) ⇒ array

+
+
+
+
Description
+
+

Generates an array of the keys of the input object. If the +object is null, the value return an empty array

+
+
Returns
+
+

array - the array of all the key names

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

obj

object

the object to examine

+
+
+
+
+

Example

+
+
+
+
keys({a : 3, b : 4}) // returns ["a", "b"]
+
+
+
+
+

9.3.33. left

+
+

left(subject, [elements]) ⇒ string | array

+
+
+
+
Description
+
+

Return a substring from the start of a string or the +left-most elements of an array

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

subject

string | array

The source text/array of code +points/elements

[elements]

integer

1

number of elements to pick

+
+
+
+
+

Example

+
+
+
+
left("Sale Price", 4) // returns "Sale"
+left("Sweden") // returns "S"
+left([4, 5, 6], 2) // returns [4, 5]
+
+
+
+
+

9.3.34. length

+
+

length(subject) ⇒ integer

+
+
+
+
Description
+
+

Calculates the length of the input argument based on +types:

+
+
    +
  • +

    string: returns the number of unicode code points

    +
  • +
  • +

    array: returns the number of array elements

    +
  • +
  • +

    object: returns the number of key-value pairs

    +
  • +
+
+
+
Returns
+
+

integer - the length of the input subject

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | array | object

subject whose length to +calculate

+
+
+
+
+

Example

+
+
+
+
length(`[]`) // returns 0
+length("") // returns 0
+length("abcd") // returns 4
+length([1, 2, 3, 4]) // returns 4
+length(`{}`) // returns 0
+length({a : 3, b : 4}) // returns 2
+
+
+
+
+

9.3.35. log

+
+

log(num) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the natural logarithm (base e) of a number

+
+
Returns
+
+

number | Array.<number> - The natural log value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

A number greater than zero

+
+
+
+
+

Example

+
+
+
+
log(10) // 2.302585092994046
+
+
+
+
+

9.3.36. log10

+
+

log10(num) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Compute the base 10 logarithm of a number.

+
+
Returns
+
+

number | Array.<number> - The base 10 log result

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

A number greater than or equal to +zero

+
+
+
+
+

Example

+
+
+
+
log10(100000) // 5
+
+
+
+
+

9.3.37. lower

+
+

lower(input) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Converts all the alphabetic code points in a string to +lowercase.

+
+
Returns
+
+

string | Array.<string> - the lower case value of the +input string

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

input

string | Array.<string>

input string

+
+
+
+
+

Example

+
+
+
+
lower("E. E. Cummings") // returns "e. e. cummings"
+
+
+
+
+

9.3.38. map

+
+

map(elements, expr) ⇒ array

+
+
+
+
Description
+
+

Apply an expression to every element in an array and +return the array of results. An input array of length N will return an +array of length N.

+
+
Returns
+
+

array - the mapped array

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

elements

array

array of elements to process

expr

expression

expression to evaluate

+
+
+
+
+

Example

+
+
+
+
map([1, 2, 3, 4], &(@ + 1)) // returns [2, 3, 4, 5]
+map(["doe", "nick", "chris"], &length(@)) // returns [3, 4, 5]
+
+
+
+
+

9.3.39. max

+
+

max(…collection) ⇒ number

+
+
+
+
Description
+
+

Calculates the largest value in the input numbers. Any +values that are not numbers (null, boolean, strings, objects) will be +ignored. If any parameters are arrays, the arrays will be flattened. If +no numbers are provided, the function will return zero.

+
+
Returns
+
+

number - the largest value found

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

…collection

array | any

values/array(s) in which the maximum +element is to be calculated

+
+
+
+
+

Example

+
+
+
+
max([1, 2, 3], [4, 5, 6]) // returns 6
+max([\"a\", \"a1\", \"b\"], null(), true())) // returns 0
+max(8, 10, 12, "14") // returns 12
+
+
+
+
+

9.3.40. maxA

+
+

maxA(…collection) ⇒ number

+
+
+
+
Description
+
+

Calculates the largest value in the input values, coercing +parameters to numbers. Null values are ignored. If any parameters cannot +be converted to a number, the function will fail with a type error. If +any parameters are arrays, the arrays will be flattened. If no numbers +are provided, the function will return zero.

+
+
Returns
+
+

number - the largest value found

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

…collection

any

values/array(s) in which the maximum element is to be +calculated

+
+
+
+
+

Example

+
+
+
+
maxA([1, 2, 3], [4, 5, 6]) // returns 6
+maxA(["a", "a1", "b", null()]) // error
+maxA(8, 10, 12, "14") // returns 14
+
+
+
+
+

9.3.41. merge

+
+

merge(…args) ⇒ object

+
+
+
+
Description
+
+

Accepts one or more objects, and returns a single object +with all objects merged. The first object is copied, and then and each +key value pair from each subsequent object are added to the first +object. Duplicate keys in subsequent objects will override those found +in earlier objects.

+
+
Returns
+
+

object - The combined object

+
+
Parameters
+
+ ++++ + + + + + + + + + + + + +
ParamType

…args

object

+
+
+
+
+

Example

+
+
+
+
merge({a: 1, b: 2}, {c : 3, d: 4}) // returns {a :1, b: 2, c: 3, d: 4}
+merge({a: 1, b: 2}, {a : 3, d: 4}) // returns {a :3, b: 2, d: 4}
+
+
+
+
+

9.3.42. mid

+
+

mid(subject, startPos, length) ⇒ string | array

+
+
+
+
Description
+
+

Extracts a substring from text, or a subset from an array.

+
+
Returns
+
+

string | array - The resulting substring or array +subset of elements

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | array

the text string or array of elements +from which to extract.

startPos

integer

the zero-based position of the first code point or +element to extract.

length

integer

The number of code points or elements to return from +the string or array. If greater then the length of subject the length +of the subject is used.

+
+
+
+
+

Example

+
+
+
+
mid("Fluid Flow", 0, 5) // returns "Fluid"
+mid("Fluid Flow", 6, 20) // returns "Flow"
+mid("Fluid Flow", 20, 5) // returns ""
+mid([0,1,2,3,4,5,6,7,8,9], 2, 3) // returns [2,3,4]
+
+
+
+
+

9.3.43. millisecond

+
+

millisecond(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Extract the milliseconds of the time value in a +date/time value.

+
+
Returns
+
+

integer | Array.<integer> - The number of milliseconds: +0 through 999

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

datetime/time for which the +millisecond is to be returned. Date/time values can be generated using +the datetime, toDate, today, +now and time functions.

+
+
+
+
+

Example

+
+
+
+
millisecond(datetime(2008, 5, 23, 12, 10, 53, 42)) // returns 42
+
+
+
+
+

9.3.44. min

+
+

min(…collection) ⇒ number

+
+
+
+
Description
+
+

Calculates the smallest value in the input numbers. Any +values that are not numbers (null, boolean, string, object) will be +ignored. If any parameters are arrays, the arrays will be flattened. If +no numbers are provided, the function will return zero.

+
+
Returns
+
+

number - the smallest value found

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

…collection

Array.<any> | any

Values/arrays to search for the +minimum value

+
+
+
+
+

Example

+
+
+
+
min([1, 2, 3], [4, 5, 6]) // returns 1
+min("4", 8, 10, 12, null()) // returns 8
+
+
+
+
+

9.3.45. minA

+
+

minA(…collection) ⇒ number

+
+
+
+
Description
+
+

Calculates the smallest value in the input values, +coercing parameters to numbers. Null values are ignored. If any +parameters cannot be converted to a number, the function will fail with +a type error. If any parameters are arrays, the arrays will be +flattened. If no numbers are provided, the function will return zero.

+
+
Returns
+
+

number - the largest value found

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

…collection

Array.<any> | any

values/array(s) in which the +maximum element is to be calculated

+
+
+
+
+

Example

+
+
+
+
minA([1, 2, 3], [4, 5, 6]) // returns 1
+minA("4", 8, 10, 12, null()) // returns 4
+
+
+
+
+

9.3.46. minute

+
+

minute(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Extract the minute (0 through 59) from a +date/time value

+
+
Returns
+
+

integer | Array.<integer> - Number of minutes in the +time portion of the date/time value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

A datetime/time value. Date/time +values can be generated using the datetime, +toDate, today, now and +time functions.

+
+
+
+
+

Example

+
+
+
+
minute(datetime(2008,5,23,12, 10, 0)) // returns 10
+minute(time(12, 10, 0)) // returns 10
+
+
+
+
+

9.3.47. mod

+
+

mod(dividend, divisor) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Return the remainder when one number is divided by another +number.

+
+
Returns
+
+

number | Array.<number> - Computes the remainder of +dividend/divisor. If dividend is negative, the result will also be +negative. If dividend is zero, an error is thrown.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

dividend

number | Array.<number>

The number for which to find +the remainder.

divisor

number | Array.<number>

The number by which to divide +number.

+
+
+
+
+

Example

+
+
+
+
mod(3, 2) // returns 1
+mod(-3, 2) // returns -1
+
+
+
+
+

9.3.48. month

+
+

month(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Finds the month of a date.

+
+
Returns
+
+

integer | Array.<integer> - The month number value, +ranging from 1 (January) to 12 (December)

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

source date/time value. Date/time values can be generated using the +datetime, toDate, today, +now and time functions.

+
+
+
+
+

Example

+
+
+
+
month(datetime(2008,5,23)) // returns 5
+
+
+
+
+

9.3.49. not

+
+

not(value) ⇒ boolean

+
+
+
+
Description
+
+

Compute logical NOT of a value. If the parameter is not +boolean it will be cast to boolean Note the +related unary NOT operator.

+
+
Returns
+
+

boolean - The logical NOT applied to the input parameter

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

value

any

any data type

+
+
+
+
+

Example

+
+
+
+
not(length("bar") > 0) // returns false
+not(false()) // returns true
+not("abcd") // returns false
+not("") // returns true
+
+
+
+
+

9.3.50. notNull

+
+

notNull(…argument) ⇒ any

+
+
+
+
Description
+
+

Finds the first argument that does not resolve to null. +This function accepts one or more arguments, and will evaluate them in +order until a non-null argument is encountered. If all arguments values +resolve to null, then return a null value.

+
+
Parameters
+
+ ++++ + + + + + + + + + + + + +
ParamType

…argument

any

+
+
+
+
+

Example

+
+
+
+
notNull(1, 2, 3, 4, `null`) // returns 1
+notNull(`null`, 2, 3, 4, `null`) // returns 2
+
+
+
+
+

9.3.51. now

+
+

now() ⇒ number

+
+
+
+
Description
+
+

Retrieve the current date/time.

+
+
Returns
+
+

number - representation of the current date/time value.

+
+
+
+
+
+

9.3.52. null

+
+

null() ⇒ boolean

+
+
+
+
Description
+
+

Return constant null value. Expressions may also use the +JSON literal: `null`

+
+
Returns
+
+

boolean - True

+
+
+
+
+
+

9.3.53. or

+
+

or(first, […operand]) ⇒ boolean

+
+
+
+
Description
+
+

Determines the logical OR result of a set of parameters. +If the parameters are not boolean they will be +cast to boolean. Note the related +Or Operator.

+
+
Returns
+
+

boolean - The logical result of applying OR to all parameters

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

first

any

logical expression

[…operand]

any

any number of additional expressions

+
+
+
+
+

Example

+
+
+
+
or((x / 2) == y, (y * 2) == x) // true
+
+
+
+
+

9.3.54. power

+
+

power(a, x) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Computes a raised to a power x. (a^x)

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

a

number | Array.<number>

The base number – can be any real +number.

x

number | Array.<number>

The exponent to which the base number +is raised.

+
+
+
+
+

Example

+
+
+
+
power(10, 2) // returns 100 (10 raised to power 2)
+
+
+
+
+

9.3.55. proper

+
+

proper(text) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Apply proper casing to a string. Proper casing is where +the first letter of each word is converted to an uppercase letter and +the rest of the letters in the word converted to lowercase. Words are +demarcated by whitespace, punctuation, or numbers. Specifically, any +character(s) matching the regular expression: [\s\d\p{P}]+.

+
+
Returns
+
+

string | Array.<string> - source string with proper +casing applied.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

text

string | Array.<string>

source string

+
+
+
+
+

Example

+
+
+
+
proper("this is a TITLE") // returns "This Is A Title"
+proper("2-way street") // returns "2-Way Street"
+proper("76BudGet") // returns "76Budget"
+
+
+
+
+

9.3.56. random

+
+

random() ⇒ number

+
+
+
+
Description
+
+

Generate a pseudo random number.

+
+
Returns
+
+

number - A value greater than or equal to zero, and less than +one.
+Example

+
+
+
+
+
+
random() // 0.022585461160693265
+
+
+
+
+

9.3.57. reduce

+
+

reduce(elements, expr, initialValue) ⇒ any

+
+
+
+
Description
+
+

Executes a user-supplied reducer expression on each +element of an array, in order, passing in the return value from the +expression from the preceding element. The final result of running the +reducer across all elements of the input array is a single value. The +expression can access the following properties of the current object:

+
+
    +
  • +

    accumulated: accumulated value based on the previous expression. For +the first array element use the initialValue parameter. If not +provided, then null

    +
  • +
  • +

    current: current element to process

    +
  • +
  • +

    index: index of the current element in the array

    +
  • +
  • +

    array: original array

    +
  • +
+
+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

elements

array

array of elements on which the expression will be +evaluated

expr

expression

reducer expression to be executed on each element

initialValue

any

the accumulated value to pass to the first array +element

+
+
+
+
+

Example

+
+
+
+
reduce([1, 2, 3], &(accumulated + current)) // returns 6
+// find maximum entry by age
+reduce(
+  [{age: 10, name: "Joe"},{age: 20, name: "John"}],
+  &max(@.accumulated.age, @.current.age), @[0].age)
+reduce([3, 3, 3], &accumulated * current, 1) // returns 27
+
+
+
+
+

9.3.58. register

+
+

register(functionName, expr) ⇒ Object

+
+
+
+
Description
+
+

Register a function. The registered function may take one +parameter. If more parameters are needed, combine them in an array or +object. A function may not be re-registered with a different definition. +Note that implementations are not required to provide register() in +order to be conformant. Built-in functions may not be overridden.

+
+
Returns
+
+

Object - returns an empty object

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

functionName

string

Name of the function to register. functionName +must begin with an underscore or uppercase letter and follow the regular +expression pattern: +^[_A-Z][_a-zA-Z0-9$]*$

expr

expression

Expression to execute with this function call

+
+
+
+
+

Example

+
+
+
+
register("_product", &@[0] * @[1]) // can now call: _product([2,21]) => returns 42
+register("_ltrim", &split(@,"").reduce(@, &accumulated & current | if(@ = " ", "", @), ""))
+// _ltrim("  abc  ") => returns "abc  "
+
+
+
+
+

9.3.59. registerWithParams

+
+

registerWithParams(functionName, expr) ⇒ Object

+
+
+
+
Description
+
+

Register a function that accepts multiple parameters. A +function may not be re-registered with a different definition. Note that +implementations are not required to provide registerWithParams() in +order to be conformant. Built-in functions may not be overridden.

+
+
Returns
+
+

Object - returns an empty object

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

functionName

string

Name of the function to register. functionName +must begin with an underscore or uppercase letter and follow the regular +expression pattern: +^[_A-Z][_a-zA-Z0-9$]*$

expr

expression

Expression to execute with this function call. +Parameters are passed as an array.

+
+
+
+
+

Example

+
+
+
+
registerWithParams("Product", &@[0] * @[1])
+// can now call: Product(2,21) => returns 42
+registerWithParams(
+  "Ltrim",
+  &split(@[0],"").reduce(@, &accumulated & current | if(@ = " ", "", @), "")
+ )
+// Ltrim("  abc  ") => returns "abc  "
+
+
+
+
+

9.3.60. replace

+
+

replace(subject, start, length, replacement) ⇒ string | array

+
+
+
+
Description
+
+

Generates text (or an array) where we substitute elements +at a given start position and length, with new text (or array elements).

+
+
Returns
+
+

string | array - the resulting text or array

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | array

original text or array

start

integer

zero-based index in the original text from where to +begin the replacement. Must be greater than or equal to 0.

length

integer

number of code points to be replaced. If start
+length is greater than the length of subject, all text past start +will be replaced.

replacement

any

Replacement to insert at the start index. If +subject is an array, and replacement is an array, the replacement +array elements will be inserted into the subject array. If subject +is an array and replacement is not an array, the replacement will be +inserted as a single element in subject If subject is a string, the +replacement will be coerced to a string.

+
+
+
+
+

Example

+
+
+
+
replace("abcdefghijk", 5, 5, "*") // returns abcde*k
+replace("2009",2,2,"10") // returns  2010
+replace("123456",0,3,"@") // returns @456
+replace(["blue","black","white","red"], 1, 2, ["green"]) // returns ["blue","green","red"]
+
+
+
+
+

9.3.61. rept

+
+

rept(text, count) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Return text repeated count times.

+
+
Returns
+
+

string | Array.<string> - Text generated from the +repeated text. if count is zero, returns an empty string.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

text

string | Array.<string>

text to repeat

count

integer | Array.<integer>

number of times to repeat the +text. Must be greater than or equal to 0.

+
+
+
+
+

Example

+
+
+
+
rept("x", 5) // returns "xxxxx"
+
+
+
+
+

9.3.62. reverse

+
+

reverse(subject) ⇒ array

+
+
+
+
Description
+
+

Reverses the order of an array or the order of code points +in a string

+
+
Returns
+
+

array - The resulting reversed array or string

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | array

the source to be reversed

+
+
+
+
+

Example

+
+
+
+
reverse(["a", "b", "c"]) // returns ["c", "b", "a"]
+
+
+
+
+

9.3.63. right

+
+

right(subject, [elements]) ⇒ string | array

+
+
+
+
Description
+
+

Generates a string from the right-most code points of a +string or a subset of elements from the end of an array

+
+
Returns
+
+

string | array - The extracted substring or array +subset Returns null if the number of elements is less than 0

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

subject

string | array

The text/array containing the code +points/elements to extract

[elements]

integer

1

number of elements to pick

+
+
+
+
+

Example

+
+
+
+
right("Sale Price", 4) // returns "rice"
+right("Sweden") // returns "n"
+right([4, 5, 6], 2) // returns [5, 6]
+
+
+
+
+

9.3.64. round

+
+

round(num, [precision]) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Round a number to a specified precision:

+
+
    +
  • +

    If precision is greater than zero, round to the specified number of +decimal places.

    +
  • +
  • +

    If precision is 0, round to the nearest integer.

    +
  • +
  • +

    If precision is less than 0, round to the left of the decimal point.

    +
  • +
+
+
+
Returns
+
+

number | Array.<number> - rounded value. Rounding a +half value will round up.

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

num

number | Array.<number>

number to round

[precision]

integer | Array.<integer>

0

precision to use for +the rounding operation.

+
+
+
+
+

Example

+
+
+
+
round(2.15, 1) // returns 2.2
+round(626.3,-3) // returns 1000 (Rounds 626.3 to the nearest multiple of 1000)
+round(626.3, 0) // returns 626
+round(1.98,-1) // returns 0 (Rounds 1.98 to the nearest multiple of 10)
+round(-50.55,-2) // -100 (round -50.55 to the nearest multiple of 100)
+round(1.95583) // 2
+round(-1.5) // -1
+
+
+
+
+ +
+

search(findText, withinText, [startPos]) ⇒ array

+
+
+
+
Description
+
+

Perform a wildcard search. The search is case-sensitive +and supports two forms of wildcards: * finds a sequence of +code points and ? finds a single code point. To use * or +? or \ as text values, precede them with an escape +(\) character. Note that the wildcard search is not greedy. +e.g. search("a*b", "abb") will return [0, "ab"] Not +[0, "abb"]

+
+
Returns
+
+

array - returns an array with two values:

+
+
    +
  • +

    The start position of the found text and the text string that was +found.

    +
  • +
  • +

    If a match was not found, an empty array is returned.

    +
  • +
+
+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

findText

string | Array.<string>

the search string – which +may include wild cards.

withinText

string | Array.<string>

The string to search.

[startPos]

integer | Array.<integer>

0

The zero-based position +of withinText to start searching. A negative value is not allowed.

+
+
+
+
+

Example

+
+
+
+
search("a?c", "acabc") // returns [2, "abc"]
+
+
+
+
+

9.3.66. second

+
+

second(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Extract the seconds of the time value in a +date/time value.

+
+
Returns
+
+

integer | Array.<integer> - The number of seconds: 0 +through 59

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

datetime/time for which the second +is to be returned. Date/time values can be generated using the +datetime, toDate, today, +now and time functions.

+
+
+
+
+

Example

+
+
+
+
second(datetime(2008,5,23,12, 10, 53)) // returns 53
+second(time(12, 10, 53)) // returns 53
+
+
+
+
+

9.3.67. sign

+
+

sign(num) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Computes the sign of a number passed as argument.

+
+
Returns
+
+

number | Array.<number> - returns 1 or -1, indicating +the sign of num. If the num is 0, it will return 0.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

any number

+
+
+
+
+

Example

+
+
+
+
sign(5) // 1
+sign(-5) // -1
+sign(0) // 0
+
+
+
+
+

9.3.68. sin

+
+

sin(angle) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Computes the sine of a number in radians

+
+
Returns
+
+

number | Array.<number> - The sine of angle, between +-1 and 1, inclusive

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

angle

number | Array.<number>

A number representing an angle in +radians.

+
+
+
+
+

Example

+
+
+
+
sin(0) // 0
+sin(1) // 0.8414709848078965
+
+
+
+
+

9.3.69. sort

+
+

sort(list) ⇒ Array.<any>

+
+
+
+
Description
+
+

This function accepts an array values and returns an array +with the elements in sorted order. If there are mixed data types, the +values will be grouped in order: numbers, strings, booleans, nulls +String sorting is based on code points and is not locale-sensitive. If +the sort encounters any objects or arrays, it will throw an evaluation +error.

+
+
Returns
+
+

Array.<any> - The ordered result

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

list

Array.<any>

to be sorted

+
+
+
+
+

Example

+
+
+
+
sort([1, 2, 4, 3, 1]) // returns [1, 1, 2, 3, 4]
+sort(["20", 20, true(), "100", null(), 100]) // returns [20, 100, "100", "20", true, null]
+
+
+
+
+

9.3.70. sortBy

+
+

sortBy(elements, expr) ⇒ array

+
+
+
+
Description
+
+

Sort an array using an expression to find the sort key. +For each element in the array, the expression is applied and the +resulting value is used as the sort value. If the result of evaluating +the expression against the current array element results in type other +than a number or a string, a TypeError will occur.

+
+
Returns
+
+

array - The sorted array

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

elements

array

Array to be sorted

expr

expression

The comparison expression

+
+
+
+
+

Example

+
+
+
+
// returns ["e", "def", "abcd"]
+sortBy(["abcd", "e", "def"], &length(@))
+
+// returns [{year: 1910}, {year: 2010}, {year: 2020}]
+sortBy([{year: 2010}, {year: 2020}, {year: 1910}], &year)
+
+// returns [5, -10, -11, -15, 30]
+sortBy([-15, 30, -10, -11, 5], &abs(@))
+
+
+
+
+

9.3.71. split

+
+

split(string, separator) ⇒ Array.<string> | +Array.<Array.<string>>

+
+
+
+
Description
+
+

Split a string into an array, given a separator

+
+
Returns
+
+

Array.<string> | Array.<Array.<string>> - The array of +separated strings

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

string

string | Array.<string>

string to split

separator

string | Array.<string>

separator where the split(s) +should occur

+
+
+
+
+

Example

+
+
+
+
split("abcdef", "") // returns ["a", "b", "c", "d", "e", "f"]
+split("abcdef", "e") // returns ["abcd", "f"]
+
+
+
+
+

9.3.72. sqrt

+
+

sqrt(num) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Find the square root of a number

+
+
Returns
+
+

number | Array.<number> - The calculated square root +value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

num

number | Array.<number>

source number

+
+
+
+
+

Example

+
+
+
+
sqrt(4) // returns 2
+
+
+
+
+

9.3.73. startsWith

+
+

startsWith(subject, prefix) ⇒ boolean | Array.<boolean>

+
+
+
+
Description
+
+

Determine if a string starts with a prefix.

+
+
Returns
+
+

boolean | Array.<boolean> - true if prefix matches +the start of subject

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

string | Array.<string>

string to search

prefix

string | Array.<string>

prefix to search for

+
+
+
+
+

Example

+
+
+
+
startsWith("jack is at home", "jack") // returns true
+
+
+
+
+

9.3.74. stdev

+
+

stdev(values) ⇒ number

+
+
+
+
Description
+
+

Estimates standard deviation based on a sample. stdev +assumes that its arguments are a sample of the entire population. If +your data represents a entire population, then compute the standard +deviation using stdevp. Non-numeric values (text, boolean, +null etc) are ignored. If there are nested arrays, they are flattened.

+
+
Returns
+
+

number - +Standard deviation

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

values

Array.<any>

The array containing numbers comprising the +population. Array size must be greater than 1.

+
+
+
+
+

Example

+
+
+
+
stdev([1345, 1301, 1368]) // returns 34.044089061098404
+stdevp([1345, 1301, 1368]) // returns 27.797
+
+
+
+
+

9.3.75. stdevA

+
+

stdevA(numbers) ⇒ number

+
+
+
+
Description
+
+

Estimates standard deviation based on a sample. stdev +assumes that its arguments are a sample of the entire population. If +your data represents a entire population, then compute the standard +deviation using stdevpA. Nested arrays are flattened. Null values are +ignored. All other parameters are converted to number. If conversion to +number fails, a type error is thrown.

+
+
Returns
+
+

number - +Standard deviation

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

numbers

Array.<number>

The array of numbers comprising the +population. Array size must be greater than 1.

+
+
+
+
+

Example

+
+
+
+
stdevA([1345, "1301", 1368]) // returns 34.044089061098404
+stdevpA([1345, 1301, "1368"]) // returns 27.797
+
+
+
+
+

9.3.76. stdevp

+
+

stdevp(values) ⇒ number

+
+
+
+
Description
+
+

Calculates standard deviation based on the entire +population given as arguments. stdevp assumes that its arguments are +the entire population. If your data represents a sample of the +population, then compute the standard deviation using +stdev. Non-numeric values (text, boolean, null etc) are +ignored. If there are nested arrays, they are flattened.

+
+
Returns
+
+

number - Calculated standard deviation

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

values

Array.<any>

The array containing numbers comprising the +population. An empty array is not allowed.

+
+
+
+
+

Example

+
+
+
+
stdevp([1345, 1301, 1368]) // returns 27.797
+stdev([1345, 1301, 1368]) // returns 34.044
+
+
+
+
+

9.3.77. stdevp

+
+

stdevp(numbers) ⇒ number

+
+
+
+
Description
+
+

Calculates standard deviation based on the entire +population given as arguments. stdevpA assumes that its arguments are +the entire population. If your data represents a sample of the +population, then compute the standard deviation using +[_stdevA]. Nested arrays are flattened. Null values are +ignored. All other parameters are converted to number. If conversion to +number fails, a type error is thrown.

+
+
Returns
+
+

number - Calculated standard deviation

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

numbers

Array.<number>

The array of numbers comprising the +population. An empty array is not allowed.

+
+
+
+
+

Example

+
+
+
+
stdevpA([1345, "1301", 1368]) // returns 27.797
+stdevA([1345, 1301, "1368"]) // returns 34.044
+
+
+
+
+

9.3.78. substitute

+
+

substitute(text, old, new, [which]) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Generates a string from the input text, with text old +replaced by text new (when searching from the left). If there is no +match, or if old has length 0, text is returned unchanged. Note that +old and new may have different lengths.

+
+
Returns
+
+

string | Array.<string> - replaced string

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

text

string | Array.<string>

The text for which to substitute +code points.

old

string | Array.<string>

The text to replace.

new

string | Array.<string>

The text to replace old with. If +new is an empty string, then occurrences of old are removed from +text.

[which]

integer | Array.<integer>

The zero-based occurrence of +old text to replace with new text. If which parameter is omitted, +every occurrence of old is replaced with new.

+
+
+
+
+

Example

+
+
+
+
substitute("Sales Data", "Sales", "Cost") // returns "Cost Data"
+substitute("Quarter 1, 2001", "1", "2", 1)" // returns "Quarter 1, 2002"
+substitute("Quarter 1, 2011", "1", "2", 2)" // returns "Quarter 1, 2012"
+
+
+
+
+

9.3.79. sum

+
+

sum(collection) ⇒ number

+
+
+
+
Description
+
+

Calculates the sum of the provided array. An empty array +will produce a return value of 0. Any values that are not numbers (null, +boolean, strings, objects) will be ignored. If any parameters are +arrays, the arrays will be flattened.

+
+
Returns
+
+

number - The computed sum

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

collection

Array.<any>

array of values

+
+
+
+
+

Example

+
+
+
+
sum([1, 2, 3]) // returns 6
+
+
+
+
+

9.3.80. tan

+
+

tan(angle) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Computes the tangent of a number in radians

+
+
Returns
+
+

number | Array.<number> - The tangent of angle

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

angle

number | Array.<number>

A number representing an angle in +radians.

+
+
+
+
+

Example

+
+
+
+
tan(0) // 0
+tan(1) // 1.5574077246549023
+
+
+
+
+

9.3.81. time

+
+

time(hours, [minutes], [seconds]) ⇒ number

+
+
+
+
Description
+
+

Construct and returns a time +value. If any of the units are greater or less than their normal +range, the overflow/underflow will be added/subtracted from the next +greater unit.

+
+
Returns
+
+

number - Returns a date/time value representing the fraction +of the day consumed by the given time

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

hours

integer

Zero-based integer value between 0 and 23 +representing the hour of the day.

[minutes]

integer

0

Zero-based integer value representing the minute +segment of a time.

[seconds]

integer

0

Zero-based integer value representing the +seconds segment of a time.

+
+
+
+
+

Example

+
+
+
+
time(12, 0, 0) | [hour(@), minute(@), second(@)] // returns [12, 0, 0]
+
+
+
+
+

9.3.82. toArray

+
+

toArray(arg) ⇒ array

+
+
+
+
Description
+
+

Converts the provided argument to an array. The conversion +happens as per the following rules:

+
+
    +
  • +

    array - Returns the provided value.

    +
  • +
  • +

    number/string/object/boolean/null - Returns a one element array +containing the argument.

    +
  • +
+
+
+
Returns
+
+

array - The resulting array

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

arg

any

parameter to turn into an array

+
+
+
+
+

Example

+
+
+
+
toArray(1) // returns [1]
+toArray(null()) // returns [`null`]
+
+
+
+
+

9.3.83. toDate

+
+

toDate(ISOString) ⇒ number

+
+
+
+
Description
+
+

Converts the provided string to a date/time value.

+
+
Returns
+
+

number - The resulting date/time +number. If conversion fails, return null.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

ISOString

string

An +ISO8601 formatted +string. (limited to the RFC +3339 profile) If the string does not include a timezone offset (or +trailing `Z'), it will be assumed to be local time

+
+
+
+
+

Example

+
+
+
+
toDate("20231110T130000+04:00") // returns 19671.375
+toDate("2023-11-10T13:00:00+04:00") // returns 19671.375
+toDate("20231110") | year(@) & "/" & month(@) // returns "2023/11"
+
+
+
+
+

9.3.84. today

+
+

today() ⇒ number

+
+
+
+
Description
+
+

Returns a date/time value +representing the start of the current day. i.e. midnight

+
+
Returns
+
+

number - today at midnight

+
+
+
+
+
+

9.3.85. toNumber

+
+

toNumber(value, [base]) ⇒ number

+
+
+
+
Description
+
+

Converts the provided arg to a number. The conversions +follow the type coercion rules but will also: * +Convert non-numeric strings to zero * Convert arrays to arrays of +numbers

+
+
Returns
+
+

number - The resulting number. If conversion to number fails, +return null.

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

value

any | Array.<any>

to convert to number

[base]

integer | Array.<integer>

10

If the input arg is a +string, the base to use to convert to number. One of: 2, 8, 10, 16. +Defaults to 10.

+
+
+
+
+

Example

+
+
+
+
toNumber(1) // returns 1
+toNumber("10") // returns 10
+toNumber({a: 1}) // returns null
+toNumber(true()) // returns 1
+toNumber("10f") // returns null
+toNumber("FF", 16) // returns 255
+
+
+
+
+

9.3.86. toString

+
+

toString(arg, [indent]) ⇒ string

+
+
+
+
Description
+
+

Returns the argument converted to a string. If the +argument is a string, it will be returned unchanged. Otherwise, returns +the JSON encoded value of the argument.

+
+
Returns
+
+

string - The result string.

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

arg

any

Value to be converted to a string

[indent]

integer

0

Indentation to use when converting objects and +arrays to a JSON string

+
+
+
+
+

Example

+
+
+
+
toString(1) // returns "1"
+toString(true()) // returns "true"
+toString({sum: 12 + 13}) // "{"sum":25}"
+toString("hello") // returns "hello"
+
+
+
+
+

9.3.87. trim

+
+

trim(text) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Remove leading and trailing spaces (U+0020), and replace +all internal multiple spaces with a single space. Note that other +whitespace characters are left intact.

+
+
Returns
+
+

string | Array.<string> - trimmed string

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

text

string | Array.<string>

string to trim

+
+
+
+
+

Example

+
+
+
+
trim("   ab    c   ") // returns "ab c"
+
+
+
+
+

9.3.88. true

+
+

true() ⇒ boolean

+
+
+
+
Description
+
+

Return constant boolean true value. Expressions may also +use the JSON literal: `true`

+
+
Returns
+
+

boolean - True

+
+
+
+
+
+

9.3.89. trunc

+
+

trunc(numA, [numB]) ⇒ number | Array.<number>

+
+
+
+
Description
+
+

Truncates a number to an integer by removing the +fractional part of the number. i.e. it rounds towards zero.

+
+
Returns
+
+

number | Array.<number> - Truncated value

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

numA

number | Array.<number>

number to truncate

[numB]

integer | Array.<integer>

0

A number specifying the +number of decimal digits to preserve.

+
+
+
+
+

Example

+
+
+
+
trunc(8.9) // returns 8
+trunc(-8.9) // returns -8
+trunc(8.912, 2) // returns 8.91
+
+
+
+
+

9.3.90. type

+
+

type(subject) ⇒ string

+
+
+
+
Description
+
+

Finds the type name of the given subject argument as a +string value. The return value will be one of the following:

+
+
    +
  • +

    number

    +
  • +
  • +

    string

    +
  • +
  • +

    boolean

    +
  • +
  • +

    array

    +
  • +
  • +

    object

    +
  • +
  • +

    null

    +
  • +
+
+
+
Returns
+
+

string - The type name

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

subject

any

type to evaluate

+
+
+
+
+

Example

+
+
+
+
type(1) // returns "number"
+type("") // returns "string"
+
+
+
+
+

9.3.91. unique

+
+

unique(input) ⇒ array

+
+
+
+
Description
+
+

Find the set of unique elements within an array

+
+
Returns
+
+

array - array with duplicate elements removed

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

input

array

input array

+
+
+
+
+

Example

+
+
+
+
unique([1, 2, 3, 4, 1, 1, 2]) // returns [1, 2, 3, 4]
+
+
+
+
+

9.3.92. upper

+
+

upper(input) ⇒ string | Array.<string>

+
+
+
+
Description
+
+

Converts all the alphabetic code points in a string to +uppercase.

+
+
Returns
+
+

string | Array.<string> - the upper case value of the +input string

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

input

string | Array.<string>

input string

+
+
+
+
+

Example

+
+
+
+
upper("abcd") // returns "ABCD"
+
+
+
+
+

9.3.93. value

+
+

value(subject, index) ⇒ any

+
+
+
+
Description
+
+

Perform an indexed lookup on an object or array

+
+
Returns
+
+

any - the result of the lookup – or null if not found.

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + + + + + + +
ParamTypeDescription

subject

object | array | null

on which to perform the +lookup. When querying for hidden properties, +subject may be any data type.

index

string | integer

if subject is an object, index must +be a string indicating the key name to search for. If subject is an +array, then index must be an integer indicating the offset into the +array

+
+
+
+
+

Example

+
+
+
+
value({a: 1, b:2, c:3}, "a") // returns 1
+value([1, 2, 3, 4], 2) // returns 3
+
+
+
+
+

9.3.94. values

+
+

values(obj) ⇒ array

+
+
+
+
Description
+
+

Generates an array of the values of the provided object. +Note that because JSON objects are inherently unordered, the values +associated with the provided object are also unordered.

+
+
Returns
+
+

array - array of the values

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

obj

object

source object

+
+
+
+
+

Example

+
+
+
+
values({a : 3, b : 4}) // returns [3, 4]
+
+
+
+
+

9.3.95. weekday

+
+

weekday(date, [returnType]) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Extract the day of the week from a date. The specific +numbering of the day of week is controlled by the returnType +parameter:

+
+
    +
  • +

    1 : Sunday (1), Monday (2), …, Saturday (7)

    +
  • +
  • +

    2 : Monday (1), Tuesday (2), …, Sunday(7)

    +
  • +
  • +

    3 : Monday (0), Tuesday (1), …., Sunday(6)

    +
  • +
+
+
+
Returns
+
+

integer | Array.<integer> - day of the week

+
+
Parameters
+
+ ++++++ + + + + + + + + + + + + + + + + + + + + + + +
ParamTypeDefaultDescription

date

number | Array.<number>

date/time value for which the day of the week is to be returned. +Date/time values can be generated using the datetime, +toDate, today, now and +time functions.

[returnType]

integer | Array.<integer>

1

Determines the +representation of the result. An unrecognized returnType will result in +a error.

+
+
+
+
+

Example

+
+
+
+
weekday(datetime(2006,5,21)) // 1
+weekday(datetime(2006,5,21), 2) // 7
+weekday(datetime(2006,5,21), 3) // 6
+
+
+
+
+

9.3.96. year

+
+

year(date) ⇒ integer | Array.<integer>

+
+
+
+
Description
+
+

Finds the year of a datetime value

+
+
Returns
+
+

integer | Array.<integer> - The year value

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

date

number | Array.<number>

input date/time value Date/time values can be generated using the +datetime, toDate, today, +now and time functions.

+
+
+
+
+

Example

+
+
+
+
year(datetime(2008,5,23)) // returns 2008
+
+
+
+
+

9.3.97. zip

+
+

zip(…arrays) ⇒ array

+
+
+
+
Description
+
+

Generates a convolved (zipped) array containing grouped +arrays of values from the array arguments from index 0, 1, 2, etc. This +function accepts a variable number of arguments. The length of the +returned array is equal to the length of the shortest array.

+
+
Returns
+
+

array - An array of arrays with elements zipped together

+
+
Parameters
+
+ +++++ + + + + + + + + + + + + + + +
ParamTypeDescription

…arrays

array

array of arrays to zip together

+
+
+
+
+

Example

+
+
+
+
zip([1, 2, 3], [4, 5, 6, 7]) // returns [[1, 4], [2, 5], [3, 6]]
+
+
+
+
+
+
+
+

10. Integrations

+
+
+

The json-formula API allows integrations to customize various json-formula behaviors.

+
+
+

10.1. Globals

+
+

By default, json-formula has one global symbol: @. A host may inject additional global identifiers. These identifiers must be prefixed with the dollar ($) symbol.

+
+

Examples

+
+

Given: a global symbol:

+
+
+
+
  {
+    "$days": [
+       "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
+    ]
+  }
+
+
+
+
+
    eval(value($days, weekday(datetime(date.year, date.month, date.day), 3)),
+    {
+      "date": {
+        "year": 2023,
+        "month": 9,
+        "day": 13
+      }
+    }) -> "Wednesday"
+
+
+
+
+

10.2. Specify locale

+
+

The default locale for json-formula is en-US. A host may specify an alternate locale. The locale setting affects only the behavior of the casefold() function.

+
+
+
+

10.3. Custom toNumber

+
+

In various contexts, json-formula converts values to numbers. +A host may provide its own toNumber() function that json-formula will use in place of the default functionality. For example, a custom toNumber() could make use of locale-specific date formats to attempt to convert a string to a date value, or could allow currency values e.g., "$123.45" to be converted to number.

+
+
+
+

10.4. Additional Functions

+
+

A host may provide its own set of functions to augment the base set provided by json-formula.

+
+
+
+

10.5. Hidden Properties

+
+

A host system may construct its source JSON data with complex properties that have nested structure that can be found through explicit navigation, but will not be found through normal tree searching. Here is an example of how this can be configured in JavaScript:

+
+
+
+
function createField(id, value) {
+  class Field {
+    valueOf() { return value; }
+
+    toString() { return value.toString(); }
+
+    toJSON() { return value; }
+  }
+  const f = new Field();
+  Object.defineProperty(f, '$id', { get: () -> id });
+  Object.defineProperty(f, '$value', { get: () -> value });
+
+  return f;
+}
+
+const json = {
+  "street": createField("abc123", "Maple Street"),
+  "city": createField("def456", "New York")
+}
+
+Given this configuration, these search results are possible:
+
+street -> "Maple Street"
+street.$value -> "Maple Street"
+street.$id -> "abc123"
+type(street) -> "string"
+keys(street) -> []
+
+
+
+
+

10.6. Tracking

+
+

A host system may want to track which properties are accessed during the evaluation of an expression. This can be done by providing a track function on the object being evaluated. The track function will be called with the object being evaluated and the key being accessed. Here is an example of how this can be configured in JavaScript:

+
+
+
+
properties[Symbol.for('track')] = (obj, key) => trackDependent(obj, key);
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/doc/output/json-formula-specification-2.0.0.pdf b/doc/output/json-formula-specification-2.0.0.pdf new file mode 100644 index 00000000..6bc564e9 Binary files /dev/null and b/doc/output/json-formula-specification-2.0.0.pdf differ diff --git a/doc/spec.adoc b/doc/spec.adoc index 7186b062..0c8f152a 100644 --- a/doc/spec.adoc +++ b/doc/spec.adoc @@ -1,6 +1,6 @@ = json-formula Specification PDF Association Forms Technical Working Group -0.2.0, {docdate}: +2.0.0, {docdate}: :toc: macro :outlinelevels: 3 :appendix-caption: Appendix @@ -26,13 +26,13 @@ The grammar borrows from * https://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part2.html[OpenFormula] for spreadsheet operators and function * https://jmespath.org/[JMESPath] for JSON query semantics -The intended audience are both end-users of json-formula as well as implementors; the contents are then both a user guide and a specification. +The intended audience are both end-users of json-formula as well as implementers; the contents are then both a user guide and a specification. // start numbering the sections from here... :sectnums: == Notation -In the specification, examples are shown through the use of a `search` function. The syntax for this function is: +In the specification, examples are shown through the use of a `search` function called `eval`. The syntax for this function is: [source%unbreakable] ---- @@ -59,8 +59,7 @@ json-formula supports all the JSON types: * object: an unordered collection of key value pairs * `null` -There is an additional type that is not a JSON type that's used in -json-formula functions: +There is an additional type that is not a JSON type that's used in json-formula functions: * expression: A string prefixed with an ampersand (`&`) character @@ -1250,8 +1249,7 @@ With nested arrays: Functions are evaluated in applicative order: - Each argument must be an expression -- Each argument expression must be evaluated before evaluating the -function +- Each argument expression must be evaluated before evaluating the function - Each argument expression result must be coerced to the expected type - If coercion is not possible, a `TypeError` error is raised - The function is then called with the evaluated function arguments. diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index bd8ee1dd..02a7652a 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -1,12 +1,12 @@ { "name": "@adobe/json-formula", - "version": "1.1.1", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@adobe/json-formula", - "version": "1.1.1", + "version": "2.0.0", "license": "Apache-2.0", "devDependencies": { "@babel/core": "^7.23.6", @@ -27,7 +27,7 @@ "html-webpack-plugin": "^5.6.0", "jest": "^29.3.1", "jest-cli": "^29.7.0", - "jsdoc": "^4.0.2", + "jsdoc": "^4.0.5", "jsdoc-to-markdown": "^8.0.0", "webpack": "^5.89.0", "webpack-cli": "^5.0.0", @@ -3225,26 +3225,29 @@ "dev": true }, "node_modules/@types/linkify-it": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.5.tgz", - "integrity": "sha512-yg6E+u0/+Zjva+buc3EIb+29XEg4wltq7cSmd4Uc2EE/1nUVmxyzpX6gUXD0V8jIrG0r7YeOGVIbYRkxeooCtw==", - "dev": true + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", + "dev": true, + "license": "MIT" }, "node_modules/@types/markdown-it": { - "version": "12.2.3", - "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-12.2.3.tgz", - "integrity": "sha512-GKMHFfv3458yYy+v/N8gjufHO6MSZKCOXpZc5GXIWWy8uldwfmPn98vp81gZ5f9SVw8YYBctgfJ22a2d7AOMeQ==", + "version": "14.1.2", + "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", + "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", "dev": true, + "license": "MIT", "dependencies": { - "@types/linkify-it": "*", - "@types/mdurl": "*" + "@types/linkify-it": "^5", + "@types/mdurl": "^2" } }, "node_modules/@types/mdurl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-1.0.5.tgz", - "integrity": "sha512-6L6VymKTzYSrEf4Nev4Xa1LCHKrlTlYCBMTlQKFuddo1CvQcE52I0mwfOJayueUC7MJuXOeHTcIU683lzd0cUA==", - "dev": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", + "dev": true, + "license": "MIT" }, "node_modules/@types/mime": { "version": "1.3.5", @@ -9868,21 +9871,22 @@ } }, "node_modules/jsdoc": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-4.0.2.tgz", - "integrity": "sha512-e8cIg2z62InH7azBBi3EsSEqrKx+nUtAS5bBcYTSpZFA+vhNPyhv8PTFZ0WsjOPDj04/dOLlm08EDcQJDqaGQg==", + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/jsdoc/-/jsdoc-4.0.5.tgz", + "integrity": "sha512-P4C6MWP9yIlMiK8nwoZvxN84vb6MsnXcHuy7XzVOvQoCizWX5JFCBsWIIWKXBltpoRZXddUOVQmCTOZt9yDj9g==", "dev": true, + "license": "Apache-2.0", "dependencies": { "@babel/parser": "^7.20.15", "@jsdoc/salty": "^0.2.1", - "@types/markdown-it": "^12.2.3", + "@types/markdown-it": "^14.1.1", "bluebird": "^3.7.2", "catharsis": "^0.9.0", "escape-string-regexp": "^2.0.0", "js2xmlparser": "^4.0.2", "klaw": "^3.0.0", - "markdown-it": "^12.3.2", - "markdown-it-anchor": "^8.4.1", + "markdown-it": "^14.1.0", + "markdown-it-anchor": "^8.6.7", "marked": "^4.0.10", "mkdirp": "^1.0.4", "requizzle": "^0.2.3", @@ -10086,12 +10090,13 @@ "dev": true }, "node_modules/linkify-it": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.3.tgz", - "integrity": "sha512-ynTsyrFSdE5oZ/O9GEf00kPngmOfVwazR5GKDq6EYfhlpFug3J2zybX56a2PRRpc9P+FuSoGNAwjlbDs9jJBPQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", + "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", "dev": true, + "license": "MIT", "dependencies": { - "uc.micro": "^1.0.1" + "uc.micro": "^2.0.0" } }, "node_modules/loader-runner": { @@ -10210,19 +10215,21 @@ } }, "node_modules/markdown-it": { - "version": "12.3.2", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.3.2.tgz", - "integrity": "sha512-TchMembfxfNVpHkbtriWltGWc+m3xszaRD0CZup7GFFhzIgQqxIfn3eGj1yZpfuflzPvfkt611B2Q/Bsk1YnGg==", + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", + "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^2.0.1", - "entities": "~2.1.0", - "linkify-it": "^3.0.1", - "mdurl": "^1.0.1", - "uc.micro": "^1.0.5" + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" }, "bin": { - "markdown-it": "bin/markdown-it.js" + "markdown-it": "bin/markdown-it.mjs" } }, "node_modules/markdown-it-anchor": { @@ -10235,6 +10242,19 @@ "markdown-it": "*" } }, + "node_modules/markdown-it/node_modules/entities": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/marked": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz", @@ -10248,10 +10268,11 @@ } }, "node_modules/mdurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-1.0.1.tgz", - "integrity": "sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==", - "dev": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", + "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", + "dev": true, + "license": "MIT" }, "node_modules/media-typer": { "version": "0.3.0", @@ -11114,6 +11135,16 @@ "node": ">=6" } }, + "node_modules/punycode.js": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", + "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/pure-rand": { "version": "6.0.4", "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz", @@ -12783,10 +12814,11 @@ "dev": true }, "node_modules/uc.micro": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.6.tgz", - "integrity": "sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==", - "dev": true + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", + "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", + "dev": true, + "license": "MIT" }, "node_modules/uglify-js": { "version": "3.17.4", diff --git a/package.json b/package.json index 01bd4dd7..6cf50592 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/json-formula", - "version": "2.0.0-beta.1", + "version": "2.0.0", "description": "json-formula Grammar and implementation", "main": "src/json-formula.js", "type": "module", @@ -45,7 +45,7 @@ "html-webpack-plugin": "^5.6.0", "jest": "^29.3.1", "jest-cli": "^29.7.0", - "jsdoc": "^4.0.2", + "jsdoc": "^4.0.5", "jsdoc-to-markdown": "^8.0.0", "webpack": "^5.89.0", "webpack-cli": "^5.0.0", diff --git a/src/json-formula.js b/src/json-formula.js index 6dc45615..1cb584df 100644 --- a/src/json-formula.js +++ b/src/json-formula.js @@ -11,7 +11,68 @@ governing permissions and limitations under the License. */ import Formula from './interpreter.js'; +// data type constants re-exported from dataTypes.js +// which represent the various data types supported by json-formula function params export { dataTypes } from './dataTypes.js'; +/** +@enum {Number} + // Type constants used to define functions. + const dataTypes = { + TYPE_NUMBER: 0, + TYPE_ANY: 1, + TYPE_STRING: 2, + TYPE_ARRAY: 3, + TYPE_OBJECT: 4, + TYPE_BOOLEAN: 5, + TYPE_EXPREF: 6, + TYPE_NULL: 7, + TYPE_ARRAY_NUMBER: 8, + TYPE_ARRAY_STRING: 9, + TYPE_ARRAY_ARRAY: 10, + TYPE_EMPTY_ARRAY: 11, + }; + */ + +/** + * @typedef {object} CustomFunctionDefinition + * @property {Function} _func - The function implementation + * @property {array} [_signature] - Function signature metadata + * @example + // simple custom functions definition + const customFunctions = { + true_fn: { + _func: () => true, + _signature: [], + }, + false_fn: { + _func: () => false, + _signature: [], + }, + }; + @example + // custom function with a signature for its parameters + const customFunctions = { + padEnd: { + _func: args => { + const src = args[0]; + const length = args[1]; + const padChar = args[2]; + if (Array.isArray(src)) return src.map(s => s.padEnd(length, padChar)); + return src.padEnd(length, padChar); + }, + _signature: [ + { types: [TYPE_STRING, TYPE_ARRAY_STRING] }, + { types: [TYPE_NUMBER] }, + { types: [TYPE_STRING] }, + ], + } + } + // May also register functions is via the `register()` or `registerWithParams()` methods. e.g. + + const regFormula = `${register("${fn_name}", &${code})`; + // Run the registration formula after which, the registered function may be called + this.search(regFormula, {}); +*/ /** * Class represents an instance of a JsonFormula Expression that can be executed later on with @@ -23,7 +84,6 @@ class JsonFormula { * @param {object} [customFunctions={}] custom functions needed by a hosting application. * @param {function} [stringToNumber='null'] A function that converts string values to numbers. * Can be used to convert currencies/dates to numbers - * @param {string} [language=en-US] * @param {array} [debug=[]] will be populated with any errors/warnings */ constructor( @@ -37,11 +97,32 @@ class JsonFormula { this.formula = new Formula(debug, customFunctions, stringToNumber); } + /** + * @typedef {object} globals + * An object where each key **MUST** begin with a `$` character, representing global variables + * that can be accessed inside a json-formula expression. + * The value of each key can be of any data type supported by json. + * + * @example + * const globals = { + * $num: 42, + * $arr: [1, 2, 3], + * $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + * }; + * jsonFormula({}, globals, '$arr * $num') // returns [42, 84, 126] + */ + /** * Evaluates the JsonFormula on a particular json payload and return the result + * @param {string} expression the json-formula expression to evaluate * @param {object|array} json the json data on which the expression needs to be evaluated * @param {object} [globals={}] global objects that can be accessed via custom functions. + * @param {string} [language=en-US] BCP-47 language tag * @returns {*} the result of the expression being evaluated + * @example + * const jf = new JsonFormula(); + * const result = jf.search('toDate(d) | day(@) & "/" & month(@)', {d: "2025-11-12"}); + * // returns "12/11" */ search(expression, json, globals = {}, language = 'en-US') { const ast = this.compile(expression, Object.keys(globals)); @@ -49,11 +130,22 @@ class JsonFormula { } /** - * Execute a previously compiled expression against a json object and return the result + * Execute a previously compiled expression against a json object and return the result. + * Use this method for better performance when you will evaluate the same expression + * multiple times with different data. * @param {object} ast The abstract syntax tree returned from compile() * @param {object|array} json the json data on which the expression needs to be evaluated + * @param {string} [language=en-US] BCP-47 language tag * @param globals {*} set of objects available in global scope * @returns {*} the result of the expression being evaluated + * @example + * const globals = { + * $days: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + * }; + * const jf = new JsonFormula(); + * const ast = jf.compile('value($days, num)', ['$days']); // compile the expression once + * const result1 = jf.run(ast, {num: 2}, 'en-US', globals); // returns "Wed" + * const result2 = jf.run(ast, {num: 3}, 'en-US', globals); // returns "Thu" */ run(ast, json, language, globals) { return this.formula.search( @@ -67,9 +159,8 @@ class JsonFormula { /** * Creates a compiled expression that can be executed later on with some data. * @param {string} expression the expression to evaluate - * @param {string[]} [allowedGlobalNames=[]] A list of names of the global variables + * @param {string[]} [allowedGlobalNames=[]] An array of names of the global variables * being used in the expression. - * @param {array} [debug=[]] will be populated with any errors/warnings */ compile(expression, allowedGlobalNames = []) { this.debug.length = 0; @@ -80,15 +171,16 @@ class JsonFormula { /** * Compile and execute a json-formula expression. * If executing the same expression multiple times, it is more efficient to create a - * class instance of {JsonFormula} and call the search method multiple times. + * class instance of JsonFormula and call the search() method or the compile()/run() methods + * multiple times. * @param {object|array} json the json data on which the expression needs to be evaluated * @param {object} globals global objects that can be accessed via custom functions. * @param {string} expression the expression to evaluate * @param {object} [customFunctions={}] custom functions needed by a hosting application. * @param {function} [stringToNumber='null'] A function that converts string values to numbers. * Can be used to convert currencies/dates to numbers -* @param {string} [language=en-US] * @param {array} [debug=[]] will be populated with any errors/warnings +* @param {string} [language=en-US] BCP-47 language tag * @returns {*} the result of the expression being evaluated */