@math.gl/expressions 4.2.0-alpha.5

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.
Files changed (42) hide show
  1. package/LICENSE +140 -0
  2. package/README.md +12 -0
  3. package/dist/dggs.cjs +54 -0
  4. package/dist/dggs.cjs.map +6 -0
  5. package/dist/dggs.d.ts +18 -0
  6. package/dist/dggs.d.ts.map +1 -0
  7. package/dist/dggs.js +42 -0
  8. package/dist/dggs.js.map +1 -0
  9. package/dist/expression-eval.d.ts +103 -0
  10. package/dist/expression-eval.d.ts.map +1 -0
  11. package/dist/expression-eval.js +298 -0
  12. package/dist/expression-eval.js.map +1 -0
  13. package/dist/function-libraries.d.ts +75 -0
  14. package/dist/function-libraries.d.ts.map +1 -0
  15. package/dist/function-libraries.js +98 -0
  16. package/dist/function-libraries.js.map +1 -0
  17. package/dist/function-registry.d.ts +93 -0
  18. package/dist/function-registry.d.ts.map +1 -0
  19. package/dist/function-registry.js +131 -0
  20. package/dist/function-registry.js.map +1 -0
  21. package/dist/get.d.ts +9 -0
  22. package/dist/get.d.ts.map +1 -0
  23. package/dist/get.js +32 -0
  24. package/dist/get.js.map +1 -0
  25. package/dist/index.cjs +473 -0
  26. package/dist/index.cjs.map +6 -0
  27. package/dist/index.d.ts +7 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +8 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/parse-expression-string.d.ts +21 -0
  32. package/dist/parse-expression-string.d.ts.map +1 -0
  33. package/dist/parse-expression-string.js +61 -0
  34. package/dist/parse-expression-string.js.map +1 -0
  35. package/package.json +50 -0
  36. package/src/dggs.ts +62 -0
  37. package/src/expression-eval.ts +426 -0
  38. package/src/function-libraries.ts +168 -0
  39. package/src/function-registry.ts +163 -0
  40. package/src/get.ts +37 -0
  41. package/src/index.ts +26 -0
  42. package/src/parse-expression-string.ts +80 -0
