fig-tree-evaluator 2.23.2 → 3.0.0-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +214 -148
- package/build/chunks/shared.js +1 -0
- package/build/editor-hints/index.d.ts +35 -0
- package/build/editor-hints/index.js +1 -0
- package/build/format/index.d.ts +31 -0
- package/build/format/index.js +1 -0
- package/build/index.d.ts +741 -240
- package/build/index.js +1 -0
- package/build/migrate/index.d.ts +55 -0
- package/build/migrate/index.js +1 -0
- package/package.json +97 -50
- package/CHANGELOG.md +0 -134
- package/build/index.cjs.js +0 -1
- package/build/index.esm.js +0 -1
package/package.json
CHANGED
|
@@ -1,72 +1,119 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fig-tree-evaluator",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0-preview.1",
|
|
4
4
|
"description": "Module to evaluate JSON-structured expression trees",
|
|
5
|
-
"
|
|
6
|
-
"
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./build/index.js",
|
|
7
|
+
"types": "./build/index.d.ts",
|
|
7
8
|
"sideEffects": false,
|
|
8
|
-
"types": "build/index.d.ts",
|
|
9
9
|
"exports": {
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./build/index.d.ts",
|
|
12
|
-
"
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
"default": "./build/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./migrate": {
|
|
15
|
+
"types": "./build/migrate/index.d.ts",
|
|
16
|
+
"default": "./build/migrate/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./editor-hints": {
|
|
19
|
+
"types": "./build/editor-hints/index.d.ts",
|
|
20
|
+
"default": "./build/editor-hints/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./format": {
|
|
23
|
+
"types": "./build/format/index.d.ts",
|
|
24
|
+
"default": "./build/format/index.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"typesVersions": {
|
|
28
|
+
"*": {
|
|
29
|
+
"migrate": [
|
|
30
|
+
"./build/migrate/index.d.ts"
|
|
31
|
+
],
|
|
32
|
+
"editor-hints": [
|
|
33
|
+
"./build/editor-hints/index.d.ts"
|
|
34
|
+
],
|
|
35
|
+
"format": [
|
|
36
|
+
"./build/format/index.d.ts"
|
|
37
|
+
]
|
|
15
38
|
}
|
|
16
39
|
},
|
|
17
40
|
"files": [
|
|
18
41
|
"build"
|
|
19
42
|
],
|
|
20
|
-
"
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22.12"
|
|
45
|
+
},
|
|
46
|
+
"packageManager": "pnpm@10.8.1",
|
|
47
|
+
"pnpm": {
|
|
48
|
+
"onlyBuiltDependencies": [
|
|
49
|
+
"esbuild",
|
|
50
|
+
"sqlite3",
|
|
51
|
+
"unrs-resolver"
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/CarlosNZ/fig-tree-evaluator.git"
|
|
57
|
+
},
|
|
21
58
|
"author": "Carl Smith <5456533+CarlosNZ@users.noreply.github.com>",
|
|
22
59
|
"license": "MIT",
|
|
23
|
-
"devDependencies": {
|
|
24
|
-
"@rollup/plugin-typescript": "^11.1.5",
|
|
25
|
-
"@testing-library/jest-dom": "^6.1.3",
|
|
26
|
-
"@testing-library/react": "^14.0.0",
|
|
27
|
-
"@types/jest": "^29.5.5",
|
|
28
|
-
"@types/node": "^20.8.2",
|
|
29
|
-
"@types/node-fetch": "^2.6.11",
|
|
30
|
-
"@types/pg": "^8.10.3",
|
|
31
|
-
"@typescript-eslint/eslint-plugin": "^6.11.0",
|
|
32
|
-
"@typescript-eslint/parser": "^6.11.0",
|
|
33
|
-
"axios": "^1.7.2",
|
|
34
|
-
"dotenv": "^16.0.1",
|
|
35
|
-
"eslint": "^8.53.0",
|
|
36
|
-
"fig-tree-evaluator": "^2.23.1",
|
|
37
|
-
"jest": "^29.7.0",
|
|
38
|
-
"node-fetch": "2.7.0",
|
|
39
|
-
"pg": "^8.11.3",
|
|
40
|
-
"prettier": "^3.0.3",
|
|
41
|
-
"rimraf": "^5.0.5",
|
|
42
|
-
"rollup": "^4.53.3",
|
|
43
|
-
"rollup-plugin-bundle-size": "^1.0.3",
|
|
44
|
-
"rollup-plugin-dts": "^6.0.2",
|
|
45
|
-
"rollup-plugin-sizes": "^1.0.5",
|
|
46
|
-
"rollup-plugin-terser": "^7.0.2",
|
|
47
|
-
"sqlite": "^5.1.1",
|
|
48
|
-
"sqlite3": "^5.1.7",
|
|
49
|
-
"ts-jest": "^29.1.1",
|
|
50
|
-
"ts-node": "^10.8.0",
|
|
51
|
-
"tslib": "^2.6.2",
|
|
52
|
-
"typescript": "^5.2.0"
|
|
53
|
-
},
|
|
54
60
|
"scripts": {
|
|
55
|
-
"setup": "yarn install && cd demo && yarn install",
|
|
56
61
|
"test": "jest",
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
+
"test:v2": "jest --config jest.v2.config.js",
|
|
63
|
+
"test:live": "jest --config jest.live.config.js",
|
|
64
|
+
"generate:operators": "tsx codegen/buildOperatorReference.ts",
|
|
65
|
+
"artifacts:fetch": "node codegen/fetchArtifacts.mjs",
|
|
66
|
+
"generateMassiveQuery": "tsx codegen/generateMassiveQuery.ts",
|
|
67
|
+
"getVersion": "tsx codegen/getVersion.ts",
|
|
68
|
+
"checkDefinitions": "tsx codegen/checkDefinitions.ts",
|
|
69
|
+
"extractV2Table": "tsx codegen/extractV2Table.ts",
|
|
70
|
+
"differential": "tsx differential/index.ts",
|
|
71
|
+
"lint": "eslint .",
|
|
72
|
+
"format": "prettier --write .",
|
|
73
|
+
"format:check": "prettier --check .",
|
|
74
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json && tsc -p tsconfig.globals.json",
|
|
75
|
+
"build": "pnpm getVersion && pnpm checkDefinitions && rimraf ./build && rollup -c && rimraf ./build/dts",
|
|
76
|
+
"size": "node codegen/bundleSize.mjs",
|
|
77
|
+
"check:package": "node codegen/checkPackage.mjs",
|
|
62
78
|
"compile": "rimraf ./build && tsc",
|
|
63
|
-
"
|
|
64
|
-
"
|
|
65
|
-
"
|
|
79
|
+
"dev": "node codegen/dev.mjs",
|
|
80
|
+
"bench": "node codegen/bench.mjs",
|
|
81
|
+
"bench:browser": "node codegen/benchBrowser.mjs",
|
|
82
|
+
"bench:serve": "node codegen/benchServe.mjs",
|
|
83
|
+
"release": "node codegen/release.mjs",
|
|
84
|
+
"prepublishOnly": "pnpm build"
|
|
66
85
|
},
|
|
67
|
-
"
|
|
86
|
+
"devDependencies": {
|
|
87
|
+
"@eslint/js": "^9.0.0",
|
|
88
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
89
|
+
"@rollup/plugin-typescript": "^12.3.0",
|
|
90
|
+
"@types/jest": "^30.0.0",
|
|
91
|
+
"@types/node": "^22.0.0",
|
|
92
|
+
"@types/node-fetch": "^2.6.13",
|
|
93
|
+
"@types/pg": "^8.20.0",
|
|
94
|
+
"axios": "^1.18.1",
|
|
68
95
|
"dequal": "^2.0.3",
|
|
69
|
-
"
|
|
96
|
+
"dotenv": "^16.6.1",
|
|
97
|
+
"esbuild": "0.28.1",
|
|
98
|
+
"eslint": "^9.0.0",
|
|
99
|
+
"eslint-plugin-comment-length": "^2.3.1",
|
|
100
|
+
"fig-tree-evaluator-v2": "npm:fig-tree-evaluator@2.23.2",
|
|
101
|
+
"globals": "^17.12.0",
|
|
102
|
+
"jest": "^30.4.2",
|
|
103
|
+
"node-fetch": "2.7.0",
|
|
104
|
+
"object-property-extractor": "^1.0.14",
|
|
105
|
+
"pg": "^8.22.0",
|
|
106
|
+
"prettier": "^3.9.4",
|
|
107
|
+
"rimraf": "^6.1.3",
|
|
108
|
+
"rollup": "^4.62.2",
|
|
109
|
+
"rollup-plugin-dts": "^6.4.1",
|
|
110
|
+
"sqlite": "^5.1.1",
|
|
111
|
+
"sqlite3": "^5.1.7",
|
|
112
|
+
"ts-jest": "^29.4.11",
|
|
113
|
+
"tslib": "^2.8.1",
|
|
114
|
+
"tsx": "^4.19.0",
|
|
115
|
+
"typescript": "^5.9.3",
|
|
116
|
+
"typescript-eslint": "^8.63.0"
|
|
70
117
|
},
|
|
71
118
|
"bugs": {
|
|
72
119
|
"url": "https://github.com/CarlosNZ/fig-tree-evaluator/issues"
|
package/CHANGELOG.md
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
The format below (from v2.21.4 onwards) is loosely based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
4
|
-
|
|
5
|
-
## [2.23.2]
|
|
6
|
-
|
|
7
|
-
### Changed
|
|
8
|
-
|
|
9
|
-
- `stringSubstitution`: a substitution value of `null` or `undefined` is rendered as an empty string instead of the text `"null"`/`"undefined"`. This matches what a named parameter with no matching value in `substitutions` or the `data` object already resolved to, and applies to both positional (`%1`) and named (`{{name}}`) substitutions, regardless of `trimWhiteSpace`. `false` and `0` are unaffected -- they're still rendered as `"false"` and `"0"`. ([#138](https://github.com/CarlosNZ/fig-tree-evaluator/issues/138))
|
|
10
|
-
|
|
11
|
-
## [2.23.1]
|
|
12
|
-
|
|
13
|
-
### Fixed
|
|
14
|
-
|
|
15
|
-
- `stringSubstitution`: escaped substitution characters (`\%N` for positional, `\{{name}}` for named) are now un-escaped for every occurrence, not just the first. ([#142](https://github.com/CarlosNZ/fig-tree-evaluator/issues/142))
|
|
16
|
-
- `DIVIDE` operator: `output: 'decimal'` is now accepted (previously rejected by its own type-check, even though decimal division was the runtime fall-through behaviour). The `output` metadata `default` also now correctly reflects the actual runtime default (`'decimal'`). Minor typo fix in the `values` parameter description ("by the first" → "by the second"). ([#141](https://github.com/CarlosNZ/fig-tree-evaluator/issues/141))
|
|
17
|
-
- `inputDefault` in a custom `FunctionDefinition` now accepts primitive values (previously only object values were valid at the type level). Falsy primitives (`0`, `false`, `""`) are also preserved by `getCustomFunctions()` instead of being silently dropped from the exposed metadata.
|
|
18
|
-
- `notEqual` (`!=`, `ne`) with `nullEqualsUndefined: true` no longer always returns `false` when the first value is `null` or `undefined`. The check now correctly returns `true` when any value falls outside the null/undefined equivalence class ([#140](https://github.com/CarlosNZ/fig-tree-evaluator/issues/140)).
|
|
19
|
-
- `split` operator: the `delimiter` now interprets the whitespace escape sequences `\n`, `\t` and `\r` when written literally, so a delimiter typed as `\n` (backslash + `n`) splits on real line breaks. This is convenient when authoring the delimiter in an input field that can't hold a real control character. Genuine control characters and other delimiters (including a single backslash) are unaffected.
|
|
20
|
-
|
|
21
|
-
## [2.23.0] - 2026-06-30
|
|
22
|
-
|
|
23
|
-
### Added
|
|
24
|
-
|
|
25
|
-
- New `FigTreeEvaluator` instance method `isFigTreeExpression(expression)` — a registry-aware check for whether an expression is something *this* instance would actually evaluate. Unlike the structural stand-alone `isFigTreeExpression` export, it validates `$`-prefixed shorthand and keys against the instance's registered operators, fragments and custom functions, and follows its `evaluateFullObject` and `noShorthand` settings. Useful for editor UIs deciding whether to treat a value as an evaluable expression rather than plain data.
|
|
26
|
-
|
|
27
|
-
## [2.22.1] - 2026-06-30
|
|
28
|
-
|
|
29
|
-
### Fixed
|
|
30
|
-
|
|
31
|
-
- `convertToShorthand` now handles operator nodes in the positional `children` array form (previously emitted verbatim).
|
|
32
|
-
- `convertToShorthand` of `buildObject` now uses the array form regardless of whether the input uses the `properties` or `values` parameter name.
|
|
33
|
-
|
|
34
|
-
## [2.22.0] - 2026-06-29
|
|
35
|
-
|
|
36
|
-
### Changed
|
|
37
|
-
|
|
38
|
-
- The `parseChildren` operator method (`ParseChildrenMethod`) is now synchronous — its return type narrows from `OperatorNode | Promise<OperatorNode>` to `OperatorNode`. The async option had been vestigial since v2.20.6, when `parseChildren` stopped evaluating children during parsing.
|
|
39
|
-
- As a consequence, the conversion helpers `convertFromShorthand` and `convertV1ToV2` are now synchronous and no longer return a `Promise`. Existing `await`-ed calls continue to work unchanged.
|
|
40
|
-
|
|
41
|
-
## [2.21.6] - 2026-06-28
|
|
42
|
-
|
|
43
|
-
### Fixed
|
|
44
|
-
|
|
45
|
-
- Shorthand conversion (`convertToShorthand`) of `GET`/`POST`/`graphQL` nodes now uses the named-object form instead of the positional-array form. These operators have a custom `parseChildren` (field-name/value zipping) whose order doesn't match their parameter definitions, so the array form mis-mapped properties such as `returnProperty`.
|
|
46
|
-
|
|
47
|
-
## [2.21.5] - 2026-06-28
|
|
48
|
-
|
|
49
|
-
### Fixed
|
|
50
|
-
|
|
51
|
-
- Shorthand conversion (`convertToShorthand`) no longer drops non-parameter properties (e.g. `fallback`) when a node is converted to the positional-array form. Such nodes now use the named-object form so no information is lost.
|
|
52
|
-
|
|
53
|
-
## [2.21.4] - 2026-06-28
|
|
54
|
-
|
|
55
|
-
### Changed
|
|
56
|
-
|
|
57
|
-
- Compile bundle to ES2020 (from ES2015). Eliminates the `tslib` runtime helpers that were ~13% of the bundle, reducing it by ~7% gzipped. Minimum supported runtime is now ES2020 (Node 14+, evergreen browsers).
|
|
58
|
-
|
|
59
|
-
### Fixed
|
|
60
|
-
|
|
61
|
-
- Shorthand conversion (`convertToShorthand`) of `getData`/`objectProperties` nodes that include an `additionalData` parameter. Previously this produced a malformed, deeply-nested array instead of a named-property object.
|
|
62
|
-
|
|
63
|
-
## Earlier versions
|
|
64
|
-
|
|
65
|
-
*Trivial upgrades (e.g. documentation, small re-factors, types, etc.) not included*
|
|
66
|
-
|
|
67
|
-
- **v2.21.0**: Use default parameter values for Fragments if not provided in expression
|
|
68
|
-
- **v2.20.6**: Fix certain `parseChildren` methods to not evaluate while parsing
|
|
69
|
-
- **v2.20.0**:
|
|
70
|
-
- Add helper scripts to convert V1 to V2 expressions, and to and from Shorthand syntax -- used in [FigTree Editor](https://github.com/CarlosNZ/fig-tree-editor-react) tool.
|
|
71
|
-
- Small tweaks to `buildObject` and `match` operators to make them a little more consistent in their behaviour.
|
|
72
|
-
- **v2.19.0**: *Remove* "string" shorthand syntax (technically a breaking change, but I doubt anyone is affected by this) #124
|
|
73
|
-
- **v2.18.0**: Prevent HTTP clients from being bundled with main package
|
|
74
|
-
- **v2.17.0**: Allow Custom Functions to be expressed as Custom Operators
|
|
75
|
-
- **v2.16.10**: Fix for when aliases reference other aliases at the same level
|
|
76
|
-
- **v2.16.8**: Don't deep merge fragments, data, headers and functions when using `.updateOptions()`
|
|
77
|
-
- **v2.16.5**: Make sure all parameters that are objects get pre-evaluated, even when
|
|
78
|
-
`evaluateFullObject` is off.
|
|
79
|
-
- **v2.16.0**: Standardise error response (see [Error handling](#error-handling))
|
|
80
|
-
- **v2.15.0**:
|
|
81
|
-
- Remove `axios` package dependency and create HTTP client abstraction (with built-in wrappers for `axios` and `fetch`). *Results in significantly smaller bundle size.*
|
|
82
|
-
- Generalise `PG_SQL` operator to a client-agnostic `SQL` operator (with built-in abstractions for `node-postgres` and `SQLite`)
|
|
83
|
-
- ***Breaking changes*** as a result of the above: SQL client and HTTP client must be specified differently. See relevant operator details.
|
|
84
|
-
- Changes to `SQL` parameters to reflect the aforementioned agnosticism.
|
|
85
|
-
- **v2.14.0**: Improvements to `stringSubstitution` operator:
|
|
86
|
-
- Can accept nested property references (e.g. `{{user.name}}`)
|
|
87
|
-
- Will also search for replacements from `data` object
|
|
88
|
-
- **v2.13.4**: Bug fix for `objectProperties` operator when array index larger than `9` is used, and for sequential array indexes (e.g. `prop[1][2]`)
|
|
89
|
-
- **v2.13.0**: Add default values to operator properties, export more types and helper methods
|
|
90
|
-
- **v2.12.0**: Add `caseInsensitive` option to equality/non-equality operators
|
|
91
|
-
- **v2.11.5**: Upgrade dependencies
|
|
92
|
-
- **v2.11.4**: Bundle target ES6
|
|
93
|
-
- **v2.11.0**: Improved package bundling (bundle size ~50%), with CommonJS and ESM outputs. Note: small **breaking change**: "FigTreeEvaluator" is no longer a default export, so need to import with: `import { FigTreeEvaluator } from 'fig-tree-evaluator'`
|
|
94
|
-
- **v2.10.0**: Extended stringSubstitution functionality to included named
|
|
95
|
-
property substitution, trim whitespace option, and pluralisation (#97)
|
|
96
|
-
- **v2.9.0**: Added ability to invalidate cache by time (#94)
|
|
97
|
-
- **v2.8.6**: Small bug fix where `options` object would be mutated instead of replaced
|
|
98
|
-
- **v2.8.5**: Small bug fix in [COUNT](#count) operator
|
|
99
|
-
- **v2.8.4**: Refactor types, better compliance with [ESLint](https://eslint.org/) rules, add more tests
|
|
100
|
-
- **v2.8.0**:
|
|
101
|
-
- **[Shorthand syntax](#shorthand-syntax)** (#80)
|
|
102
|
-
- **Methods to retrieve [metadata](#metadata)** about operators, fragments and
|
|
103
|
-
functions (#82)
|
|
104
|
-
- **v2.7.0**: **Add `excludeOperators` option** to allow certain operators to be
|
|
105
|
-
prohibited (e.g. database lookups) (#54)
|
|
106
|
-
- **v2.6.0**: Resolve alias nodes that are not part of an Operator node when `evaluateFullObject` is enabled (#78)
|
|
107
|
-
- **v2.5.0**:
|
|
108
|
-
- Bug fixes for edge cases (mainly related to backwards compatibility)
|
|
109
|
-
- More backwards compatibility for very old (pre-v1) syntax (undocumented)
|
|
110
|
-
- **v2.4.1**: Small bug fix for Fragments edge case
|
|
111
|
-
- **v2.4.0**: **Implement [Fragments](#fragments)** (#74)
|
|
112
|
-
- **v2.3.2**: Bug fix: alias nodes not working with `evaluateFullObject` (#72)
|
|
113
|
-
- **v2.3.0**: **Implement [caching/memoization](#caching-memoization)** (#68)
|
|
114
|
-
- **v2.2.3**: Change option `objects` name to `data` (but keep backward compatibility) (#66)
|
|
115
|
-
- **v2.2.2**: **Option to evaluate whole object** if operator nodes are deep within it (#64)
|
|
116
|
-
- **v2.2.1**: More efficient branch evaluation for condition/match operators (#63)
|
|
117
|
-
- **v2.2.0**:
|
|
118
|
-
- **New "[Match](#match)" operator** (#61)
|
|
119
|
-
- Fix for regex incompatibility with Safari (#60)
|
|
120
|
-
- **v2.1.4**: Upgrade dependencies
|
|
121
|
-
- **v2.1.0**: **[Alias nodes](#alias-nodes)** (#57)
|
|
122
|
-
- **v2.0.4**: Backwards compatibility for customFunctions (#53)
|
|
123
|
-
- **v2.0.1**: **Add deep equality comparison** for objects/arrays in `=`/`!=` operators
|
|
124
|
-
- **v2.0.0**: Re-write as stand-alone package. Major improvements include:
|
|
125
|
-
- more [operators](#operator-reference)
|
|
126
|
-
- operator (and property) [aliases](#operator--property-aliases)
|
|
127
|
-
- more appropriately-named properties associated with each operator (as
|
|
128
|
-
opposed to a single `children` array)
|
|
129
|
-
- class-based Evaluator instances
|
|
130
|
-
- runtime type-checking
|
|
131
|
-
- better error handling and error reporting
|
|
132
|
-
- more flexible output conversion
|
|
133
|
-
- more well-organised codebase
|
|
134
|
-
- **v1.x.x**: created specifically for [Conforma](https://github.com/openmsupply/conforma-server/wiki/Query-Syntax) application manager by [mSupplyFoundation](https://github.com/openmsupply). v2 is a complete re-write with numerous improvements, but should be 99% backwards compatible.
|
package/build/index.cjs.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var e=require("object-property-extractor"),r=require("dequal/lite");const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},n=(e,r)=>r[s(e)],i=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),c=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,p=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},g=y,v=(e,r={},t,a=!0)=>a&&f(e)?b(e,r,t):e,b=(e,r,s)=>{if(t(e)||a(e))return e;const n=Object.entries(e),i=n.filter((([e])=>u(e))),o=n.filter((([e])=>!u(e)));return{...i.reduce(((e,[t,a])=>e={...e,...T(t,a,r,s)}),{}),...Object.fromEntries(o)}},T=(e,r,t,a)=>{const s=e.slice(1),i=n(s,g);return i?Array.isArray(r)?{operator:i,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:i,...r}:{operator:i,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class w extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),n=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===n?"":n}`}}const C=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:n=!1})=>{if(void 0!==e)return e;if(a instanceof w){if(!n)throw a;return a.prettyPrint}const i=new w("string"==typeof a?new Error(a):a,r,t,s);if(n)return i.prettyPrint;throw i},E=e=>f(e)&&"literal"in e,A=({value:e,name:r,expectedType:t})=>{if(E(t)){const{literal:a}=t;return!!a.includes(e)||O(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===A({value:e,name:r,expectedType:t})))||O(r,e,t.join("|"));return!!(0,q[t])(e)||O(r,e,t)},S=(...e)=>{const r=[];return e.forEach((e=>{const t=A(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},q={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},O=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${x(r)}) is not of type: ${t}`:`- ${x(r)} is not of type: ${t}`,x=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},N=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},j=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(E(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const n=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:n}})),P=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},L=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=S(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},k=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,I=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>k(e))):t?null===s?null:k(s):s},U=e=>/^https?:\/\/.+/.test(e),R=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,n=r.slice(a,s);return""===n?e:e+(0===t?"":"/")+n}),""),D=async(e,r)=>{const{url:t,params:a={},data:s={},headers:n={},method:i="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[i]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...n},params:a,data:s})}catch(r){e.throwError(r)}},Q=async(e,r)=>{const{options:s,operators:i,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const p=Object.keys(r.options?.functions??{});u=v(u,r.options?.fragments,p,!s.noShorthand),Array.isArray(u)&&(u=await F(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:n,useCache:i,input:o,args:l,...u}=e,c={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(c.fallback=a),void 0!==s&&(c.outputType=s),void 0!==n&&(c.type=n),void 0!==i&&(c.useCache=i),void 0!==l&&(c.args=l),void 0!==o?c.input=o:Object.keys(u).length>0&&(c.input=u),c})(u,r)),s.evaluateFullObject&&!h&&!m)return c(await $(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:c(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[n,i]=await F([e.fragment,e.parameters],r),o=v(s?.fragments?.[n],s.fragments,p,!s.noShorthand);if(void 0===o)return C({fallback:await Q(y,r),error:`Fragment not defined: ${n}`,expression:u,returnErrorAsString:g});if(!t(o))return c(o,r);u={...e,...o,...i},delete u.fragment}const b=u,T=n(b.operator,o);if(!T)return C({fallback:await Q(y,r),error:`Invalid operator: ${b.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return C({fallback:await Q(y,r),error:`Excluded operator: ${b.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:E,parseChildren:A}=i[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,b);const q=await _(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await Q(S.children,O)),!Array.isArray(S.children))return C({fallback:await Q(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=A(S,O),delete S.children}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let x;try{x=await E(S,O)}catch(e){return C({fallback:await Q(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const N=S?.outputType??S?.type;if(!N)return x;const j=await Q(N,r);return j in d?d[j](x):C({fallback:await Q(y,r),operator:T,error:`- Invalid output type: ${j}`,expression:S,returnErrorAsString:g})},F=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>Q(e,r)))):await Q(e,r),_=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push(Q(e[t],r))));const s=await Promise.all(a),n=P(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(n[t[e]]=n?.[r]??r);return n},$=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=v(e,r.options?.fragments,t);if(!f(a))return e;const s=[],n=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(n.push(e,Q(t,r)),delete a[e])}));const i=await Promise.all(n);r.resolvedAliasNodes={...r.resolvedAliasNodes,...L(i)},Object.entries(a).forEach((([e,t])=>{s.push(e,Q(t,r))}));const o=await Promise.all(s);return c(L(o),r)},H=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],M=N(H),G={description:"Logical AND",aliases:["and","&","&&"],parameters:H},B=e=>{const r=e.children;return{...e,values:r}},z={propertyAliases:M,operatorData:G,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(j(G.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:B},W=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],J=N(W),V={description:"Logical OR",aliases:["or","|","||"],parameters:W},Y={propertyAliases:J,operatorData:V,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(j(V.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:B},X=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Z=N(X),K={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:X},ee={propertyAliases:Z,operatorData:K,evaluate:async(e,t)=>{const[a,s,n]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(j(K.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:n}));const i=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==n?n:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==i[0]&&void 0!==i[0]?i.every((e=>r.dequal(e,i[0]))):i.every((e=>null==e))},parseChildren:B},re=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],te=N(re),ae={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:re},se={propertyAliases:te,operatorData:ae,evaluate:async(e,t)=>{const[a,s,n]=await F([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(j(ae.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:n}));const i=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==n?n:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==i[0]&&void 0!==i[0]?i.some((e=>!r.dequal(e,i[0]))):i.some((e=>!(null==e)))},parseChildren:B},ne=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],ie=N(ne),oe={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:ne},le={propertyAliases:ie,operatorData:oe,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(j(oe.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:B},ue=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],ce=N(ue),pe={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:ue},de={propertyAliases:ce,operatorData:pe,evaluate:async(e,r)=>{const[t,a,s]=await F([e.values,e.from,e.subtract],r);r.typeChecker(j(pe.parameters,{values:t,from:a,subtract:s}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return n[0]-n[1]},parseChildren:B},he=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],me=N(he),fe={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:he},ye={propertyAliases:me,operatorData:fe,evaluate:async(e,r)=>{const t=await F(e.values,r);if(r.typeChecker(j(fe.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:B},ge=[{name:"values",description:"Array of values - 1st element will be divided by the second",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder","decimal"]},default:"decimal"}],ve=N(ge),be={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:ge},Te={propertyAliases:ve,operatorData:be,evaluate:async(e,r)=>{const[t,a,s,n]=await F([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(j(be.parameters,{values:t,dividend:a,divisor:s,output:n}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===i[1])throw new Error("Division by zero!");switch(n){case"quotient":return Math.floor(i[0]/i[1]);case"remainder":return i[0]%i[1];default:return i[0]/i[1]}},parseChildren:B},we=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ce=N(we),Ee={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:we},Ae={propertyAliases:Ce,operatorData:Ee,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(j(Ee.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,n]=t;return s===n&&!a||s>n},parseChildren:B},Se=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],qe=N(Se),Oe={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Se},xe={propertyAliases:qe,operatorData:Oe,evaluate:async(e,r)=>{const[t,a=!0]=await F([e.values,e.strict],r);if(r.typeChecker(j(Oe.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,n]=t;return s===n&&!a||s<n},parseChildren:B},Ne=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],je=N(Ne),Pe={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:Ne},Le={propertyAliases:je,operatorData:Pe,evaluate:async(e,r)=>{r.typeChecker(j(Pe.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await Q(e.condition,r)?await Q(e.valueIfTrue,r):await Q(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},ke=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Ie=N(ke),Ue={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:ke},Re={propertyAliases:Ie,operatorData:Ue,evaluate:async(e,r)=>{const[t,a]=await F([e.testString,e.pattern],r);r.typeChecker(j(Ue.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},De=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],Qe=N(De),Fe={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:De},_e={propertyAliases:Qe,operatorData:Fe,evaluate:async(r,t)=>{const[a,s={}]=await F([r.property,r.additionalData],t);t.typeChecker(j(Fe.parameters,{property:a,additionalData:s}));const n={...t.options?.data??{},...s};return e(n,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},$e=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],He=N($e),Me={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:$e},Ge={propertyAliases:He,operatorData:Me,evaluate:async(e,r)=>{const[t,a={},s=!0,n="%",i={}]=await F([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(j(Me.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:n,numberMapping:i})),Array.isArray(a)){const e="$"===n?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),i=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(i),l=P(Array.from(o),a.map((e=>Be(e,s))));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(new RegExp(`\\\\${"$"===e?"\\$":e}`,"g"),e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace(/\\\{\{/g,"{{"));continue}const t=await ze(e,a,i,r);l.push(Be(t,s))}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},Be=(e,r)=>{if(null==e)return"";const t=String(e);return r?t.trim():t},ze=async(r,t,a,s)=>{const n=s.options?.data??{},i=r.replace(/{{(.+)}}/,"$1"),o=await Q(e(t,i,e(n,i,"")),s);if("number"!=typeof o)return o;if(!(i in a))return o;const l=a[i];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[i]),c=u.find((e=>e.startsWith(">")));if(c){if(o>Number(c.slice(1)))return l?.[c]}const p=u.find((e=>e.startsWith("<")));if(p){if(o<Number(p.slice(1)))return l?.[p]}return l.other?l.other.replace("{}",String(o)):o},We=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],Je=N(We),Ve={description:"Count elements in an array",aliases:["count","length"],parameters:We},Ye={propertyAliases:Je,operatorData:Ve,evaluate:async(e,r)=>{const t=await F(e.values,r);return r.typeChecker(j(Ve.parameters,{values:t})),t.length},parseChildren:B},Xe=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],Ze=N(Xe),Ke={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Xe},er=" ",rr={propertyAliases:Ze,operatorData:Ke,evaluate:async(e,r)=>{const[t,a,s,n]=await F([e.value,e.delimiter??er,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(j(Ke.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:n}));let i=t.split((e=>e.replace(/\\n/g,"\n").replace(/\\t/g,"\t").replace(/\\r/g,"\r"))(a));return s&&(i=i.map((e=>e.trim()))),n&&""===i[i.length-1]&&i.pop(),i},parseChildren:e=>{const[r,t=er]=e.children;return{...e,value:r,delimiter:t}}},tr=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],ar=N(tr),sr={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:tr},nr={propertyAliases:ar,operatorData:sr,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,n,i,o,l]=await F([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(j(sr.parameters,{query:a,single:n,flatten:i,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,n)=>{const i=await t.query({query:e,values:r})||[];["array","string","number"].includes(n??"")&&(s=!0);const o=s?i.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):i;return a?o[0]:o}),a,s,n,i,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},ir=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],or=N(ir),lr={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:ir},ur={propertyAliases:or,operatorData:lr,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,n,i,o,l]=await F([e.query,e.url,await $(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:c}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...j(lr.parameters,{url:u,query:a,variables:n,returnNode:i,headers:o,useCache:l}),{name:"headers",value:c,expectedType:["object","null"]}]);const p=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=U(p)?p:R(d,p),m={query:a,variables:n},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const n=await D(t,{url:e,method:"post",data:r,headers:a});return I(n?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...c,...o},i);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,n=Array.isArray(a)?a:[a],i=s.slice(0,n.length),o=P(n,i),l={...e,query:r,url:t,variables:o};return s.length>n.length&&(l.returnNode=s.pop()),l}},cr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],pr=N(cr),dr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:cr},hr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],n=a.slice(0,s.length),i=P(s,n),o={...e,url:r,parameters:i};return a.length>s.length&&(o.returnProperty=a.pop()),o},mr=hr,fr={propertyAliases:pr,operatorData:dr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,n,i,o]=await F([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...j(dr.parameters,{url:l,returnProperty:n,headers:i,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...i},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const n=await D(t,{url:e,params:r,headers:a});return I(n,s)}),U(l)?l:R(c,l),s,p,n);return h},parseChildren:hr},yr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],gr=N(yr),vr={description:"HTTP POST Request",aliases:["POST","post"],parameters:yr},br={propertyAliases:gr,operatorData:vr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,n,i,o]=await F([e.url,await $(e.parameters,r),e.returnProperty,await $(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...j(vr.parameters,{url:l,headers:i,data:s,returnProperty:n,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...i},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const n=await D(t,{url:e,data:r,headers:a,method:"post"});return I(n,s)}),U(l)?l:R(c,l),s,p,n);return h},parseChildren:mr},Tr=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],wr=N(Tr),Cr={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:Tr},Er=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},Ar={propertyAliases:wr,operatorData:Cr,evaluate:async(e,r)=>{const t=await F(e.properties,r);r.typeChecker(j(Cr.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Er({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await F(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Er},Sr=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],qr={propertyAliases:N(Sr),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:Sr},evaluate:async(e,r)=>{const a=await Q(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?L(e.branches):e.branches??{},n=t(s)?await Q(s,r):s;if(!f(n))throw new Error("Branches don't evaluate to an object");if(a in n)return await Q(n[a],r);if("fallback"in n)return await Q(n.fallback,r);if(a in e)return await Q(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=L(t);return{...e,matchExpression:r,branches:a}}},Or=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],xr=N(Or),Nr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:Or},jr={propertyAliases:xr,operatorData:Nr,evaluate:async(r,t)=>{const[a,s=[],n,i]=await F([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(j(Nr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const c=i??t.options.useCache??!1,p=[...void 0===n?[]:[await $(n,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(c,(async(e,...r)=>await u(...r)),a,...p)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Pr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],Lr=N(Pr),kr={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Pr},Ir={propertyAliases:Lr,operatorData:kr,evaluate:async(e,r)=>(r.typeChecker(j(kr.parameters,{value:e.value})),await Q(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Ur=Object.freeze({__proto__:null,AND:z,BUILD_OBJECT:Ar,CONDITIONAL:Le,COUNT:Ye,CUSTOM_FUNCTIONS:jr,DIVIDE:Te,EQUAL:ee,GET:fr,GRAPHQL:ur,GREATER_THAN:Ae,LESS_THAN:xe,MATCH:qr,MULTIPLY:ye,NOT_EQUAL:se,OBJECT_PROPERTIES:_e,OR:Y,PASSTHRU:Ir,PLUS:le,POST:br,REGEX:Re,SPLIT:rr,SQL:nr,STRING_SUBSTITUTION:Ge,SUBTRACT:de});const Rr=(e,r,s)=>{const{fragments:n,functionNames:i,evaluateFullObject:o,useShorthand:l}=r;if(f(e)){const c=v(e,n,i,l);if(t(c)||a(c))return!0;if(!o)return!1;const p=new Set([...s,...Object.keys(e).filter(u)]);return Object.values(e).some((e=>Rr(e,r,p)))}return Array.isArray(e)?e.some((e=>Rr(e,r,s))):!("string"!=typeof e||!u(e))&&s.has(e)};class Dr{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Qr(t),s=a in this.store,n=Date.now(),i=s&&n-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=n,i&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:n},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Qr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),Fr=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?_r(window.fetch):void 0),_r=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,n=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",i=await e(t+n,{headers:a,method:"GET"}),o=await i.json();if(!i.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:i.status,error:i.statusText,url:i.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:n}=r,i=new URLSearchParams(s),o=i.size>0?`?${i.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(n),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class $r{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=S(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.23.2",this.options=Hr(e),this.operators=i(Ur,this.options?.excludeOperators??[],y),this.operatorAliases=y,this.cache=new Dr({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=Fr(e.graphQLConnection?.httpClient),this.httpClient=Fr(e.httpClient)}async evaluate(e,r={}){const t=p(this.options,Hr(r),!0);return r.httpClient&&(this.httpClient=Fr(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=Fr(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await Q(e,{options:t,operators:r.excludeOperators?i(Ur,r.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}isFigTreeExpression(e){return((e,r)=>Rr(e,r,new Set))(e,{fragments:this.options.fragments??{},functionNames:Object.keys(this.options.functions??{}),evaluateFullObject:this.options.evaluateFullObject??!1,useShorthand:!this.options.noShorthand})}getOptions(){return this.options}updateOptions(e){this.options=p(this.options,Hr(e),!1),this.options.excludeOperators&&(this.operators=i(Ur,this.options.excludeOperators,y))}getOperators(){const e=this.options.excludeOperators?i(Ur,this.options.excludeOperators,y):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(y))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:n,backgroundColor:i}=r;return e&&(a.description=e),void 0!==t&&(a.argsDefault=t),void 0!==s&&(a.inputDefault=s),n&&(a.textColor=n),i&&(a.backgroundColor=i),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?i(Ur,this.options.excludeOperators,y):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Hr=e=>"objects"in e?{...e,data:e.objects}:e,Mr=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Gr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(zr("additionalData",r,a.parameters))return Object.fromEntries(r);const e=zr("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:n,aliases:i,required:o}of a.parameters){const a=[n,...i],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${n}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Br=(e,r,t)=>{if(!e)return!1;const a=s(e),n=t.find((e=>e.name===a||e.aliases.includes(a)))?.parameters[0];if(!n)return!1;return!!("array"===n.type||Array.isArray(n.type)&&n.type.includes("array"))&&[n.name,...n.aliases].some((e=>e in r))},zr=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},Wr=(e,r)=>u(e)&&!r.has(e),Jr=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},Vr=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},Yr=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};Object.defineProperty(exports,"dequal",{enumerable:!0,get:function(){return r.dequal}}),exports.AxiosClient=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),exports.FetchClient=_r,exports.FigTreeError=w,exports.FigTreeEvaluator=$r,exports.SQLNodePostgres=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),exports.SQLite=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),exports.convertFromShorthand=(e,r)=>{const n=r.getOperators(),i=r.getFragments(),o=r.getCustomFunctions(),l=i.map((e=>e.name)),u=o.map((e=>e.name)),c=e=>{if(Array.isArray(e))return e.map((e=>c(e)));if(!f(e))return e;const i=Object.entries(e);if(0===i.length)return e;const o=i[0][0].replace("$",""),d=s(o),h=n.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=i[0][1];if(Array.isArray(s)){const t=s.map((e=>c(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...p(i)}}const n=c(s);if(!f(n)||!Yr(n,h)||t(n)||a(n)){return{operator:e,[h.parameters[0].name]:n}}return{operator:e,...n,...p(i)}}if(m){const r=c(e[i[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...p(i)}}if(y){const e=o,r=i[0][1],s=c(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...p(i)}}return Object.fromEntries(i.map((([e,r])=>[e,c(r)])))},p=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,c(r)])))};return c(e)},exports.convertToShorthand=(e,r,t=2)=>{const a=r.getOperators(),n=r.getFragments(),i=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=n.map((e=>e.name)),c=i.map((e=>e.name)),p=new Set([...l,...u,...c]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:n,fragment:i,...l}=e;if(!n&&!i)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));if(n&&Array.isArray(l.children)){const e=s(n),t=a.find((r=>r.name===e||r.aliases.includes(e)));if(t){const e=t.parseChildren({...l,operator:n},r.getConfig());return delete e.children,d(e)}}const u=c.includes(n);i&&l?.parameters&&(Object.entries(l.parameters).forEach((([e,r])=>{l[e]=r})),delete l.parameters);const h=u?n:Jr(n,a),m=`$${h??i}`,y=i?Vr(i,o):[],g=Object.keys(l).filter((e=>Wr(e,p)&&!y.includes(e))),v=Object.entries(l).filter((([e])=>!g.includes(e)&&!y.includes(e))).map((([e,r])=>[e,d(r)])),b=Object.fromEntries(g.map((e=>[e,d(l[e])]))),T=Object.fromEntries(y.map((e=>[e,d(l[e])])));switch(!0){case Object.keys(T).length>0:return{[m]:T,...b};case u:return 1!==v.length||"input"in l?{[m]:Object.fromEntries(v),...b}:{[m]:v[0][1]};case Br(n,l,a):return 1===v.length?{[m]:v[0][1]}:{[m]:Object.fromEntries(v),...b};case"match"===h:return{[m]:Object.fromEntries(v),...b};case v.length>t||!!i||v.some((([e])=>"useCache"===e||"outputType"===e))||v.some((e=>Array.isArray(e[1]))):return{[m]:Object.fromEntries(v),...b};case 1===v.length:return{[m]:v[0][1],...b};default:return{[m]:Gr(s(n),v,a),...b}}};return d(e)},exports.convertV1ToV2=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const n=Mr(e)?(()=>{const{operator:a}=e,n=s(a),i=t.find((e=>e.name===n||e.aliases.includes(n)));if(i){const t=i.parseChildren(e,r.getConfig());delete t.children;const a=i.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,i={};for(const[e,r]of Object.entries(n)){const t="type"===e?"outputType":e;Array.isArray(r)?i[t]=r.map((e=>a(e))):i[t]=a(r)}return i};return a(e)},exports.evaluateExpression=(e,r)=>new $r(r).evaluate(e),exports.isAliasString=u,exports.isFigTreeError=e=>e instanceof w,exports.isFigTreeExpression=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),exports.isFragmentNode=a,exports.isObject=f,exports.isOperatorNode=t,exports.isV1Node=Mr,exports.preProcessShorthand=v,exports.standardiseOperatorName=s,exports.truncateString=o;
|
package/build/index.esm.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import e from"object-property-extractor";import{dequal as r}from"dequal/lite";export{dequal}from"dequal/lite";const t=e=>e instanceof Object&&"operator"in e,a=e=>e instanceof Object&&"fragment"in e,s=e=>{const r=m(e);return r||e},n=(e,r)=>r[s(e)],i=(e,r,t)=>{const a={...e};return r.forEach((e=>{t[s(e)]||console.warn(`Invalid operator exclusion: ${e}`),delete a[t[s(e)]]})),a},o=(e,r=200)=>e.length<r?e:`${e.slice(0,r-2).trim()}...`,l=(e,r)=>{const t=Object.entries(e).map((([e,t])=>[r(e),t]));return Object.fromEntries(t)},u=e=>/^\$.+/.test(e),c=(e,{resolvedAliasNodes:r})=>"string"==typeof e&&u(e)?r?.[e]??e:e,p=(e,r,t)=>{const a={...e,...r};return t?((e.data||r.data)&&(a.data={...e.data,...r.data}),(e.functions||r.functions)&&(a.functions={...e.functions,...r.functions}),(e.fragments||r.fragments)&&(a.fragments={...e.fragments,...r.fragments}),(e.headers||r.headers)&&(a.headers={...e.headers,...r.headers}),a):a},d={number:e=>h(e),string:e=>String(e),array:e=>Array.isArray(e)?e:[e],boolean:e=>Boolean(e),bool:e=>Boolean(e)},h=e=>{if("string"!=typeof e)return Number.isNaN(Number(e))?e:Number(e);const r=new RegExp(/-?\d*\.?\d+/gm),t=e.match(r);return t?Number(t[0]):0},m=e=>e.replace(/[^A-Za-z\d _-]/g,"").split(/[-_ ]/).map((e=>e.match(/[a-z]+|[A-Z]+[a-z]*/g)??e)).flat().filter((e=>""!==e)).map(((e,r)=>0===r?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase())).join(""),f=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),y=e=>t(e)||a(e)||"string"==typeof e&&u(e)||f(e)&&1===Object.keys(e).length&&u(Object.keys(e)[0]),g={and:"AND","&":"AND","&&":"AND",or:"OR","|":"OR","||":"OR","=":"EQUAL",eq:"EQUAL",equal:"EQUAL",equals:"EQUAL","!=":"NOT_EQUAL",notEqual:"NOT_EQUAL","!":"NOT_EQUAL",ne:"NOT_EQUAL","+":"PLUS",plus:"PLUS",add:"PLUS",concat:"PLUS",join:"PLUS",merge:"PLUS","-":"SUBTRACT",subtract:"SUBTRACT",minus:"SUBTRACT",takeaway:"SUBTRACT","*":"MULTIPLY",x:"MULTIPLY",multiply:"MULTIPLY",times:"MULTIPLY","/":"DIVIDE",divide:"DIVIDE","÷":"DIVIDE",">":"GREATER_THAN",greaterThan:"GREATER_THAN",higher:"GREATER_THAN",larger:"GREATER_THAN","<":"LESS_THAN",lessThan:"LESS_THAN",lower:"LESS_THAN",smaller:"LESS_THAN","?":"CONDITIONAL",conditional:"CONDITIONAL",ifThen:"CONDITIONAL",regex:"REGEX",patternMatch:"REGEX",regexp:"REGEX",matchPattern:"REGEX",getData:"OBJECT_PROPERTIES",dataProperties:"OBJECT_PROPERTIES",data:"OBJECT_PROPERTIES",objectProperties:"OBJECT_PROPERTIES",objProps:"OBJECT_PROPERTIES",getProperty:"OBJECT_PROPERTIES",getObjProp:"OBJECT_PROPERTIES",stringSubstitution:"STRING_SUBSTITUTION",substitute:"STRING_SUBSTITUTION",stringSub:"STRING_SUBSTITUTION",replace:"STRING_SUBSTITUTION",split:"SPLIT",arraySplit:"SPLIT",count:"COUNT",length:"COUNT",GET:"GET",get:"GET",api:"GET",POST:"POST",post:"POST",sql:"SQL",pgSql:"SQL",postgres:"SQL",pg:"SQL",sqLite:"SQL",sqlite:"SQL",mySql:"SQL",graphQL:"GRAPHQL",graphQl:"GRAPHQL",graphql:"GRAPHQL",gql:"GRAPHQL",buildObject:"BUILD_OBJECT",build:"BUILD_OBJECT",object:"BUILD_OBJECT",match:"MATCH",switch:"MATCH",customFunctions:"CUSTOM_FUNCTIONS",customFunction:"CUSTOM_FUNCTIONS",objectFunctions:"CUSTOM_FUNCTIONS",function:"CUSTOM_FUNCTIONS",functions:"CUSTOM_FUNCTIONS",runFunction:"CUSTOM_FUNCTIONS",pass:"PASSTHRU",_:"PASSTHRU",passThru:"PASSTHRU",passthru:"PASSTHRU",ignore:"PASSTHRU",coerce:"PASSTHRU",convert:"PASSTHRU"},v=g,b=(e,r={},t,a=!0)=>a&&f(e)?T(e,r,t):e,T=(e,r,s)=>{if(t(e)||a(e))return e;const n=Object.entries(e),i=n.filter((([e])=>u(e))),o=n.filter((([e])=>!u(e)));return{...i.reduce(((e,[t,a])=>e={...e,...w(t,a,r,s)}),{}),...Object.fromEntries(o)}},w=(e,r,t,a)=>{const s=e.slice(1),i=n(s,v);return i?Array.isArray(r)?{operator:i,children:r}:f(r)&&!Object.keys(r).some((e=>u(e)))?{operator:i,...r}:{operator:i,children:[r]}:s in t?{fragment:s,parameters:{...r}}:a.includes(s)?Array.isArray(r)?{operator:s,args:r}:f(r)?"input"in r||"args"in r?{operator:s,...r}:{operator:s,input:r}:{operator:s,args:[r]}:{[e]:r}};class C extends Error{constructor(e,r,t,a){super(e.message),Object.assign(this,e),this.operator=r,this.expression=a,this.errorData=e.errorData,t&&(this.name=t),"Error"===this.name&&(this.name="FigTreeError");const s=(r?"Operator: "+r:"")+("FigTreeError"===this.name?"":` - ${this.name}`),n=this.errorData?"\n"+JSON.stringify(this.errorData,null,2):"";this.prettyPrint=`${""!==s?s+"\n":""}${this.message}${"\n{}"===n?"":n}`}}const E=e=>e instanceof C,A=({fallback:e,operator:r,name:t,error:a,expression:s,returnErrorAsString:n=!1})=>{if(void 0!==e)return e;if(a instanceof C){if(!n)throw a;return a.prettyPrint}const i=new C("string"==typeof a?new Error(a):a,r,t,s);if(n)return i.prettyPrint;throw i},S=e=>f(e)&&"literal"in e,q=({value:e,name:r,expectedType:t})=>{if(S(t)){const{literal:a}=t;return!!a.includes(e)||j(r,e,`Literal(${a.map((e=>void 0===e?"undefined":`"${e}"`)).join(", ")})`)}if(Array.isArray(t))return!!t.some((t=>!0===q({value:e,name:r,expectedType:t})))||j(r,e,t.join("|"));return!!(0,N[t])(e)||j(r,e,t)},O=(...e)=>{const r=[];return e.forEach((e=>{const t=q(e);!0!==t&&r.push(t)})),!(r.length>0)||r.join("\n")},N={any:e=>void 0!==e,string:e=>"string"==typeof e,number:e=>"number"==typeof e,boolean:e=>"boolean"==typeof e,array:e=>Array.isArray(e),null:e=>null===e,object:e=>f(e),undefined:e=>void 0===e},j=(e,r,t)=>void 0===r&&e?`- Missing required property "${e}" (type: ${t})`:void 0!==e?`- Property "${e}" (value: ${P(r)}) is not of type: ${t}`:`- ${P(r)} is not of type: ${t}`,P=e=>{const r=void 0===e||Number.isNaN(e)?String(e):JSON.stringify(e);return o(r,50)},x=e=>{const r={};return e.forEach((e=>{e.aliases.forEach((t=>r[t]=e.name))})),r},k=(e,r)=>e.map((({name:e,required:t,type:a})=>{if(S(a)){const s=[...a.literal];return t||s.push(void 0),{name:e,value:r[e],expectedType:{literal:s}}}const s=Array.isArray(a)?a:[a];t||s.push("undefined");const n=1===s.length?s[0]:s;return{name:e,value:r[e],expectedType:n}})),L=(e,r)=>{const t=e.map(((e,t)=>[e,r[t]]));return Object.fromEntries(t)},I=e=>{if(e.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const r=e.filter(((e,r)=>r%2==0)),t=O(...r.map((e=>({value:e,expectedType:["string","number","boolean"]}))));if(!0!==t)throw new Error(t);const a=e.filter(((e,r)=>r%2==1)),s={};return r.forEach(((e,r)=>{s[e]=a[r]})),s},U=e=>f(e)&&1===Object.keys(e).length?Object.values(e)[0]:e,R=(r,t,a=void 0)=>{const s=t?e(r,t,a):r;return Array.isArray(s)?s.map((e=>U(e))):t?null===s?null:U(s):s},D=e=>/^https?:\/\/.+/.test(e),Q=(...e)=>e.reduce(((e,r,t)=>{const a="/"===r[0]?1:0,s="/"===r.slice(-1)?-1:void 0,n=r.slice(a,s);return""===n?e:e+(0===t?"":"/")+n}),""),_=async(e,r)=>{const{url:t,params:a={},data:s={},headers:n={},method:i="get"}=r;if(!t||""===t)throw new Error("Invalid url");try{return await e[i]({url:t,headers:{"Content-Type":"application/json",Accept:"application/json",...n},params:a,data:s})}catch(r){e.throwError(r)}},F=async(e,r)=>{const{options:s,operators:i,operatorAliases:o}=r;let u=s?.allowJSONStringInput?(e=>{if("string"!=typeof e)return e;try{const r=JSON.parse(e);return t(r)?r:e}catch(r){return e}})(e):e;const p=Object.keys(r.options?.functions??{});u=b(u,r.options?.fragments,p,!s.noShorthand),Array.isArray(u)&&(u=await $(u,r));const h=t(u),m=a(u);if(h&&(u=await(async(e,r)=>{if(!(e.operator in(r.options?.functions??{})))return e;const{operator:t,fallback:a,outputType:s,type:n,useCache:i,input:o,args:l,...u}=e,c={operator:"CUSTOM_FUNCTIONS",function:t};return void 0!==a&&(c.fallback=a),void 0!==s&&(c.outputType=s),void 0!==n&&(c.type=n),void 0!==i&&(c.useCache=i),void 0!==l&&(c.args=l),void 0!==o?c.input=o:Object.keys(u).length>0&&(c.input=u),c})(u,r)),s.evaluateFullObject&&!h&&!m)return c(await M(u,r),r);if(!h&&!m)return s.supportDeprecatedValueNodes&&f(u)&&"value"in u?u.value:c(u,r);const{fallback:y}=u,g=s?.returnErrorAsString??!1;if(m){const e={...u},a=s?.fragments?.[e.fragment]?.metadata?.parameters?.filter((e=>void 0!==e.default));void 0===e.parameters&&(e.parameters={}),a?.forEach((r=>{void 0===e.parameters?.[r.name]&&void 0===e?.[r.name]&&(e.parameters[r.name]=r.default)}));const[n,i]=await $([e.fragment,e.parameters],r),o=b(s?.fragments?.[n],s.fragments,p,!s.noShorthand);if(void 0===o)return A({fallback:await F(y,r),error:`Fragment not defined: ${n}`,expression:u,returnErrorAsString:g});if(!t(o))return c(o,r);u={...e,...o,...i},delete u.fragment}const v=u,T=n(v.operator,o);if(!T)return A({fallback:await F(y,r),error:`Invalid operator: ${v.operator}`,expression:u,returnErrorAsString:g});if(!r.operators[T])return A({fallback:await F(y,r),error:`Excluded operator: ${v.operator}`,expression:u,returnErrorAsString:g});const{propertyAliases:w,evaluate:C,parseChildren:E}=i[T];let S=((e,r)=>l(r,(r=>r in e?e[r]:r)))(w,v);const q=await H(S,r);m||Object.entries(q).forEach((([e,t])=>r.resolvedAliasNodes[e]=t));const O=m?{...r,resolvedAliasNodes:{...r.resolvedAliasNodes,...q}}:r;if("children"in S){if(Array.isArray(S.children)||(S.children=await F(S.children,O)),!Array.isArray(S.children))return A({fallback:await F(y,r),operator:T,name:"Type Error",error:'- Property "children" is not of type: array',expression:u,returnErrorAsString:g});try{S=E(S,O),delete S.children}catch(e){return A({fallback:await F(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}}let N;try{N=await C(S,O)}catch(e){return A({fallback:await F(S.fallback,r),operator:T,error:e,expression:S,returnErrorAsString:g})}const j=S?.outputType??S?.type;if(!j)return N;const P=await F(j,r);return P in d?d[P](N):A({fallback:await F(y,r),operator:T,error:`- Invalid output type: ${P}`,expression:S,returnErrorAsString:g})},$=async(e,r)=>Array.isArray(e)?await Promise.all(e.map((e=>F(e,r)))):await F(e,r),H=async(e,r)=>{const t=Object.keys(e).filter(u);if(0===t.length)return{};const a=[];t.forEach((t=>a.push(F(e[t],r))));const s=await Promise.all(a),n=L(t,await Promise.all(a));for(const[e,r]of s.entries())"string"==typeof r&&u(r)&&(n[t[e]]=n?.[r]??r);return n},M=async(e,r)=>{const t=Object.keys(r.options?.functions??{}),a=b(e,r.options?.fragments,t);if(!f(a))return e;const s=[],n=[];Object.entries(a).forEach((([e,t])=>{u(e)&&(n.push(e,F(t,r)),delete a[e])}));const i=await Promise.all(n);r.resolvedAliasNodes={...r.resolvedAliasNodes,...I(i)},Object.entries(a).forEach((([e,t])=>{s.push(e,F(t,r))}));const o=await Promise.all(s);return c(I(o),r)},G=[{name:"values",description:"Returns true if all values are true",aliases:[],required:!0,type:"array",default:[!0,!0]}],B=x(G),z={description:"Logical AND",aliases:["and","&","&&"],parameters:G},W=e=>{const r=e.children;return{...e,values:r}},J={propertyAliases:B,operatorData:z,evaluate:async(e,r)=>{const t=await $(e.values,r);return r.typeChecker(k(z.parameters,{values:t})),t.reduce(((e,r)=>e&&!!r),!0)},parseChildren:W},V=[{name:"values",description:"Returns true if any values are true",aliases:[],required:!0,type:"array",default:[!0,!1]}],Y=x(V),X={description:"Logical OR",aliases:["or","|","||"],parameters:V},Z={propertyAliases:Y,operatorData:X,evaluate:async(e,r)=>{const t=await $(e.values,r);return r.typeChecker(k(X.parameters,{values:t})),t.reduce(((e,r)=>e||!!r),!1)},parseChildren:W},K=[{name:"values",description:"Array of values to check for equality",aliases:[],required:!0,type:"array",default:["These are equal","These are equal"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],ee=x(K),re={description:"Test multiple values are equal",aliases:["=","eq","equal","equals"],parameters:K},te={propertyAliases:ee,operatorData:re,evaluate:async(e,t)=>{const[a,s,n]=await $([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(k(re.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:n}));const i=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==n?n:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==i[0]&&void 0!==i[0]?i.every((e=>r(e,i[0]))):i.every((e=>null==e))},parseChildren:W},ae=[{name:"values",description:"Array of values to check for inequality",aliases:[],required:!0,type:"array",default:["These items","don't match"]},{name:"caseInsensitive",description:"If the values are strings, ignore the case (default: false)",aliases:[],required:!1,type:"boolean",default:!1},{name:"nullEqualsUndefined",description:"Whether a null value should be considered equal to an undefined value (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],se=x(ae),ne={description:"Test if any values are different",aliases:["!=","notEqual","!","ne"],parameters:ae},ie={propertyAliases:se,operatorData:ne,evaluate:async(e,t)=>{const[a,s,n]=await $([e.values,e.caseInsensitive,e.nullEqualsUndefined],t);t.typeChecker(k(ne.parameters,{values:a,caseInsensitive:s,nullEqualsUndefined:n}));const i=(void 0!==s?s:t.options?.caseInsensitive??!1)&&a.every((e=>"string"==typeof e))?a.map((e=>e.toLowerCase())):a;return!(void 0!==n?n:void 0!==t.options?.nullEqualsUndefined&&t.options.nullEqualsUndefined)||null!==i[0]&&void 0!==i[0]?i.some((e=>!r(e,i[0]))):i.some((e=>!(null==e)))},parseChildren:W},oe=[{name:"values",description:"Array of values to check to add together",aliases:[],required:!0,type:"array",default:[1,2,3]},{name:"type",description:"Data type to coerce input values to before addition",aliases:[],required:!1,type:{literal:["string","array","number","boolean","bool"]},default:"string"}],le=x(oe),ue={description:"Add, concatenate or merge multiple values",aliases:["+","plus","add","concat","join","merge"],parameters:oe},ce={propertyAliases:le,operatorData:ue,evaluate:async(e,r)=>{const t=await $(e.values,r);return r.typeChecker(k(ue.parameters,{values:t,type:e.type})),0===t.length?t:"string"===e?.type?t.reduce(((e,r)=>e.concat(r)),""):"array"===e?.type?t.reduce(((e,r)=>e.concat(r)),[]):t.every((e=>"string"==typeof e||Array.isArray(e)))?t.reduce(((e,r)=>e.concat(r))):t.every((e=>f(e)))?t.reduce(((e,r)=>({...e,...r})),{}):t.reduce(((e,r)=>e+r))},parseChildren:W},pe=[{name:"values",description:"Array of values - 2nd element will be subtracted from the first",aliases:[],required:!1,type:"array",default:[10,5]},{name:"from",description:"Numerical value that will be subtracted from",aliases:["subtractFrom"],required:!1,type:"number",default:100},{name:"subtract",description:"Numerical value to subtract",aliases:[],required:!1,type:"number",default:50}],de=x(pe),he={description:"Subtract one numerical value from another",aliases:["-","subtract","minus","takeaway"],parameters:pe},me={propertyAliases:de,operatorData:he,evaluate:async(e,r)=>{const[t,a,s]=await $([e.values,e.from,e.subtract],r);r.typeChecker(k(he.parameters,{values:t,from:a,subtract:s}));const n=t??[a,s].filter((e=>void 0!==e));if(n.length<2)throw new Error("- Not enough values provided");if(n.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return n[0]-n[1]},parseChildren:W},fe=[{name:"values",description:"Array of values whose product will be calculated",aliases:[],required:!0,type:"array",default:[5,5]}],ye=x(fe),ge={description:"Multiply several numerical values together",aliases:["*","x","multiply","times"],parameters:fe},ve={propertyAliases:ye,operatorData:ge,evaluate:async(e,r)=>{const t=await $(e.values,r);if(r.typeChecker(k(ge.parameters,{values:t})),0===t.length)return 0;if(t.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");return t.reduce(((e,r)=>e*r))},parseChildren:W},be=[{name:"values",description:"Array of values - 1st element will be divided by the second",aliases:[],required:!1,type:"array",default:[100,10]},{name:"dividend",description:"The number that will be divided",aliases:["divide"],required:!1,type:"number",default:99},{name:"divisor",description:"The number that dividend will be divided by",aliases:["by","divideBy"],required:!1,type:"number",default:3},{name:"output",description:"Whether to output a quotient, remainder or decimal",aliases:[],required:!1,type:{literal:["quotient","remainder","decimal"]},default:"decimal"}],Te=x(be),we={description:"Divide one numerical value by another",aliases:["/","divide","÷"],parameters:be},Ce={propertyAliases:Te,operatorData:we,evaluate:async(e,r)=>{const[t,a,s,n]=await $([e.values,e.dividend,e.divisor,e.output],r);r.typeChecker(k(we.parameters,{values:t,dividend:a,divisor:s,output:n}));const i=t??[a,s].filter((e=>void 0!==e));if(i.length<2)throw new Error("- Not enough values provided");if(i.some((e=>"number"!=typeof e)))throw new Error("- Not all values are numbers");if(0===i[1])throw new Error("Division by zero!");switch(n){case"quotient":return Math.floor(i[0]/i[1]);case"remainder":return i[0]%i[1];default:return i[0]/i[1]}},parseChildren:W},Ee=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[10,9]},{name:"strict",description:"Whether value must be strictly greater than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ae=x(Ee),Se={description:"Test if a value is greater than (or equal to) another value",aliases:[">","greaterThan","higher","larger"],parameters:Ee},qe={propertyAliases:Ae,operatorData:Se,evaluate:async(e,r)=>{const[t,a=!0]=await $([e.values,e.strict],r);if(r.typeChecker(k(Se.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,n]=t;return s===n&&!a||s>n},parseChildren:W},Oe=[{name:"values",description:"Array of values - 1st element will be compared to the second",aliases:[],required:!0,type:"array",default:[9,10]},{name:"strict",description:"Whether value must be strictly smaller than (i.e. not equal) (default: false)",aliases:[],required:!1,type:"boolean",default:!1}],Ne=x(Oe),je={description:"Test if a value is smaller than (or equal to) another value",aliases:["<","lessThan","lower","smaller"],parameters:Oe},Pe={propertyAliases:Ne,operatorData:je,evaluate:async(e,r)=>{const[t,a=!0]=await $([e.values,e.strict],r);if(r.typeChecker(k(je.parameters,{values:t,strict:a})),t.length<2)throw new Error("- Not enough values provided");const[s,n]=t;return s===n&&!a||s<n},parseChildren:W},xe=[{name:"condition",description:"The expression to check for truthiness",aliases:[],required:!0,type:"any",default:!0},{name:"valueIfTrue",description:"Value to return if condition is true",aliases:["ifTrue"],required:!0,type:"any",default:"The condition is true"},{name:"valueIfFalse",description:"Value to return if condition is false",aliases:["ifFalse","ifNot"],required:!0,type:"any",default:"The condition is false"}],ke=x(xe),Le={description:"Return a value based on a condition",aliases:["?","conditional","ifThen"],parameters:xe},Ie={propertyAliases:ke,operatorData:Le,evaluate:async(e,r)=>{r.typeChecker(k(Le.parameters,{condition:e.condition,valueIfTrue:e.valueIfTrue,valueIfFalse:e.valueIfFalse}));return await F(e.condition,r)?await F(e.valueIfTrue,r):await F(e.valueIfFalse,r)},parseChildren:e=>{const[r,t,a]=e.children;return{...e,condition:r,valueIfTrue:t,valueIfFalse:a}}},Ue=[{name:"testString",description:"The string to test",aliases:["string","value"],required:!0,type:"string",default:"test-this"},{name:"pattern",description:"The regular expression pattern",aliases:["regex","regexp","regExp","re"],required:!0,type:"string",default:"^[a-z]{4}-[a-z]{4}$"}],Re=x(Ue),De={description:"Compare a string against a regex pattern",aliases:["regex","patternMatch","regexp","matchPattern"],parameters:Ue},Qe={propertyAliases:Re,operatorData:De,evaluate:async(e,r)=>{const[t,a]=await $([e.testString,e.pattern],r);r.typeChecker(k(De.parameters,{testString:t,pattern:a}));return new RegExp(a).test(t)},parseChildren:e=>{const[r,t]=e.children;return{...e,testString:r,pattern:t}}},_e=[{name:"property",description:'The path to the required property (e.g. "user.firstName")',aliases:["path","propertyName"],required:!0,type:"string",default:"path.to[0].my.data"},{name:"additionalData",description:"Additional data objects to be considered",aliases:["additional","objects","data","additionalObjects"],required:!1,type:["object","array"],default:{}}],Fe=x(_e),$e={description:"Extract values from data objects",aliases:["getData","dataProperties","data","objectProperties","objProps","getProperty","getObjProp"],parameters:_e},He={propertyAliases:Fe,operatorData:$e,evaluate:async(r,t)=>{const[a,s={}]=await $([r.property,r.additionalData],t);t.typeChecker(k($e.parameters,{property:a,additionalData:s}));const n={...t.options?.data??{},...s};return e(n,a)},parseChildren:e=>{const[r,t]=e.children,a={...e,property:r};return void 0!==t&&(a.fallback=t),a}},Me=[{name:"string",description:"A parameterised (%1, %2) string where the parameters are to be replaced",aliases:[],required:!0,type:"string",default:"Hello, %1"},{name:"substitutions",description:"An array of substitution values for the parameterised string",aliases:["replacements","values"],required:!1,type:["array","object"],default:{}},{name:"trimWhiteSpace",description:"Whether or not to trim white space from either end of the substituted strings (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"substitutionCharacter",description:'Which character to search for in original string for replacement -- can be "%" or "$" (default: "%")',aliases:["subCharacter","subChar"],required:!1,type:"string",default:"$"},{name:"numberMapping",description:"Rules for mapping number values to text strings, such as pluralisation.",aliases:["numMap","numberMap","pluralisation","pluralization","plurals"],required:!1,type:"object",default:{}}],Ge=x(Me),Be={description:"Replace values in a string using simple parameter substitution",aliases:["stringSubstitution","substitute","stringSub","replace"],parameters:Me},ze={propertyAliases:Ge,operatorData:Be,evaluate:async(e,r)=>{const[t,a={},s=!0,n="%",i={}]=await $([e.string,e.substitutions,e.trimWhiteSpace,e.substitutionCharacter,e.numberMapping],r);if(r.typeChecker(k(Be.parameters,{string:t,substitutions:a,trimWhiteSpace:s,substitutionCharacter:n,numberMapping:i})),Array.isArray(a)){const e="$"===n?"$":"%",r=new RegExp(`(?<!\\\\)(${"%"===e?"%":"\\$"}[\\d]+)`,"g"),i=(t.match(r)||[]).sort(((e,r)=>Number(e.slice(1))-Number(r.slice(1)))),o=new Set(i),l=L(Array.from(o),a.map((e=>We(e,s))));return t.split(r).map((e=>e in l?l[e]:e)).join("").replace(new RegExp(`\\\\${"$"===e?"\\$":e}`,"g"),e)}const o=/(?<!\\)({{(?:[A-Za-z0-9_.]|\[[0-9]+\])+}})/g,l=[];for(const e of t.split(o)){if(!/(?<!\\){{(.+)}}/.exec(e)){l.push(e.replace(/\\\{\{/g,"{{"));continue}const t=await Je(e,a,i,r);l.push(We(t,s))}return l.join("")},parseChildren:e=>{const[r,...t]=e.children;return{...e,string:r,substitutions:t}}},We=(e,r)=>{if(null==e)return"";const t=String(e);return r?t.trim():t},Je=async(r,t,a,s)=>{const n=s.options?.data??{},i=r.replace(/{{(.+)}}/,"$1"),o=await F(e(t,i,e(n,i,"")),s);if("number"!=typeof o)return o;if(!(i in a))return o;const l=a[i];if(o in l)return l[o].replace("{}",String(o));const u=Object.keys(a[i]),c=u.find((e=>e.startsWith(">")));if(c){if(o>Number(c.slice(1)))return l?.[c]}const p=u.find((e=>e.startsWith("<")));if(p){if(o<Number(p.slice(1)))return l?.[p]}return l.other?l.other.replace("{}",String(o)):o},Ve=[{name:"values",description:"An array to count",aliases:[],required:!0,type:"array",default:[1,2,3,4,5]}],Ye=x(Ve),Xe={description:"Count elements in an array",aliases:["count","length"],parameters:Ve},Ze={propertyAliases:Ye,operatorData:Xe,evaluate:async(e,r)=>{const t=await $(e.values,r);return r.typeChecker(k(Xe.parameters,{values:t})),t.length},parseChildren:W},Ke=[{name:"value",description:"The string to be split",aliases:["string"],required:!0,type:"string",default:"Alpha, Bravo, Charlie"},{name:"delimiter",description:"The value to split the string on (default is white space)",aliases:["separator"],required:!1,type:"string",default:","},{name:"trimWhiteSpace",description:"Whether to trim white space from around the resulting elements (default: true)",aliases:["trim","trimWhitespace"],required:!1,type:"boolean",default:!0},{name:"excludeTrailing",description:"If the input string ends in a delimiter, there will be an additional blank element if this value is false (default: true)",aliases:["removeTrailing","excludeTrailingDelimiter"],required:!1,type:"boolean",default:!0}],er=x(Ke),rr={description:"Split a string into an array",aliases:["split","arraySplit"],parameters:Ke},tr=" ",ar={propertyAliases:er,operatorData:rr,evaluate:async(e,r)=>{const[t,a,s,n]=await $([e.value,e.delimiter??tr,e.trimWhiteSpace??!0,e.excludeTrailing??!0],r);r.typeChecker(k(rr.parameters,{value:t,delimiter:a,trimWhiteSpace:s,excludeTrailing:n}));let i=t.split((e=>e.replace(/\\n/g,"\n").replace(/\\t/g,"\t").replace(/\\r/g,"\r"))(a));return s&&(i=i.map((e=>e.trim()))),n&&""===i[i.length-1]&&i.pop(),i},parseChildren:e=>{const[r,t=tr]=e.children;return{...e,value:r,delimiter:t}}},sr=[{name:"query",description:"SQL query string, with parameterised replacements (e.g. $1, $2, etc)",aliases:["text"],required:!0,type:"string"},{name:"values",description:"An array/object of values to replace the SQL string parameters, as per SQL connection specifications ",aliases:["replacements"],required:!1,type:["array","object"]},{name:"single",description:"Specify if returning a single record",aliases:["singleRecord"],required:!1,type:"boolean"},{name:"flatten",description:"Specify whether to flatten resulting record objects to arrays of values",aliases:["flat","array"],required:!1,type:"boolean"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean"}],nr=x(sr),ir={description:"Query an SQL database",aliases:["sql","pgSql","postgres","pg","sqLite","sqlite","mySql"],parameters:sr},or={propertyAliases:nr,operatorData:ir,evaluate:async(e,r)=>{const t=r.options?.sqlConnection;if(!t)throw new Error("No SQL database connection provided");const[a,s,n,i,o,l]=await $([e.query,e.values||[],e.single,e.flatten,e.useCache,e.type],r);r.typeChecker(k(ir.parameters,{query:a,single:n,flatten:i,values:s,useCache:o}));const u=e.useCache??r.options.useCache??!0;{const e=r.cache.useCache(u,(async(e,r,a,s,n)=>{const i=await t.query({query:e,values:r})||[];["array","string","number"].includes(n??"")&&(s=!0);const o=s?i.map((e=>{const r=Object.values(e);return r.length<=1?r[0]:r})):i;return a?o[0]:o}),a,s,n,i,l);return e}},parseChildren:e=>{const[r,...t]=e.children;return{...e,query:r,values:t}}},lr=[{name:"query",description:"GraphQL query string",aliases:[],required:!0,type:"string",default:'query getCountries {\n countries(filter: {continent: {eq: "OC"}}) {\n name\n }\n }'},{name:"url",description:"Endpoint for the GraphQL request (if not already provided in options)",aliases:["endpoint"],required:!1,type:["string","null"],default:"https://countries.trevorblades.com/"},{name:"headers",description:"HTTP Headers (if not already provided in options)",aliases:[],required:!1,type:"object",default:{}},{name:"variables",description:"Values for the variables used in query (key-value pairs)",aliases:[],required:!1,type:"object",default:{}},{name:"returnNode",description:"Property path to extract from the query response",aliases:["outputNode","returnProperty"],required:!1,type:"string",default:"data.countries[1].name"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],ur=x(lr),cr={description:"GraphQL request",aliases:["graphQL","graphQl","graphql","gql"],parameters:lr},pr={propertyAliases:ur,operatorData:cr,evaluate:async(e,r)=>{const t=r.graphQLClient??r.httpClient;if(!t)throw new Error("No HTTP client provided for GraphQL connection");const[a,s,n,i,o,l]=await $([e.query,e.url,await M(e.variables,r),e.returnNode,e.headers,e.useCache],r),{url:u,headers:c}=s instanceof Object?s:{url:s,headers:null};r.typeChecker([...k(cr.parameters,{url:u,query:a,variables:n,returnNode:i,headers:o,useCache:l}),{name:"headers",value:c,expectedType:["object","null"]}]);const p=u&&"graphqlendpoint"!==u.toLowerCase()?u:"",d=r.options.graphQLConnection?.endpoint??r.options.baseEndpoint??"",h=D(p)?p:Q(d,p),m={query:a,variables:n},f=l??r.options.useCache??!0,y=await r.cache.useCache(f,(async(e,r,a,s)=>{const n=await _(t,{url:e,method:"post",data:r,headers:a});return R(n?.data,s)}),h,m,{...r.options.graphQLConnection?.headers,...r.options?.headers,...c,...o},i);return y},parseChildren:e=>{const[r,t="",a,...s]=e.children,n=Array.isArray(a)?a:[a],i=s.slice(0,n.length),o=L(n,i),l={...e,query:r,url:t,variables:o};return s.length>n.length&&(l.returnNode=s.pop()),l}},dr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://restcountries.com/v3.1/name/zealand"},{name:"returnProperty",description:"Property from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"Query parameters (key-value)",aliases:["queryParams","queryParameters","urlQueries"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],hr=x(dr),mr={description:"HTTP GET Request",aliases:["GET","get","api"],parameters:dr},fr=e=>{const[r="",t,...a]=e.children,s=Array.isArray(t)?t:[t],n=a.slice(0,s.length),i=L(s,n),o={...e,url:r,parameters:i};return a.length>s.length&&(o.returnProperty=a.pop()),o},yr=fr,gr={propertyAliases:hr,operatorData:mr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,n,i,o]=await $([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...k(mr.parameters,{url:l,returnProperty:n,headers:i,parameters:s,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...i},d=o??r.options.useCache??!0,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const n=await _(t,{url:e,params:r,headers:a});return R(n,s)}),D(l)?l:Q(c,l),s,p,n);return h},parseChildren:fr},vr=[{name:"url",description:"Endpoint URL",aliases:["endpoint"],required:!0,type:"string",default:"https://jsonplaceholder.typicode.com/posts"},{name:"returnProperty",description:"Property path from request result",aliases:["outputProperty"],required:!1,type:"string",default:"result.path"},{name:"headers",description:"HTTP Headers",aliases:[],required:!1,type:"object",default:{}},{name:"parameters",description:"JSON Body parameters (key-value)",aliases:["bodyJson","data"],required:!1,type:"object",default:{}},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!0}],br=x(vr),Tr={description:"HTTP POST Request",aliases:["POST","post"],parameters:vr},wr={propertyAliases:br,operatorData:Tr,evaluate:async(e,r)=>{const t=r.httpClient;if(!t)throw new Error("No HTTP client provided");const[a,s,n,i,o]=await $([e.url,await M(e.parameters,r),e.returnProperty,await M(e.headers,r),e.useCache],r),{url:l,headers:u}=a instanceof Object?a:{url:a,headers:null};r.typeChecker([...k(Tr.parameters,{url:l,headers:i,data:s,returnProperty:n,useCache:o}),{name:"headers",value:u,expectedType:["object","null"]}]);const c=r.options.baseEndpoint??"",p={...r.options?.headers,...u,...i},d=o??r.options.useCache??!1,h=await r.cache.useCache(d,(async(e,r,a,s)=>{const n=await _(t,{url:e,data:r,headers:a,method:"post"});return R(n,s)}),D(l)?l:Q(c,l),s,p,n);return h},parseChildren:yr},Cr=[{name:"properties",description:'An array of objects, each with a "key" property and a "value" property',aliases:["values","keyValPairs","keyValuePairs"],required:!0,type:"array",default:["firstKey","firstValue","secondKey","secondValue"]}],Er=x(Cr),Ar={description:"Construct an object using objects defining keys and values",aliases:["buildObject","build","object"],parameters:Cr},Sr=e=>{const r=e.children;if(r.every((e=>f(e))))return{...e,properties:r};if(r.length%2!=0)throw new Error("Even number of children required to make key/value pairs");const t=r.filter(((e,r)=>r%2==0)),a=r.filter(((e,r)=>r%2==1)),s=t.map(((e,r)=>({key:e,value:a[r]})));return{...e,properties:s}},qr={propertyAliases:Er,operatorData:Ar,evaluate:async(e,r)=>{const t=await $(e.properties,r);r.typeChecker(k(Ar.parameters,{properties:t}));const{properties:a}=t.some((e=>!f(e)))?Sr({...e,children:t}):{properties:t},s=a.filter((e=>e instanceof Object&&"key"in e&&"value"in e)).map((({key:e,value:t})=>(async e=>{const[t,a]=await $(e,r);return r.typeChecker({name:"key",value:t,expectedType:["string","number","boolean"]}),[t,a]})([e,t])));return Object.fromEntries(await Promise.all(s))},parseChildren:Sr},Or=[{name:"matchExpression",description:"Expression to match against",aliases:["matchValue"],required:!0,type:["string","number","boolean"],default:"matchMe"},{name:"branches",description:"Object whose keys are compared against the match expression. The value of the matching key is returned",aliases:["arms","cases"],required:!1,type:["object","array"],default:{matchMe:"YES",nonMatch:"NO"}},{name:"[...branches]",description:"Branch properties can optionally be placed at the operator root",aliases:[],required:!1,type:["object","array"]}],Nr={propertyAliases:x(Or),operatorData:{description:"Return different values depending on a matching expression",aliases:["match","switch"],parameters:Or},evaluate:async(e,r)=>{const a=await F(e.matchExpression,r);r.typeChecker({name:"matchExpression",value:a,expectedType:["string","number","boolean"]});const s=Array.isArray(e.branches)?I(e.branches):e.branches??{},n=t(s)?await F(s,r):s;if(!f(n))throw new Error("Branches don't evaluate to an object");if(a in n)return await F(n[a],r);if("fallback"in n)return await F(n.fallback,r);if(a in e)return await F(e[a],r);throw new Error(`No match found for ${a}`)},parseChildren:e=>{const[r,...t]=e.children,a=I(t);return{...e,matchExpression:r,branches:a}}},jr=[{name:"functionName",description:"Path (in options.functions) to the required function",aliases:["functionPath","funcName","function","path","name"],required:!0,type:"string",default:null},{name:"args",description:"Arguments for the function",aliases:["arguments","variables"],required:!1,type:["array","any"],default:[]},{name:"input",description:"Argument for the function if a single input parameter",aliases:["arg"],required:!1,type:"any",default:"input"},{name:"useCache",description:"Whether or not the FigTree cache is used",aliases:[],required:!1,type:"boolean",default:!1}],Pr=x(jr),xr={description:"Call a custom function (defined in options)",aliases:["customFunctions","customFunction","objectFunctions","function","functions","runFunction"],parameters:jr},kr={propertyAliases:Pr,operatorData:xr,evaluate:async(r,t)=>{const[a,s=[],n,i]=await $([r.functionName,r.args,r.input,r.useCache],t);t.typeChecker(k(xr.parameters,{functionName:a,args:s}));const{data:o,functions:l}=t.options;if(!l)throw new Error("- No functions defined");const u=e(l,`${a}.function`,null)??e(l,a,null)??e(t.options,`${a}.function`,null)??e(t.options,a,null)??e(o,a,null);if(!u||"function"!=typeof u)throw new Error(`- No function found: "${a}"`);const c=i??t.options.useCache??!1,p=[...void 0===n?[]:[await M(n,t)],...Array.isArray(s)?s:[s]];return await t.cache.useCache(c,(async(e,...r)=>await u(...r)),a,...p)},parseChildren:e=>{const[r,...t]=e.children;return{...e,functionName:r,args:t}}},Lr=[{name:"value",description:"Value to pass through",aliases:["_","data"],required:!0,type:"any",default:null}],Ir=x(Lr),Ur={description:"Pass through a value unchanged (or change its type)",aliases:["pass","_","passThru","passthru","ignore","coerce","convert"],parameters:Lr},Rr={propertyAliases:Ir,operatorData:Ur,evaluate:async(e,r)=>(r.typeChecker(k(Ur.parameters,{value:e.value})),await F(e.value,r)),parseChildren:e=>{const[...r]=e.children,t=1===r?.length?r[0]:r;return{...e,value:t}}};var Dr=Object.freeze({__proto__:null,AND:J,BUILD_OBJECT:qr,CONDITIONAL:Ie,COUNT:Ze,CUSTOM_FUNCTIONS:kr,DIVIDE:Ce,EQUAL:te,GET:gr,GRAPHQL:pr,GREATER_THAN:qe,LESS_THAN:Pe,MATCH:Nr,MULTIPLY:ve,NOT_EQUAL:ie,OBJECT_PROPERTIES:He,OR:Z,PASSTHRU:Rr,PLUS:ce,POST:wr,REGEX:Qe,SPLIT:ar,SQL:or,STRING_SUBSTITUTION:ze,SUBTRACT:me});const Qr=(e,r,s)=>{const{fragments:n,functionNames:i,evaluateFullObject:o,useShorthand:l}=r;if(f(e)){const c=b(e,n,i,l);if(t(c)||a(c))return!0;if(!o)return!1;const p=new Set([...s,...Object.keys(e).filter(u)]);return Object.values(e).some((e=>Qr(e,r,p)))}return Array.isArray(e)?e.some((e=>Qr(e,r,s))):!("string"!=typeof e||!u(e))&&s.has(e)};class _r{constructor(e){this.useCache=async(e,r,...t)=>{if(!e)return await r(...t);const a=Fr(t),s=a in this.store,n=Date.now(),i=s&&n-this.store[a].timestamp>1e3*this.maxTime;if(s)return this.queue=this.queue.filter((e=>e!==a)),this.queue.unshift(a),this.store[a].timestamp=n,i&&(this.store[a].result=await r(...t)),this.store[a].result;const o=await r(...t);return this.store[a]={result:o,timestamp:n},this.queue.unshift(a),this.resizeCache(),o},this.getMax=()=>this.maxSize,this.setMax=e=>{this.maxSize=e,this.resizeCache()},this.getMaxTime=()=>this.maxTime,this.setMaxTime=e=>{this.maxTime=e},this.getCache=()=>this.store,this.setCache=e=>this.store=e,this.resizeCache=()=>{if(this.queue.length>this.maxSize){this.queue.slice(this.maxSize).forEach((e=>delete this.store[e])),this.queue=this.queue.slice(0,this.maxSize)}},this.store={},this.queue=[],this.maxSize=e?.maxSize??50,this.maxTime=e?.maxTime??1800}}const Fr=e=>e.map((e=>"object"==typeof e?JSON.stringify(e):e)).join("_"),$r=e=>e||("undefined"!=typeof window&&"document"in window&&"fetch"in window?Mr(window.fetch):void 0),Hr=e=>({get:async r=>(await e({...r,method:"get"})).data,post:async r=>(await e({...r,method:"post"})).data,throwError:r=>{if(e.isAxiosError(r)&&r.response)throw r.errorData={status:r.response?.status,error:r.response?.statusText,url:r.config?.url,response:r.response?.data},r;throw new Error("Network error: "+r?.message)}}),Mr=e=>({get:async r=>{const{url:t,headers:a,params:s={}}=r,n=Object.keys(s).length>0?`?${new URLSearchParams(s).toString()}`:"",i=await e(t+n,{headers:a,method:"GET"}),o=await i.json();if(!i.ok){const e=new Error("Problem with GET request");throw e.name="FetchError",e.errorData={status:i.status,error:i.statusText,url:i.url,response:o},console.log(e.errorData),e}return o},post:async r=>{const{url:t,headers:a,params:s,data:n}=r,i=new URLSearchParams(s),o=i.size>0?`?${i.toString()}`:"",l=await e(t+o,{headers:a,body:JSON.stringify(n),method:"POST"}),u=await l.json();if(!l.ok){const e=new Error("Problem with POST request");throw e.name="FetchError",e.errorData={status:l.status,error:l.statusText,url:l.url,response:u},console.log(e.errorData),e}return u},throwError:e=>{throw e}});class Gr{constructor(e={}){this.typeChecker=(...e)=>{const r=1===e.length&&Array.isArray(e[0])?e[0]:e,t=O(...r);if(!0===t)return;const a=new Error(t);throw a.name="Type Error",a},this.getCache=()=>this.cache.getCache(),this.setCache=e=>this.cache.setCache(e),this.getVersion=()=>"2.23.2",this.options=zr(e),this.operators=i(Dr,this.options?.excludeOperators??[],g),this.operatorAliases=g,this.cache=new _r({maxSize:e.maxCacheSize,maxTime:e.maxCacheTime}),this.graphQLClient=$r(e.graphQLConnection?.httpClient),this.httpClient=$r(e.httpClient)}async evaluate(e,r={}){const t=p(this.options,zr(r),!0);return r.httpClient&&(this.httpClient=$r(r.httpClient)),r.graphQLConnection?.httpClient&&(this.graphQLClient=$r(r.graphQLConnection.httpClient)),t.maxCacheSize&&t.maxCacheSize!==this.cache.getMax()&&this.cache.setMax(t.maxCacheSize),t.maxCacheTime&&t.maxCacheTime!==this.cache.getMaxTime()&&this.cache.setMaxTime(t.maxCacheTime),await F(e,{options:t,operators:r.excludeOperators?i(Dr,r.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:t.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient})}isFigTreeExpression(e){return((e,r)=>Qr(e,r,new Set))(e,{fragments:this.options.fragments??{},functionNames:Object.keys(this.options.functions??{}),evaluateFullObject:this.options.evaluateFullObject??!1,useShorthand:!this.options.noShorthand})}getOptions(){return this.options}updateOptions(e){this.options=p(this.options,zr(e),!1),this.options.excludeOperators&&(this.operators=i(Dr,this.options.excludeOperators,g))}getOperators(){const e=this.options.excludeOperators?i(Dr,this.options.excludeOperators,g):this.operators,r=Object.entries(e).map((([e,r])=>({name:e,...r.operatorData,parseChildren:r.parseChildren}))),t=[...new Set(Object.values(g))];return r.sort(((e,r)=>t.indexOf(e.name)-t.indexOf(r.name)))}getFragments(){return Object.entries(this.options.fragments??{}).map((([e,r])=>({name:e,...r?.metadata})))}getCustomFunctions(){return Object.entries(this.options.functions??{}).map((([e,r])=>{const t="function"==typeof r?r:r?.function,a={name:e,numRequiredArgs:t?.length};if("function"!=typeof r){const{description:e,argsDefault:t,inputDefault:s,textColor:n,backgroundColor:i}=r;return e&&(a.description=e),void 0!==t&&(a.argsDefault=t),void 0!==s&&(a.inputDefault=s),n&&(a.textColor=n),i&&(a.backgroundColor=i),a}return a}))}getConfig(){return{options:this.options,operators:this.options.excludeOperators?i(Dr,this.options.excludeOperators,g):this.operators,operatorAliases:this.operatorAliases,typeChecker:this.options.skipRuntimeTypeCheck?()=>{}:this.typeChecker,resolvedAliasNodes:{},cache:this.cache,graphQLClient:this.graphQLClient,httpClient:this.httpClient}}}const Br=(e,r)=>new Gr(r).evaluate(e),zr=e=>"objects"in e?{...e,data:e.objects}:e,Wr=e=>({query:async({query:r,values:t=[]})=>{const a={text:r,values:t??[]};try{const r=await e.query(a);if(r?.error)throw new Error(r.error);return r.rows}catch(e){throw e.name="Node-Postgres error",e}}}),Jr=e=>({query:async({query:r,values:t=[]})=>{try{return await e.all(r,t)}catch(e){throw e.name="SQLite error",e}}}),Vr=(e,r)=>{const t=r.getOperators(),a=e=>{if(!f(e))return e;const n=Yr(e)?(()=>{const{operator:a}=e,n=s(a),i=t.find((e=>e.name===n||e.aliases.includes(n)));if(i){const t=i.parseChildren(e,r.getConfig());delete t.children;const a=i.aliases[0];return t.operator=a,t}throw new Error("Invalid operator: "+a)})():e,i={};for(const[e,r]of Object.entries(n)){const t="type"===e?"outputType":e;Array.isArray(r)?i[t]=r.map((e=>a(e))):i[t]=a(r)}return i};return a(e)},Yr=e=>f(e)&&"operator"in e&&"children"in e&&Array.isArray(e.children),Xr=(e,r,t=2)=>{const a=r.getOperators(),n=r.getFragments(),i=r.getCustomFunctions(),o=r.getOptions().fragments,l=a.map((e=>[e.name,...e.aliases])).flat(),u=n.map((e=>e.name)),c=i.map((e=>e.name)),p=new Set([...l,...u,...c]),d=e=>{if(Array.isArray(e))return e.map((e=>d(e)));if(!f(e))return e;const{operator:n,fragment:i,...l}=e;if(!n&&!i)return Object.fromEntries(Object.entries(e).map((([e,r])=>[e,d(r)])));if(n&&Array.isArray(l.children)){const e=s(n),t=a.find((r=>r.name===e||r.aliases.includes(e)));if(t){const e=t.parseChildren({...l,operator:n},r.getConfig());return delete e.children,d(e)}}const u=c.includes(n);i&&l?.parameters&&(Object.entries(l.parameters).forEach((([e,r])=>{l[e]=r})),delete l.parameters);const h=u?n:tt(n,a),m=`$${h??i}`,y=i?at(i,o):[],g=Object.keys(l).filter((e=>rt(e,p)&&!y.includes(e))),v=Object.entries(l).filter((([e])=>!g.includes(e)&&!y.includes(e))).map((([e,r])=>[e,d(r)])),b=Object.fromEntries(g.map((e=>[e,d(l[e])]))),T=Object.fromEntries(y.map((e=>[e,d(l[e])])));switch(!0){case Object.keys(T).length>0:return{[m]:T,...b};case u:return 1!==v.length||"input"in l?{[m]:Object.fromEntries(v),...b}:{[m]:v[0][1]};case Kr(n,l,a):return 1===v.length?{[m]:v[0][1]}:{[m]:Object.fromEntries(v),...b};case"match"===h:return{[m]:Object.fromEntries(v),...b};case v.length>t||!!i||v.some((([e])=>"useCache"===e||"outputType"===e))||v.some((e=>Array.isArray(e[1]))):return{[m]:Object.fromEntries(v),...b};case 1===v.length:return{[m]:v[0][1],...b};default:return{[m]:Zr(s(n),v,a),...b}}};return d(e)},Zr=(e,r,t)=>{const a=t.find((r=>r.name===e||r.aliases.includes(e)));if(!a)throw new Error("Invalid operator: "+e);const s=[];switch(a.name){case"OBJECT_PROPERTIES":{if(et("additionalData",r,a.parameters))return Object.fromEntries(r);const e=et("property",r,a.parameters);if(!e)throw new Error("Missing required property for operator $getData: property");const t=r.find((([e])=>"fallback"===e));return t?[e[1],t[1]]:e[1]}case"GET":case"POST":case"GRAPHQL":return Object.fromEntries(r);default:{const t=new Set;for(const{name:n,aliases:i,required:o}of a.parameters){const a=[n,...i],l=r.find((([e])=>a.includes(e)));if(void 0===l&&o)throw new Error(`Missing required property for operator ${e}: ${n}`);if(void 0===l)break;s.push(l[1]),t.add(l[0])}if(r.some((([e])=>!t.has(e))))return Object.fromEntries(r)}}return s},Kr=(e,r,t)=>{if(!e)return!1;const a=s(e),n=t.find((e=>e.name===a||e.aliases.includes(a)))?.parameters[0];if(!n)return!1;return!!("array"===n.type||Array.isArray(n.type)&&n.type.includes("array"))&&[n.name,...n.aliases].some((e=>e in r))},et=(e,r,t)=>{const a=t.find((r=>r.name===e));if(!a)return;const s=[a.name,...a.aliases];return r.find((([e])=>s.includes(e)))},rt=(e,r)=>u(e)&&!r.has(e),tt=(e,r)=>{if(!e)return;const t=r.find((r=>e===r.name||r.aliases.includes(s(e))));return t?.aliases.find((e=>/^[A-Za-z_]{2,}$/.test(e)))},at=(e,r={})=>{const t=r[e];if(!t)throw new Error("Fragment referenced in expression that is not defined in FigTree: "+e);const a=JSON.stringify(t).match(/"(\$\w+)"/gm);if(!a)return[];const s=new Set;return a.forEach((e=>s.add(e.replace(/"/g,"")))),Array.from(s)},st=(e,r)=>{const n=r.getOperators(),i=r.getFragments(),o=r.getCustomFunctions(),l=i.map((e=>e.name)),u=o.map((e=>e.name)),c=e=>{if(Array.isArray(e))return e.map((e=>c(e)));if(!f(e))return e;const i=Object.entries(e);if(0===i.length)return e;const o=i[0][0].replace("$",""),d=s(o),h=n.find((e=>e.name===d||e.aliases.includes(d))),m=l.includes(o),y=u.includes(o);if(h){const e=h.aliases[0],s=i[0][1];if(Array.isArray(s)){const t=s.map((e=>c(e))),a=h.parseChildren({operator:e,children:t},r.getConfig());return delete a.children,{...a,...p(i)}}const n=c(s);if(!f(n)||!nt(n,h)||t(n)||a(n)){return{operator:e,[h.parameters[0].name]:n}}return{operator:e,...n,...p(i)}}if(m){const r=c(e[i[0][0]]);if(!f(r))throw new Error("Invalid shorthand Fragment");return{fragment:o,...r,...p(i)}}if(y){const e=o,r=i[0][1],s=c(r);if(!f(s)||t(s)||a(s)){return{operator:e,["args"]:s}}return{operator:e,...s,...p(i)}}return Object.fromEntries(i.map((([e,r])=>[e,c(r)])))},p=e=>{const r=e.slice(1);return Object.fromEntries(r.map((([e,r])=>[e,c(r)])))};return c(e)},nt=(e,r)=>{const t=r.parameters.map((e=>[e.name,...e.aliases])).flat();return Object.keys(e).some((e=>t.includes(e)))};export{Hr as AxiosClient,Mr as FetchClient,C as FigTreeError,Gr as FigTreeEvaluator,Wr as SQLNodePostgres,Jr as SQLite,st as convertFromShorthand,Xr as convertToShorthand,Vr as convertV1ToV2,Br as evaluateExpression,u as isAliasString,E as isFigTreeError,y as isFigTreeExpression,a as isFragmentNode,f as isObject,t as isOperatorNode,Yr as isV1Node,b as preProcessShorthand,s as standardiseOperatorName,o as truncateString};
|