@nodora/js 0.3.0 → 0.4.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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Nodora
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nodora
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # @nodora/js
2
-
1
+ # @nodora/js
2
+
3
3
  JS bindings for the Nodora rule engine. This library allows you to compile and evaluate Nodora rules.
package/lib/index.d.ts CHANGED
@@ -1,95 +1,128 @@
1
- export type EmittedSignal = {
2
- name: string;
3
- args: any[];
4
- };
5
-
6
- export type EvaluationResult = {
7
- outputs: Record<string, any>;
8
- emitted_signals: EmittedSignal[];
9
- };
10
-
11
- /**
12
- * A compiled Nodora ruleset, as returned by compile().
13
- */
14
- export type Ruleset = Record<string, any>;
15
-
16
- export interface Evaluator {
17
- /**
18
- * Get evaluator id
19
- */
20
- getId(): number;
21
-
22
- /**
23
- * Register a callback for a signal
24
- * @param signalName - Name of the signal to listen for
25
- * @param callback - Callback function to invoke when signal is emitted
26
- * @returns Evaluator instance for chaining
27
- */
28
- on(signalName: string, callback: (...args: any[]) => void): Evaluator;
29
-
30
- /**
31
- * Evaluates a rule with the given input
32
- * @param ruleName - Name of the rule to evaluate
33
- * @param input - Input values for the rule
34
- * @returns Evaluation result
35
- */
36
- evaluate(ruleName: string, input?: Record<string, any>): EvaluationResult;
37
-
38
- /**
39
- * Asynchronously evaluates a rule with the given input
40
- * @param ruleName - Name of the rule to evaluate
41
- * @param input - Input values for the rule
42
- * @returns Promise resolving to the evaluation result
43
- */
44
- evaluateAsync(
45
- ruleName: string,
46
- input?: Record<string, any>,
47
- ): Promise<EvaluationResult>;
48
-
49
- /**
50
- * Clean up evaluator resources
51
- */
52
- destroy(): void;
53
- }
54
-
55
- /**
56
- * Create a new evaluator
57
- * @param ruleset - The compiled ruleset, either as the object returned by
58
- * compile() or as a JSON string
59
- * @returns Promise resolving to an Evaluator instance
60
- */
61
- export function createEvaluator(ruleset: Ruleset | string): Promise<Evaluator>;
62
-
63
- /**
64
- * Compile a ruleset
65
- * @param src - Source code
66
- * @returns Promise resolving to the compiled ruleset
67
- */
68
- export function compile(src: string): Promise<Ruleset>;
69
-
70
- type BaseType = "string" | "number" | "bool" | "object" | "any";
71
- type ArrayType = `array<${string}>`;
72
- type UnionType = `${string}|${string}`;
73
- export type Type = BaseType | ArrayType | UnionType;
74
-
75
- export interface FunctionArgSpec {
76
- name: string;
77
- type: Type;
78
- required?: boolean;
79
- }
80
-
81
- export interface RegisterFunctionOptions {
82
- name: string;
83
- namespace?: string;
84
- args?: FunctionArgSpec[];
85
- returnType: Type;
86
- fn: (...args: any[]) => any;
87
- }
88
-
89
- /**
90
- * Register a custom function in the registry. Must be called before compilation or evaluation.
91
- * @param options - Function specification and implementation
92
- */
93
- export function registerFunction(
94
- options: RegisterFunctionOptions,
95
- ): Promise<void>;
1
+ export type EmittedSignal = {
2
+ name: string;
3
+ args: any[];
4
+ };
5
+
6
+ export type EvaluationResult = {
7
+ outputs: Record<string, any>;
8
+ emitted_signals: EmittedSignal[];
9
+ };
10
+
11
+ /**
12
+ * A compiled Nodora ruleset.
13
+ */
14
+ export type Ruleset = Record<string, any>;
15
+
16
+ export interface Evaluator {
17
+ /**
18
+ * Get evaluator id
19
+ */
20
+ getId(): number;
21
+
22
+ /**
23
+ * Register a callback for a signal
24
+ * @param signalName - Name of the signal to listen for
25
+ * @param callback - Callback function to invoke when signal is emitted
26
+ * @returns Evaluator instance for chaining
27
+ */
28
+ on(signalName: string, callback: (...args: any[]) => void): Evaluator;
29
+
30
+ /**
31
+ * Evaluates a rule with the given input
32
+ * @param ruleName - Name of the rule to evaluate
33
+ * @param input - Input values for the rule
34
+ * @returns Evaluation result
35
+ */
36
+ evaluate(ruleName: string, input?: Record<string, any>): EvaluationResult;
37
+
38
+ /**
39
+ * Asynchronously evaluates a rule with the given input
40
+ * @param ruleName - Name of the rule to evaluate
41
+ * @param input - Input values for the rule
42
+ * @returns Promise resolving to the evaluation result
43
+ */
44
+ evaluateAsync(
45
+ ruleName: string,
46
+ input?: Record<string, any>,
47
+ ): Promise<EvaluationResult>;
48
+
49
+ /**
50
+ * Clean up evaluator resources
51
+ */
52
+ destroy(): void;
53
+ }
54
+
55
+ type BaseType = "string" | "number" | "bool" | "object" | "any";
56
+ type ArrayType = `array<${string}>`;
57
+ type UnionType = `${string}|${string}`;
58
+ export type Type = BaseType | ArrayType | UnionType;
59
+
60
+ export interface FunctionArgSpec {
61
+ name: string;
62
+ type: Type;
63
+ required?: boolean;
64
+ }
65
+
66
+ export interface RegisterFunctionOptions {
67
+ name: string;
68
+ namespace?: string;
69
+ args?: FunctionArgSpec[];
70
+ returnType: Type;
71
+ fn: (...args: any[]) => any;
72
+ }
73
+
74
+ /**
75
+ * A position in the source. Lines start at 1, columns at 0.
76
+ */
77
+ export interface Position {
78
+ line: number;
79
+ col: number;
80
+ }
81
+
82
+ /**
83
+ * Thrown by Engine.compile(). The message includes the positions, with columns
84
+ * starting at 1.
85
+ */
86
+ export class CompileError extends Error {
87
+ /** Position of a syntax error */
88
+ pos?: Position;
89
+
90
+ /** Semantic errors, in case there are any */
91
+ errors?: { message: string; span?: { start: Position; end: Position } }[];
92
+ }
93
+
94
+ export interface Engine {
95
+ /**
96
+ * Register a custom function. Must be called before the rulesets that use it
97
+ * are compiled and evaluated. Built-in functions cannot be replaced.
98
+ * @param options - Function specification and implementation
99
+ * @returns Engine instance for chaining
100
+ */
101
+ registerFunction(options: RegisterFunctionOptions): Engine;
102
+
103
+ /**
104
+ * Compile a ruleset. Throws a CompileError if the source is not valid
105
+ * @param src - Source code
106
+ * @returns The compiled ruleset. It holds references to functions, not the
107
+ * functions themselves: they are provided by the engine it is evaluated with
108
+ */
109
+ compile(src: string): Ruleset;
110
+
111
+ /**
112
+ * Create a new evaluator, which calls this engine's functions
113
+ * @param ruleset - The compiled ruleset, either as the object returned by
114
+ * compile() or as a JSON string
115
+ */
116
+ createEvaluator(ruleset: Ruleset | string): Evaluator;
117
+
118
+ /**
119
+ * Clean up engine resources. Evaluators created by it keep working.
120
+ */
121
+ destroy(): void;
122
+ }
123
+
124
+ /**
125
+ * Create a new engine
126
+ * @returns Promise resolving to an Engine instance
127
+ */
128
+ export function createEngine(): Promise<Engine>;
package/lib/index.js CHANGED
@@ -1,144 +1,160 @@
1
- import "./wasm_exec.js";
2
- import { loadWasmBinary } from "#wasm-loader";
3
-
4
- let wasmInstance = null;
5
- let initPromise = null;
6
-
7
- async function init() {
8
- if (initPromise) return initPromise;
9
- initPromise = (async () => {
10
- let GoClass = globalThis.Go;
11
- if (!GoClass) {
12
- throw new Error("wasm_exec.js did not define Go class");
13
- }
14
- const go = new GoClass();
15
- const wasmBytes = await loadWasmBinary();
16
-
17
- const result = await WebAssembly.instantiate(wasmBytes, go.importObject);
18
- wasmInstance = result.instance;
19
- go.run(wasmInstance);
20
-
21
- return wasmInstance;
22
- })();
23
-
24
- try {
25
- return await initPromise;
26
- } catch (error) {
27
- initPromise = null;
28
- wasmInstance = null;
29
- throw new Error(`init() failed: ${error.message}`);
30
- }
31
- }
32
-
33
- class Evaluator {
34
- constructor(evaluatorId) {
35
- this.evaluatorId = evaluatorId;
36
- }
37
-
38
- getId() {
39
- return this.evaluatorId;
40
- }
41
-
42
- evaluate(ruleName, input = {}) {
43
- const result = globalThis.__nodoraEvaluate(
44
- this.evaluatorId,
45
- ruleName,
46
- input,
47
- );
48
- if (result.error) throw new Error(result.error);
49
- return result;
50
- }
51
-
52
- async evaluateAsync(ruleName, input = {}) {
53
- return this.evaluate(ruleName, input);
54
- }
55
-
56
- on(signalName, callback) {
57
- if (typeof callback !== "function") {
58
- throw new Error("callback must be a function");
59
- }
60
-
61
- globalThis.__nodoraOnSignal(this.evaluatorId, signalName, callback);
62
- return this;
63
- }
64
-
65
- destroy() {
66
- globalThis.__nodoraDestroy(this.evaluatorId);
67
- }
68
- }
69
-
70
- async function createEvaluator(ruleset) {
71
- if (!wasmInstance) {
72
- await init();
73
- }
74
-
75
- const rulesetJSON =
76
- typeof ruleset === "string" ? ruleset : JSON.stringify(ruleset);
77
-
78
- const result = globalThis.__nodoraCreateEvaluator(rulesetJSON);
79
- if (result.error) {
80
- throw new Error(result.error);
81
- }
82
-
83
- return new Evaluator(result);
84
- }
85
-
86
- async function compile(src) {
87
- if (!wasmInstance) {
88
- await init();
89
- }
90
- const result = globalThis.__nodoraCompile(src);
91
- if (result.error) throw result.error;
92
- return result;
93
- }
94
-
95
- function assertType(x, type, err) {
96
- if (!x || typeof x !== type) {
97
- throw new Error(err);
98
- }
99
- }
100
-
101
- async function registerFunction({ name, namespace, args, returnType, fn }) {
102
- if (!wasmInstance) await init();
103
-
104
- assertType(name, "string", "name is required and must be a string");
105
- assertType(
106
- returnType,
107
- "string",
108
- "returnType is required and must be a string",
109
- );
110
- assertType(fn, "function", "fn is required and must be a function");
111
-
112
- args = (args || []).map((arg, i) => {
113
- assertType(arg, "object", `args[${i}] must be an object`);
114
- assertType(
115
- arg.name,
116
- "string",
117
- `args[${i}].name is required and must be a string`,
118
- );
119
- assertType(
120
- arg.type,
121
- "string",
122
- `args[${i}].type is required and must be a string`,
123
- );
124
-
125
- return {
126
- name: arg.name,
127
- type: arg.type,
128
- required: !!(arg.required ?? true),
129
- };
130
- });
131
-
132
- namespace = typeof namespace === "string" ? namespace : "";
133
- const spec = {
134
- name,
135
- namespace,
136
- args: args,
137
- returnType,
138
- };
139
-
140
- const result = globalThis.__nodoraRegisterFunction(spec, fn);
141
- if (result && result.error) throw new Error(result.error);
142
- }
143
-
144
- export { compile, createEvaluator, Evaluator, registerFunction };
1
+ import "./wasm_exec.js";
2
+ import { loadWasmBinary } from "#wasm-loader";
3
+
4
+ let wasmInstance = null;
5
+ let initPromise = null;
6
+
7
+ async function init() {
8
+ if (initPromise) return initPromise;
9
+ initPromise = (async () => {
10
+ let GoClass = globalThis.Go;
11
+ if (!GoClass) {
12
+ throw new Error("wasm_exec.js did not define Go class");
13
+ }
14
+ const go = new GoClass();
15
+ const wasmBytes = await loadWasmBinary();
16
+
17
+ const result = await WebAssembly.instantiate(wasmBytes, go.importObject);
18
+ wasmInstance = result.instance;
19
+ go.run(wasmInstance);
20
+
21
+ return wasmInstance;
22
+ })();
23
+
24
+ try {
25
+ return await initPromise;
26
+ } catch (error) {
27
+ initPromise = null;
28
+ wasmInstance = null;
29
+ throw new Error(`init() failed: ${error.message}`);
30
+ }
31
+ }
32
+
33
+ class Evaluator {
34
+ constructor(evaluatorId) {
35
+ this.evaluatorId = evaluatorId;
36
+ }
37
+
38
+ getId() {
39
+ return this.evaluatorId;
40
+ }
41
+
42
+ evaluate(ruleName, input = {}) {
43
+ const result = globalThis.__nodoraEvaluate(
44
+ this.evaluatorId,
45
+ ruleName,
46
+ input,
47
+ );
48
+ if (result.error) throw new Error(result.error);
49
+ return result;
50
+ }
51
+
52
+ async evaluateAsync(ruleName, input = {}) {
53
+ return this.evaluate(ruleName, input);
54
+ }
55
+
56
+ on(signalName, callback) {
57
+ if (typeof callback !== "function") {
58
+ throw new Error("callback must be a function");
59
+ }
60
+
61
+ globalThis.__nodoraOnSignal(this.evaluatorId, signalName, callback);
62
+ return this;
63
+ }
64
+
65
+ destroy() {
66
+ globalThis.__nodoraDestroy(this.evaluatorId);
67
+ }
68
+ }
69
+
70
+ function assertType(x, type, err) {
71
+ if (!x || typeof x !== type) {
72
+ throw new Error(err);
73
+ }
74
+ }
75
+
76
+ class CompileError extends Error {
77
+ constructor({ message, pos, errors }) {
78
+ super(message);
79
+ this.name = "CompileError";
80
+ if (pos) this.pos = pos;
81
+ if (errors) this.errors = errors;
82
+ }
83
+ }
84
+
85
+ class Engine {
86
+ constructor(engineId) {
87
+ this.engineId = engineId;
88
+ }
89
+
90
+ registerFunction({ name, namespace, args, returnType, fn }) {
91
+ assertType(name, "string", "name is required and must be a string");
92
+ assertType(
93
+ returnType,
94
+ "string",
95
+ "returnType is required and must be a string",
96
+ );
97
+ assertType(fn, "function", "fn is required and must be a function");
98
+
99
+ args = (args || []).map((arg, i) => {
100
+ assertType(arg, "object", `args[${i}] must be an object`);
101
+ assertType(
102
+ arg.name,
103
+ "string",
104
+ `args[${i}].name is required and must be a string`,
105
+ );
106
+ assertType(
107
+ arg.type,
108
+ "string",
109
+ `args[${i}].type is required and must be a string`,
110
+ );
111
+
112
+ return {
113
+ name: arg.name,
114
+ type: arg.type,
115
+ required: !!(arg.required ?? true),
116
+ };
117
+ });
118
+
119
+ namespace = typeof namespace === "string" ? namespace : "";
120
+ const spec = { name, namespace, args, returnType };
121
+
122
+ const result = globalThis.__nodoraRegisterFunction(this.engineId, spec, fn);
123
+ if (result && result.error) throw new Error(result.error);
124
+ return this;
125
+ }
126
+
127
+ compile(src) {
128
+ const result = globalThis.__nodoraCompile(this.engineId, src);
129
+ if (result.error) {
130
+ throw typeof result.error === "string"
131
+ ? new Error(result.error)
132
+ : new CompileError(result.error);
133
+ }
134
+ return result;
135
+ }
136
+
137
+ createEvaluator(ruleset) {
138
+ const rulesetJSON =
139
+ typeof ruleset === "string" ? ruleset : JSON.stringify(ruleset);
140
+
141
+ const result = globalThis.__nodoraCreateEvaluator(
142
+ this.engineId,
143
+ rulesetJSON,
144
+ );
145
+ if (result.error) throw new Error(result.error);
146
+
147
+ return new Evaluator(result);
148
+ }
149
+
150
+ destroy() {
151
+ globalThis.__nodoraDestroyEngine(this.engineId);
152
+ }
153
+ }
154
+
155
+ async function createEngine() {
156
+ if (!wasmInstance) await init();
157
+ return new Engine(globalThis.__nodoraCreateEngine());
158
+ }
159
+
160
+ export { CompileError, createEngine, Evaluator };
Binary file
@@ -1,13 +1,13 @@
1
- export async function loadWasmBinary() {
2
- const wasmUrl = new URL("./nodora.wasm.gz", import.meta.url);
3
- const response = await fetch(wasmUrl.href);
4
- if (!response.ok) {
5
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
6
- }
7
- if (response.headers.get("Content-Encoding")?.includes("gzip")) {
8
- return response.arrayBuffer();
9
- }
10
- const ds = new DecompressionStream("gzip");
11
- const decompressed = response.body.pipeThrough(ds);
12
- return await new Response(decompressed).arrayBuffer();
13
- }
1
+ export async function loadWasmBinary() {
2
+ const wasmUrl = new URL("./nodora.wasm.gz", import.meta.url);
3
+ const response = await fetch(wasmUrl.href);
4
+ if (!response.ok) {
5
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
6
+ }
7
+ if (response.headers.get("Content-Encoding")?.includes("gzip")) {
8
+ return response.arrayBuffer();
9
+ }
10
+ const ds = new DecompressionStream("gzip");
11
+ const decompressed = response.body.pipeThrough(ds);
12
+ return await new Response(decompressed).arrayBuffer();
13
+ }
package/lib/wasm.node.js CHANGED
@@ -1,13 +1,13 @@
1
- import { readFile } from "fs/promises";
2
- import { fileURLToPath } from "url";
3
- import { gunzip } from "zlib";
4
- import { promisify } from "util";
5
-
6
- const gunzipAsync = promisify(gunzip);
7
-
8
- export async function loadWasmBinary() {
9
- const compressed = await readFile(
10
- fileURLToPath(new URL("./nodora.wasm.gz", import.meta.url))
11
- );
12
- return gunzipAsync(compressed);
13
- }
1
+ import { readFile } from "fs/promises";
2
+ import { fileURLToPath } from "url";
3
+ import { gunzip } from "zlib";
4
+ import { promisify } from "util";
5
+
6
+ const gunzipAsync = promisify(gunzip);
7
+
8
+ export async function loadWasmBinary() {
9
+ const compressed = await readFile(
10
+ fileURLToPath(new URL("./nodora.wasm.gz", import.meta.url))
11
+ );
12
+ return gunzipAsync(compressed);
13
+ }