@@ -0,0 +1,168 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return */
5
+
6
+ import {
7
+ acos,
8
+ asin,
9
+ atan,
10
+ clamp,
11
+ cos,
12
+ degrees,
13
+ lerp,
14
+ normalizeAngle,
15
+ radians,
16
+ safeMod,
17
+ sin,
18
+ tan,
19
+ toDegrees,
20
+ toRadians
21
+ } from '@math.gl/core';
22
+ import {Ellipsoid, isWGS84} from '@math.gl/geospatial';
23
+ import type {ExpressionFunctionRegistry} from './function-registry';
24
+
25
+ /**
26
+ * A function that can be exposed to evaluated expressions.
27
+ *
28
+ * @param args - Arguments supplied by a call expression.
29
+ * @returns The value made available to the expression.
30
+ */
31
+ export type ExpressionFunction = (...args: any[]) => any;
32
+
33
+ /**
34
+ * A named collection of functions that can be supplied to an expression
35
+ * evaluator through {@link ExpressionEvaluationOptions}.
36
+ */
37
+ export type ExpressionFunctionLibrary = Record<string, ExpressionFunction>;
38
+
39
+ /**
40
+ * Options shared by the synchronous and asynchronous expression evaluators.
41
+ */
42
+ export type ExpressionEvaluationOptions = {
43
+ /**
44
+ * Instance-scoped registry of named functions available to the expression.
45
+ */
46
+ registry?: ExpressionFunctionRegistry;
47
+
48
+ /**
49
+ * Function libraries to add to the evaluation context.
50
+ *
51
+ * Libraries are merged from left to right. Functions in later libraries
52
+ * replace functions with the same name in earlier libraries. Values in the
53
+ * expression context replace functions with the same name in any library.
54
+ */
55
+ libraries?: ExpressionFunctionLibrary[];
56
+ };
57
+
58
+ /**
59
+ * General-purpose mathematical functions for expression evaluation.
60
+ *
61
+ * Includes JavaScript `Math` functions and math.gl helpers such as `clamp`,
62
+ * `lerp`, `normalizeAngle`, `safeMod`, `toDegrees`, and `toRadians`.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * const evaluate = compile("clamp(sin(angle), 0, 1)", {
67
+ * libraries: [BASIC_MATH_FUNCTION_LIBRARY]
68
+ * });
69
+ * evaluate({angle: Math.PI / 2});
70
+ * ```
71
+ */
72
+ export const BASIC_MATH_FUNCTION_LIBRARY: ExpressionFunctionLibrary = {
73
+ abs: Math.abs,
74
+ acos,
75
+ asin,
76
+ atan,
77
+ ceil: Math.ceil,
78
+ clamp,
79
+ cos,
80
+ degrees,
81
+ exp: Math.exp,
82
+ floor: Math.floor,
83
+ lerp,
84
+ log: Math.log,
85
+ max: Math.max,
86
+ min: Math.min,
87
+ normalizeAngle,
88
+ pow: Math.pow,
89
+ radians,
90
+ round: Math.round,
91
+ safeMod,
92
+ sign: Math.sign,
93
+ sin,
94
+ sqrt: Math.sqrt,
95
+ tan,
96
+ toDegrees,
97
+ toRadians,
98
+ trunc: Math.trunc
99
+ };
100
+
101
+ /**
102
+ * WGS84 ellipsoid functions for expression evaluation.
103
+ *
104
+ * Includes cartographic and Cartesian coordinate conversion, surface
105
+ * projection, local east-north-up frame generation, and WGS84 inspection.
106
+ * Angular arguments use radians unless the selected function states otherwise.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * const evaluate = compile("cartographicToCartesian(position)", {
111
+ * libraries: [GEOSPATIAL_FUNCTION_LIBRARY]
112
+ * });
113
+ * evaluate({position: [0, 0, 0]});
114
+ * ```
115
+ */
116
+ export const GEOSPATIAL_FUNCTION_LIBRARY: ExpressionFunctionLibrary = {
117
+ cartesianToCartographic: (cartesian: number[], result?: number[]) =>
118
+ Ellipsoid.WGS84.cartesianToCartographic(cartesian, result),
119
+ cartographicToCartesian: (cartographic: number[], result?: number[]) =>
120
+ Ellipsoid.WGS84.cartographicToCartesian(cartographic, result),
121
+ eastNorthUpToFixedFrame: (origin: number[], result?: number[]) =>
122
+ Ellipsoid.WGS84.eastNorthUpToFixedFrame(origin, result),
123
+ geodeticSurfaceNormal: (cartesian: number[], result?: number[]) =>
124
+ Ellipsoid.WGS84.geodeticSurfaceNormal(cartesian, result),
125
+ geodeticSurfaceNormalCartographic: (cartographic: number[], result?: number[]) =>
126
+ Ellipsoid.WGS84.geodeticSurfaceNormalCartographic(cartographic, result),
127
+ isWGS84,
128
+ scaleToGeocentricSurface: (cartesian: number[], result?: number[]) =>
129
+ Ellipsoid.WGS84.scaleToGeocentricSurface(cartesian, result),
130
+ scaleToGeodeticSurface: (cartesian: number[], result?: number[]) =>
131
+ Ellipsoid.WGS84.scaleToGeodeticSurface(cartesian, result),
132
+ toDegrees,
133
+ toRadians,
134
+ transformPositionFromScaledSpace: (position: number[], result?: number[]) =>
135
+ Ellipsoid.WGS84.transformPositionFromScaledSpace(position, result),
136
+ transformPositionToScaledSpace: (position: number[], result?: number[]) =>
137
+ Ellipsoid.WGS84.transformPositionToScaledSpace(position, result)
138
+ };
139
+
140
+ /**
141
+ * Adds configured function libraries to an expression context.
142
+ *
143
+ * @param context - Values available to the expression.
144
+ * @param options - Function libraries to merge into the context.
145
+ * @returns The original context when no libraries are supplied, or a new
146
+ * context containing the libraries and context values.
147
+ *
148
+ * @remarks
149
+ * Libraries are merged from left to right, then overlaid with `context`.
150
+ * Registry functions have the lowest precedence. The input objects are not modified.
151
+ */
152
+ export function mergeFunctionLibraries(
153
+ context: Record<string, unknown>,
154
+ options?: ExpressionEvaluationOptions
155
+ ): Record<string, unknown> {
156
+ if (!options?.libraries?.length) {
157
+ if (!options?.registry) {
158
+ return context;
159
+ }
160
+ }
161
+
162
+ return Object.assign(
163
+ {},
164
+ options.registry?.getFunctionTable(),
165
+ ...(options.libraries || []),
166
+ context
167
+ );
168
+ }
@@ -0,0 +1,163 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {ExpressionFunction, ExpressionFunctionLibrary} from './function-libraries';
6
+
7
+ const FUNCTION_NAME_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
8
+ const DISALLOWED_FUNCTION_NAMES = new Set(['__proto__', 'prototype', 'constructor']);
9
+
10
+ /**
11
+ * Options for registering functions with an {@link ExpressionFunctionRegistry}.
12
+ */
13
+ export type FunctionRegistrationOptions = {
14
+ /**
15
+ * Replace an existing function with the same name.
16
+ *
17
+ * @defaultValue false
18
+ */
19
+ replace?: boolean;
20
+ };
21
+
22
+ /**
23
+ * An isolated collection of named functions available to expression evaluators.
24
+ *
25
+ * @remarks
26
+ * Registries are instance scoped. Registering a function does not affect other
27
+ * registries or evaluators that do not receive the registry.
28
+ *
29
+ * Function names must be valid JavaScript-style identifiers so they can be
30
+ * called directly from JSEP expressions.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * const registry = new ExpressionFunctionRegistry()
35
+ * .registerFunction('double', (value) => value * 2)
36
+ * .registerFunctions(BASIC_MATH_FUNCTION_LIBRARY);
37
+ *
38
+ * const evaluate = compile('double(round(value))', {registry});
39
+ * evaluate({value: 2.4});
40
+ * ```
41
+ */
42
+ export class ExpressionFunctionRegistry {
43
+ private readonly functions = Object.create(null) as ExpressionFunctionLibrary;
44
+
45
+ /**
46
+ * Creates a function registry.
47
+ *
48
+ * @param functionTables - Function tables to register in order.
49
+ * @throws If a table contains an invalid or duplicate function name.
50
+ */
51
+ constructor(functionTables: readonly ExpressionFunctionLibrary[] = []) {
52
+ for (const functionTable of functionTables) {
53
+ this.registerFunctions(functionTable);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Registers one named function.
59
+ *
60
+ * @param name - Identifier used to call the function from an expression.
61
+ * @param fn - JavaScript function invoked with evaluated expression arguments.
62
+ * @param options - Duplicate registration behavior.
63
+ * @returns This registry.
64
+ * @throws If the name is invalid, the value is not a function, or the name is
65
+ * already registered and replacement was not requested.
66
+ */
67
+ registerFunction(
68
+ name: string,
69
+ fn: ExpressionFunction,
70
+ options: FunctionRegistrationOptions = {}
71
+ ): this {
72
+ validateFunction(name, fn);
73
+ if (this.hasFunction(name) && !options.replace) {
74
+ throw new Error(`Expression function "${name}" is already registered.`);
75
+ }
76
+ this.functions[name] = fn;
77
+ return this;
78
+ }
79
+
80
+ /**
81
+ * Registers all entries in a function table.
82
+ *
83
+ * @param functionTable - Map from expression identifiers to JavaScript functions.
84
+ * @param options - Duplicate registration behavior.
85
+ * @returns This registry.
86
+ * @throws If any entry is invalid or conflicts with an existing registration.
87
+ *
88
+ * @remarks
89
+ * Validation is atomic: no entries are registered when any entry is invalid.
90
+ */
91
+ registerFunctions(
92
+ functionTable: ExpressionFunctionLibrary,
93
+ options: FunctionRegistrationOptions = {}
94
+ ): this {
95
+ const entries = Object.entries(functionTable);
96
+ const names = new Set<string>();
97
+
98
+ for (const [name, fn] of entries) {
99
+ validateFunction(name, fn);
100
+ if (names.has(name) || (this.hasFunction(name) && !options.replace)) {
101
+ throw new Error(`Expression function "${name}" is already registered.`);
102
+ }
103
+ names.add(name);
104
+ }
105
+
106
+ for (const [name, fn] of entries) {
107
+ this.functions[name] = fn;
108
+ }
109
+ return this;
110
+ }
111
+
112
+ /**
113
+ * Removes a registered function.
114
+ *
115
+ * @param name - Function name to remove.
116
+ * @returns `true` when a function was removed.
117
+ */
118
+ unregisterFunction(name: string): boolean {
119
+ if (!this.hasFunction(name)) {
120
+ return false;
121
+ }
122
+ return delete this.functions[name];
123
+ }
124
+
125
+ /**
126
+ * Tests whether a function is registered.
127
+ *
128
+ * @param name - Function name to inspect.
129
+ * @returns `true` when the registry contains the name.
130
+ */
131
+ hasFunction(name: string): boolean {
132
+ return Object.prototype.hasOwnProperty.call(this.functions, name);
133
+ }
134
+
135
+ /**
136
+ * Returns a registered function.
137
+ *
138
+ * @param name - Function name to retrieve.
139
+ * @returns The registered function, or `undefined`.
140
+ */
141
+ getFunction(name: string): ExpressionFunction | undefined {
142
+ return this.functions[name];
143
+ }
144
+
145
+ /**
146
+ * Returns an immutable snapshot of all registered functions.
147
+ *
148
+ * @returns A frozen function table.
149
+ */
150
+ getFunctionTable(): Readonly<ExpressionFunctionLibrary> {
151
+ return Object.freeze({...this.functions});
152
+ }
153
+ }
154
+
155
+ /** Validates one registry entry. */
156
+ function validateFunction(name: string, fn: ExpressionFunction): void {
157
+ if (!FUNCTION_NAME_PATTERN.test(name) || DISALLOWED_FUNCTION_NAMES.has(name)) {
158
+ throw new Error(`Invalid expression function name "${name}".`);
159
+ }
160
+ if (typeof fn !== 'function') {
161
+ throw new TypeError(`Expression function "${name}" must be a function.`);
162
+ }
163
+ }
package/src/get.ts ADDED
@@ -0,0 +1,37 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ /**
6
+ * Access properties of nested containers using dot-path notation.
7
+ *
8
+ * @param container - Object from which to read a value.
9
+ * @param compositeKey - Dot-separated property path.
10
+ * @returns The nested value, or `undefined` when the path cannot be resolved.
11
+ */
12
+ export function get(container: Record<string, unknown>, compositeKey: string): unknown {
13
+ let value: unknown = container;
14
+
15
+ for (const key of getKeys(compositeKey)) {
16
+ value = isObject(value) ? value[key] : undefined;
17
+ }
18
+
19
+ return value;
20
+ }
21
+
22
+ /** Tests whether a value can be used for property access. */
23
+ function isObject(value: unknown): value is Record<string, unknown> {
24
+ return value !== null && typeof value === 'object';
25
+ }
26
+
27
+ const keyMap: Record<string, string[]> = {};
28
+
29
+ /** Returns a cached list of property names for a dot-separated path. */
30
+ function getKeys(compositeKey: string): string[] {
31
+ let keyList = keyMap[compositeKey];
32
+ if (!keyList) {
33
+ keyList = compositeKey.split('.');
34
+ keyMap[compositeKey] = keyList;
35
+ }
36
+ return keyList;
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ export type {
6
+ ExpressionEvaluationOptions,
7
+ ExpressionFunction,
8
+ ExpressionFunctionLibrary
9
+ } from './function-libraries';
10
+ export {ExpressionFunctionRegistry, type FunctionRegistrationOptions} from './function-registry';
11
+ export type {BinaryOperator, Expression, ExpressionContext, UnaryOperator} from './expression-eval';
12
+ export {
13
+ addBinaryOp,
14
+ addUnaryOp,
15
+ compile,
16
+ compileAsync,
17
+ eval,
18
+ evalAsync,
19
+ parse
20
+ } from './expression-eval';
21
+ export {
22
+ BASIC_MATH_FUNCTION_LIBRARY,
23
+ GEOSPATIAL_FUNCTION_LIBRARY,
24
+ mergeFunctionLibraries
25
+ } from './function-libraries';
26
+ export {parseExpressionString, type AccessorFunction} from './parse-expression-string';
@@ -0,0 +1,80 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type jsep from 'jsep';
6
+ import {eval as evaluate, parse} from './expression-eval';
7
+ import {get} from './get';
8
+
9
+ /**
10
+ * An accessor compiled from a JSON-style expression string.
11
+ *
12
+ * @param row - Data object against which the expression is evaluated.
13
+ * @returns The value produced by the expression.
14
+ */
15
+ export type AccessorFunction = (row: Record<string, unknown>) => unknown;
16
+
17
+ const cachedExpressionMap: Record<string, AccessorFunction> = {
18
+ '-': object => object
19
+ };
20
+
21
+ /**
22
+ * Compiles a JSON-style expression string into an accessor function.
23
+ *
24
+ * @param propValue - Accessor expression to compile.
25
+ * @returns A cached accessor function.
26
+ * @throws If the expression is invalid or contains a function call.
27
+ *
28
+ * @remarks
29
+ * `-` maps to the identity accessor and `a.b.c` maps to nested property
30
+ * access. Function calls are rejected so accessors cannot execute functions
31
+ * supplied by input data.
32
+ */
33
+ export function parseExpressionString(propValue: string): AccessorFunction {
34
+ if (propValue in cachedExpressionMap) {
35
+ return cachedExpressionMap[propValue];
36
+ }
37
+
38
+ const ast = parse(propValue);
39
+ const func =
40
+ ast.type === 'Identifier'
41
+ ? (row: Record<string, unknown>) => get(row, propValue)
42
+ : compileAst(ast);
43
+
44
+ cachedExpressionMap[propValue] = func;
45
+ return func;
46
+ }
47
+
48
+ /** Validates and compiles a parsed accessor expression. */
49
+ function compileAst(ast: jsep.Expression): AccessorFunction {
50
+ traverse(ast, node => {
51
+ if (node.type === 'CallExpression') {
52
+ throw new Error('Function calls not allowed in expression accessors');
53
+ }
54
+ });
55
+
56
+ return (row: Record<string, unknown>) => evaluate(ast, row);
57
+ }
58
+
59
+ /** Visits each AST-like object in a parsed expression. */
60
+ // eslint-disable-next-line complexity
61
+ function traverse(node: unknown, visitor: (node: {type: string}) => void): void {
62
+ if (Array.isArray(node)) {
63
+ node.forEach(element => traverse(element, visitor));
64
+ return;
65
+ }
66
+
67
+ if (node && typeof node === 'object') {
68
+ if (isNodeLike(node)) {
69
+ visitor(node);
70
+ }
71
+ for (const key in node) {
72
+ traverse((node as Record<string, unknown>)[key], visitor);
73
+ }
74
+ }
75
+ }
76
+
77
+ /** Tests whether an object resembles a JSEP AST node. */
78
+ function isNodeLike(node: object): node is {type: string} {
79
+ return 'type' in node && typeof (node as {type?: unknown}).type === 'string';
80
+ }