diff --git a/bindings/nodejs/src/policy.rs b/bindings/nodejs/src/policy.rs index 5d3dc156..16873ffb 100644 --- a/bindings/nodejs/src/policy.rs +++ b/bindings/nodejs/src/policy.rs @@ -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, Option>; +type JsonInput<'env> = Either3>; + +fn parse_json_input(env: &Env, input: JsonInput) -> Result { + 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 { + pub fn enhance_graph_trace( + &self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] trace: JsonInput, + ) -> napi::Result { 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) diff --git a/bindings/nodejs/test/workspace-large.spec.ts b/bindings/nodejs/test/workspace-large.spec.ts new file mode 100644 index 00000000..a44c81ae --- /dev/null +++ b/bindings/nodejs/test/workspace-large.spec.ts @@ -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/); + }); +});