fix(nodejs): accept bytes and JSON text in Workspace setDocument, setPolicy and enhanceGraphTrace

Documents with more than one million JSON values were rejected by the object conversion limit, which a two-column decision table reaches at 250,000 rows. Buffers and strings are parsed directly, and objects are converted without that limit.
This commit is contained in:
Stefan
2026-11-19 14:31:03 +01:00
parent c78819de95
commit e6d36b3cbb
2 changed files with 91 additions and 7 deletions
+36 -7
View File
@@ -2,9 +2,10 @@ use std::collections::HashMap;
use std::sync::Arc;
use napi::anyhow::anyhow;
use napi::bindgen_prelude::{FnArgs, FunctionRef};
use napi::bindgen_prelude::{Either3, FnArgs, FunctionRef, Object, Uint8Array};
use napi::Env;
use napi_derive::napi;
use serde::de::DeserializeOwned;
use serde_json::Value;
use zen_engine::policy::PolicyDocument;
@@ -12,6 +13,19 @@ use zen_engine::workspace;
type ResolverRef = FunctionRef<FnArgs<(String, Value)>, Option<String>>;
type JsonInput<'env> = Either3<Uint8Array, String, Object<'env>>;
fn parse_json_input<T: DeserializeOwned>(env: &Env, input: JsonInput) -> Result<T, String> {
match input {
Either3::A(bytes) => serde_json::from_slice(bytes.as_ref()).map_err(|e| e.to_string()),
Either3::B(text) => serde_json::from_str(&text).map_err(|e| e.to_string()),
Either3::C(object) => {
let value: Value = env.from_js_value(object).map_err(|e| e.to_string())?;
serde_json::from_value(value).map_err(|e| e.to_string())
}
}
}
#[napi(object)]
pub struct PolicyChanges {
pub cursor: i64,
@@ -593,16 +607,26 @@ impl Workspace {
}
#[napi]
pub fn set_document(&mut self, path: String, document: Value) -> napi::Result<()> {
pub fn set_document(
&mut self,
env: Env,
path: String,
#[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput,
) -> napi::Result<()> {
let doc: zen_engine::model::DecisionContent =
serde_json::from_value(document).map_err(|e| anyhow!("Invalid document: {e}"))?;
parse_json_input(&env, document).map_err(|e| anyhow!("Invalid document: {e}"))?;
self.inner.set_document(path, doc);
Ok(())
}
#[napi]
pub fn set_policy(&mut self, path: String, document: Value) -> napi::Result<()> {
let doc: PolicyDocument = serde_json::from_value(document)
pub fn set_policy(
&mut self,
env: Env,
path: String,
#[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput,
) -> napi::Result<()> {
let doc: PolicyDocument = parse_json_input(&env, document)
.map_err(|e| anyhow!("Invalid policy document: {e}"))?;
self.inner.set_policy(path, doc);
Ok(())
@@ -981,9 +1005,14 @@ impl Workspace {
}
#[napi(ts_return_type = "PolicyTrace")]
pub fn enhance_graph_trace(&self, path: String, trace: Value) -> napi::Result<Value> {
pub fn enhance_graph_trace(
&self,
env: Env,
path: String,
#[napi(ts_arg_type = "Uint8Array | string | object")] trace: JsonInput,
) -> napi::Result<Value> {
let trace_map: workspace::GraphTraceMap =
serde_json::from_value(trace).map_err(|e| napi::Error::from_reason(e.to_string()))?;
parse_json_input(&env, trace).map_err(napi::Error::from_reason)?;
let result = self
.inner
.enhance_graph_trace(&Arc::from(path.as_str()), &trace_map)
@@ -0,0 +1,55 @@
import { describe, expect, it } from '@jest/globals';
const { Workspace } = require('../index.js');
const lookupTable = (rows: number) => ({
nodes: [
{ id: 'in', name: 'request', type: 'inputNode', content: { schema: '' }, position: { x: 0, y: 0 } },
{
id: 'table',
name: 'lookup',
type: 'decisionTableNode',
position: { x: 300, y: 0 },
content: {
hitPolicy: 'first',
inputs: [{ id: 'code', name: 'Code', field: 'code' }],
outputs: [{ id: 'rate', name: 'Rate', field: 'rate' }],
rules: Array.from({ length: rows }, (_, row) => ({
_id: `r${row}`,
code: `"C${row}"`,
rate: String(row),
})),
passThrough: true,
},
},
{ id: 'out', name: 'response', type: 'outputNode', content: { schema: '' }, position: { x: 600, y: 0 } },
],
edges: [
{ id: 'e1', type: 'edge', sourceId: 'in', targetId: 'table' },
{ id: 'e2', type: 'edge', sourceId: 'table', targetId: 'out' },
],
});
describe('Workspace large documents', () => {
const rows = 300_000;
const content = lookupTable(rows);
const text = JSON.stringify(content);
it.each<[string, () => unknown]>([
['an object', () => content],
['a JSON string', () => text],
['a Buffer', () => Buffer.from(text)],
['a Uint8Array', () => new TextEncoder().encode(text)],
])('loads more than a million JSON values from %s', (_, document) => {
const ws = new Workspace();
ws.setDocument('lookup', document());
expect(ws.isGraph('lookup')).toBe(true);
expect(ws.paths()).toEqual(['lookup']);
expect(ws.inputs({ policyPath: 'lookup' }).map((input: any) => input.path)).toEqual(['code']);
});
it('reports invalid JSON text', () => {
const ws = new Workspace();
expect(() => ws.setDocument('broken', '{ "nodes": ')).toThrow(/Invalid document/);
});
});