feat(wasm): use JsValue (JS objects) at the boundary instead of JSON strings
public
feat(wasm): use JsValue (JS objects) at the boundary instead of JSON strings
evaluate/evaluate_strict now take the context as a native JS object and
return a native JS value, bridging JsValue <-> serde_json::Value with
serde-wasm-bindgen and reusing the existing recursive mappers. Errors are
thrown as JS exceptions (idiomatic wasm-bindgen) rather than returned as
{error} objects. feel-core stays free of JSON/wasm knowledge.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
| Changeset | 1010cad66ea7f8843a0227a4e6c4dca589502730 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@gmail.com>, |
| Parents | 541814fd5e34 |
| Children | |
| Pushlog | by timo via ssh |
modified Cargo.lock +13 −0
| @@ -520,6 +520,8 @@ | ||
| 520 | 520 | version = "0.1.0" |
| 521 | 521 | dependencies = [ |
| 522 | 522 | "feel-core", |
| 523 | + "serde", | |
| 524 | + "serde-wasm-bindgen", | |
| 523 | 525 | "serde_json", |
| 524 | 526 | "wasm-bindgen", |
| 525 | 527 | ] |
| @@ -1502,6 +1504,17 @@ | ||
| 1502 | 1504 | dependencies = [ |
| 1503 | 1505 | "serde_core", |
| 1504 | 1506 | "serde_derive", |
| 1507 | +] | |
| 1508 | + | |
| 1509 | +[[package]] | |
| 1510 | +name = "serde-wasm-bindgen" | |
| 1511 | +version = "0.6.5" | |
| 1512 | +source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1513 | +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" | |
| 1514 | +dependencies = [ | |
| 1515 | + "js-sys", | |
| 1516 | + "serde", | |
| 1517 | + "wasm-bindgen", | |
| 1505 | 1518 | ] |
| 1506 | 1519 | |
| 1507 | 1520 | [[package]] |
modified README.md +15 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | ```text |
| 10 | 10 | crates/feel-core pure engine (lalrpop grammar + AST + evaluator); no target deps |
| 11 | 11 | crates/feel-pg pgrx wrapper: feel_eval(text, jsonb) RETURNS jsonb |
| 12 | -crates/feel-wasm wasm-bindgen wrapper: evaluate(expr, context_json) -> JSON string | |
| 12 | +crates/feel-wasm wasm-bindgen wrapper: evaluate(expr, context) -> JS value | |
| 13 | 13 | tools/ingest_tck.py DMN-TCK literal-expression -> feel-core fixture (with deviations) |
| 14 | 14 | ``` |
| 15 | 15 | |
| @@ -166,6 +166,20 @@ | ||
| 166 | 166 | node crates/feel-wasm/smoke.mjs # one line per case, then "smoke test passed" |
| 167 | 167 | ``` |
| 168 | 168 | |
| 169 | +The context is a native JS object and the result is a native JS value (no JSON | |
| 170 | +strings). Parse/eval errors throw; `evaluate_strict` also throws on a null that | |
| 171 | +arose from a type/domain error. | |
| 172 | + | |
| 173 | +```js | |
| 174 | +import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js"; | |
| 175 | + | |
| 176 | +evaluate("1 + 1", {}); // => 2 | |
| 177 | +evaluate("person.age", { person: { age: 42 } }); // => 42 | |
| 178 | +evaluate("{a: 1, b: a + 1}", {}); // => { a: 1, b: 2 } | |
| 179 | +evaluate("1 + true", {}); // => null (lenient) | |
| 180 | +evaluate_strict("1 + true", {}); // throws (strict) | |
| 181 | +``` | |
| 182 | + | |
| 169 | 183 | Compile-only check without wasm-pack: |
| 170 | 184 | |
| 171 | 185 | ```sh |
modified crates/feel-wasm/Cargo.toml +2 −0
| @@ -10,5 +10,7 @@ | ||
| 10 | 10 | |
| 11 | 11 | [dependencies] |
| 12 | 12 | wasm-bindgen = "0.2" |
| 13 | +serde-wasm-bindgen = "0.6" | |
| 14 | +serde = { version = "1", features = ["derive"] } | |
| 13 | 15 | serde_json.workspace = true |
| 14 | 16 | feel-core = { path = "../feel-core" } |
modified crates/feel-wasm/smoke.mjs +32 −21
| @@ -16,42 +16,53 @@ | ||
| 16 | 16 | |
| 17 | 17 | import { evaluate, evaluate_strict } from "./pkg/feel_wasm.js"; |
| 18 | 18 | |
| 19 | -// [expression, context-json, expected-json]. These mirror the feel-core and | |
| 20 | -// feel-pg tests, demonstrating "same core, same result" across all three | |
| 21 | -// targets. | |
| 19 | +// [expression, context-object, expected-value]. The context is a native JS | |
| 20 | +// object and the result is a native JS value (no JSON strings). These mirror the | |
| 21 | +// feel-core and feel-pg tests, demonstrating "same core, same result" across all | |
| 22 | +// three targets. | |
| 22 | 23 | const cases = [ |
| 23 | - ["1 + 1", "{}", "2"], | |
| 24 | - ["5 in [1..10]", "{}", "true"], | |
| 25 | - ["if 1 < 2 then 10 else 20", "{}", "10"], | |
| 26 | - ["for i in [1,2,3] return i + 1", "{}", "[2,3,4]"], | |
| 27 | - ['"apple" < "banana"', "{}", "true"], | |
| 28 | - // Context literal -> JSON object, and path access into a nested input context. | |
| 29 | - ["{a: 1, b: a + 1}", "{}", '{"a":1,"b":2}'], | |
| 30 | - ["person.age", '{"person": {"age": 42}}', "42"], | |
| 24 | + ["1 + 1", {}, 2], | |
| 25 | + ["5 in [1..10]", {}, true], | |
| 26 | + ["if 1 < 2 then 10 else 20", {}, 10], | |
| 27 | + ["for i in [1,2,3] return i + 1", {}, [2, 3, 4]], | |
| 28 | + ['"apple" < "banana"', {}, true], | |
| 29 | + // Context literal -> JS object, and path access into a nested input context. | |
| 30 | + ["{a: 1, b: a + 1}", {}, { a: 1, b: 2 }], | |
| 31 | + ["person.age", { person: { age: 42 } }, 42], | |
| 31 | 32 | ]; |
| 33 | + | |
| 34 | +const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b); | |
| 32 | 35 | |
| 33 | 36 | let ok = true; |
| 34 | 37 | for (const [expr, ctx, expected] of cases) { |
| 35 | 38 | const got = evaluate(expr, ctx); |
| 36 | - console.log(`${expr} => ${got}`); | |
| 37 | - if (got !== expected) { | |
| 39 | + console.log(`${expr} => ${JSON.stringify(got)}`); | |
| 40 | + if (!eq(got, expected)) { | |
| 38 | 41 | console.error(`FAIL: expected ${JSON.stringify(expected)}, got ${JSON.stringify(got)}`); |
| 39 | 42 | ok = false; |
| 40 | 43 | } |
| 41 | 44 | } |
| 42 | 45 | |
| 43 | 46 | // Boundary policy (ADR-14): a type error is a lenient `null`, but `evaluate_strict` |
| 44 | -// surfaces it as an {"error": ...} object instead of letting it pass silently. | |
| 47 | +// surfaces it as a thrown exception instead of letting it pass silently as `null`. | |
| 48 | +const threw = (fn) => { | |
| 49 | + try { | |
| 50 | + fn(); | |
| 51 | + return false; | |
| 52 | + } catch { | |
| 53 | + return true; | |
| 54 | + } | |
| 55 | +}; | |
| 56 | + | |
| 45 | 57 | const strictCases = [ |
| 46 | - ["1 + true", "{}", "null", true], // lenient: null; strict: error | |
| 47 | - ["null", "{}", "null", false], // a genuine value-null is fine even in strict | |
| 58 | + ["1 + true", {}, null, true], // lenient: null; strict: throws | |
| 59 | + ["null", {}, null, false], // a genuine value-null is fine even in strict | |
| 48 | 60 | ]; |
| 49 | -for (const [expr, ctx, expectedLenient, expectStrictError] of strictCases) { | |
| 61 | +for (const [expr, ctx, expectedLenient, expectStrictThrow] of strictCases) { | |
| 50 | 62 | const lenient = evaluate(expr, ctx); |
| 51 | - const strict = evaluate_strict(expr, ctx); | |
| 52 | - console.log(`${expr} => lenient ${lenient} | strict ${strict}`); | |
| 53 | - const strictIsError = strict.includes('"error"'); | |
| 54 | - if (lenient !== expectedLenient || strictIsError !== expectStrictError) { | |
| 63 | + const strictThrew = threw(() => evaluate_strict(expr, ctx)); | |
| 64 | + console.log(`${expr} => lenient ${JSON.stringify(lenient)} | strict throws: ${strictThrew}`); | |
| 65 | + if (!eq(lenient, expectedLenient) || strictThrew !== expectStrictThrow) { | |
| 55 | 66 | console.error(`FAIL: ${expr} lenient/strict mismatch`); |
| 56 | 67 | ok = false; |
| 57 | 68 | } |
modified crates/feel-wasm/src/lib.rs +35 −26
| @@ -1,48 +1,57 @@ | ||
| 1 | 1 | //! WASM wrapper for `feel-core`, built with wasm-bindgen. |
| 2 | 2 | //! |
| 3 | -//! Exposes `evaluate(expr, context_json) -> String`, returning the result as a | |
| 4 | -//! JSON string. The JSON boundary mapping lives here (not in `feel-core`), per | |
| 5 | -//! the project's boundary-mapping decision. | |
| 3 | +//! Exposes `evaluate(expr, context) -> JsValue`, taking the context as a native | |
| 4 | +//! JS object and returning the result as a native JS value. The boundary mapping | |
| 5 | +//! lives here (not in `feel-core`), per the project's boundary-mapping decision: | |
| 6 | +//! `JsValue` is bridged to `serde_json::Value` with `serde-wasm-bindgen`, then to | |
| 7 | +//! `feel-core`'s [`Value`] by the existing recursive helpers. | |
| 6 | 8 | |
| 7 | 9 | use feel_core::{evaluate as core_evaluate, Context, Value}; |
| 10 | +use serde::Serialize; | |
| 8 | 11 | use wasm_bindgen::prelude::*; |
| 9 | 12 | |
| 10 | 13 | /// Evaluate a FEEL expression (lenient boundary policy). |
| 11 | 14 | /// |
| 12 | -/// `context_json` is a JSON object string (e.g. `"{}"`). The result is returned | |
| 13 | -/// as a JSON string. On error, a JSON object `{"error": "..."}` is returned so | |
| 14 | -/// the JS side never has to deal with thrown exceptions for plain eval errors. | |
| 15 | -/// A null arising from a type/domain error is emitted as plain JSON `null` (the | |
| 16 | -/// spec-shaped result); see `evaluate_strict` to surface such errors instead. | |
| 15 | +/// `context` is a native JS object (e.g. `{}`); `undefined`/`null` is treated as | |
| 16 | +/// an empty context. The result is returned as a native JS value. Parse and eval | |
| 17 | +/// errors are thrown as JS exceptions. A null arising from a type/domain error is | |
| 18 | +/// returned as plain `null` (the spec-shaped result); see `evaluate_strict` to | |
| 19 | +/// surface such errors as a thrown exception instead. | |
| 17 | 20 | #[wasm_bindgen] |
| 18 | -pub fn evaluate(expr: &str, context_json: &str) -> String { | |
| 19 | - match eval_value(expr, context_json) { | |
| 20 | - Ok(value) => value_to_json(&value).to_string(), | |
| 21 | - Err(message) => serde_json::json!({ "error": message }).to_string(), | |
| 22 | - } | |
| 21 | +pub fn evaluate(expr: &str, context: JsValue) -> Result<JsValue, JsError> { | |
| 22 | + let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?; | |
| 23 | + to_js(&value_to_json(&value)) | |
| 23 | 24 | } |
| 24 | 25 | |
| 25 | 26 | /// Evaluate a FEEL expression (strict boundary policy): if the result is, or |
| 26 | -/// contains, a null that arose from a type/domain error, return | |
| 27 | -/// `{"error": "..."}` instead of letting the error pass silently as `null` | |
| 28 | -/// (ADR-14). A plain (value) null is still returned as `null`. | |
| 27 | +/// contains, a null that arose from a type/domain error, throw instead of letting | |
| 28 | +/// the error pass silently as `null` (ADR-14). A plain (value) null is still | |
| 29 | +/// returned as `null`. | |
| 29 | 30 | #[wasm_bindgen] |
| 30 | -pub fn evaluate_strict(expr: &str, context_json: &str) -> String { | |
| 31 | - match eval_value(expr, context_json) { | |
| 32 | - Ok(value) if value.contains_error() => serde_json::json!({ | |
| 33 | - "error": "evaluation produced a null from a type or domain error" | |
| 34 | - }) | |
| 35 | - .to_string(), | |
| 36 | - Ok(value) => value_to_json(&value).to_string(), | |
| 37 | - Err(message) => serde_json::json!({ "error": message }).to_string(), | |
| 31 | +pub fn evaluate_strict(expr: &str, context: JsValue) -> Result<JsValue, JsError> { | |
| 32 | + let value = eval_value(expr, context).map_err(|m| JsError::new(&m))?; | |
| 33 | + if value.contains_error() { | |
| 34 | + return Err(JsError::new( | |
| 35 | + "evaluation produced a null from a type or domain error", | |
| 36 | + )); | |
| 38 | 37 | } |
| 38 | + to_js(&value_to_json(&value)) | |
| 39 | 39 | } |
| 40 | 40 | |
| 41 | -fn eval_value(expr: &str, context_json: &str) -> Result<Value, String> { | |
| 41 | +fn eval_value(expr: &str, context: JsValue) -> Result<Value, String> { | |
| 42 | 42 | let parsed: serde_json::Value = |
| 43 | - serde_json::from_str(context_json).map_err(|e| format!("invalid context JSON: {e}"))?; | |
| 43 | + serde_wasm_bindgen::from_value(context).map_err(|e| format!("invalid context: {e}"))?; | |
| 44 | 44 | let ctx = context_from_json(&parsed)?; |
| 45 | 45 | core_evaluate(expr, &ctx).map_err(|e| e.to_string()) |
| 46 | +} | |
| 47 | + | |
| 48 | +/// Serialize a JSON value to a native `JsValue`. The `json_compatible` serializer | |
| 49 | +/// maps objects to plain JS objects (not `Map`); integral numbers stay JS numbers. | |
| 50 | +fn to_js(value: &serde_json::Value) -> Result<JsValue, JsError> { | |
| 51 | + let serializer = serde_wasm_bindgen::Serializer::json_compatible(); | |
| 52 | + value | |
| 53 | + .serialize(&serializer) | |
| 54 | + .map_err(|e| JsError::new(&e.to_string())) | |
| 46 | 55 | } |
| 47 | 56 | |
| 48 | 57 | /// Map a `feel-core` [`Value`] to a JSON value for the string boundary. |