@dlovans/tenet-core 0.1.0
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/README.md +113 -0
- package/dist/index.d.ts +112 -0
- package/dist/index.js +94 -0
- package/dist/lint.d.ts +31 -0
- package/dist/lint.js +160 -0
- package/package.json +53 -0
- package/wasm/tenet.wasm +0 -0
- package/wasm/wasm_exec.js +575 -0
package/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# @tenet/core
|
|
2
|
+
|
|
3
|
+
Declarative logic VM for JSON schemas. Reactive validation, temporal routing, and computed state.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @tenet/core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
### Browser
|
|
14
|
+
|
|
15
|
+
```html
|
|
16
|
+
<script src="https://unpkg.com/@tenet/core/wasm/wasm_exec.js"></script>
|
|
17
|
+
<script type="module">
|
|
18
|
+
import { init, run } from '@tenet/core';
|
|
19
|
+
|
|
20
|
+
await init('/path/to/tenet.wasm');
|
|
21
|
+
|
|
22
|
+
const schema = {
|
|
23
|
+
definitions: {
|
|
24
|
+
amount: { type: 'number', value: 150, min: 0, max: 10000 }
|
|
25
|
+
},
|
|
26
|
+
logic_tree: [
|
|
27
|
+
{
|
|
28
|
+
id: 'high_amount',
|
|
29
|
+
when: { '>': [{ var: 'amount' }, 1000] },
|
|
30
|
+
then: { error_msg: 'Amount exceeds limit.' }
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const result = run(schema);
|
|
36
|
+
console.log(result);
|
|
37
|
+
</script>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Node.js
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
import { init, run, verify } from '@tenet/core';
|
|
44
|
+
|
|
45
|
+
// Initialize WASM
|
|
46
|
+
await init('./node_modules/@tenet/core/wasm/tenet.wasm');
|
|
47
|
+
|
|
48
|
+
// Run schema logic
|
|
49
|
+
const result = run(schema, new Date());
|
|
50
|
+
|
|
51
|
+
if (result.error) {
|
|
52
|
+
console.error(result.error);
|
|
53
|
+
} else {
|
|
54
|
+
console.log(result.result.status); // 'READY', 'INCOMPLETE', or 'INVALID'
|
|
55
|
+
console.log(result.result.errors); // Validation errors
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Verify transformation
|
|
59
|
+
const verification = verify(newSchema, oldSchema);
|
|
60
|
+
console.log(verification.valid);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## API
|
|
64
|
+
|
|
65
|
+
### `init(wasmPath?: string): Promise<void>`
|
|
66
|
+
Initialize the WASM module. Must be called before `run()` or `verify()`.
|
|
67
|
+
|
|
68
|
+
### `run(schema, date?): TenetResult`
|
|
69
|
+
Execute the schema logic for the given effective date.
|
|
70
|
+
|
|
71
|
+
### `verify(newSchema, oldSchema): TenetVerifyResult`
|
|
72
|
+
Verify that a transformation is legal by replaying the logic.
|
|
73
|
+
|
|
74
|
+
### `lint(schema): LintResult` *(No WASM required)*
|
|
75
|
+
Static analysis - find issues without executing the schema.
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
import { lint } from '@tenet/core';
|
|
79
|
+
|
|
80
|
+
const result = lint(schema);
|
|
81
|
+
// No init() needed - pure TypeScript!
|
|
82
|
+
|
|
83
|
+
if (!result.valid) {
|
|
84
|
+
for (const issue of result.issues) {
|
|
85
|
+
console.log(`${issue.severity}: ${issue.message}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `isTenetSchema(obj): boolean`
|
|
91
|
+
Check if an object is a Tenet schema.
|
|
92
|
+
|
|
93
|
+
### `isReady(): boolean`
|
|
94
|
+
Check if WASM is initialized.
|
|
95
|
+
|
|
96
|
+
## JSON Schema (IDE Support)
|
|
97
|
+
|
|
98
|
+
Add to your schema files for autocompletion:
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{
|
|
102
|
+
"$schema": "https://tenet.dev/schema/v1.json",
|
|
103
|
+
"definitions": { ... }
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## TypeScript
|
|
108
|
+
|
|
109
|
+
Full type definitions are included. See `TenetSchema`, `Definition`, `Rule`, `LintResult`, etc.
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tenet - Declarative Logic VM for JSON Schemas
|
|
3
|
+
*
|
|
4
|
+
* This module provides a JavaScript/TypeScript wrapper around the Tenet WASM binary.
|
|
5
|
+
* Works in both browser and Node.js environments.
|
|
6
|
+
*/
|
|
7
|
+
export { lint, isTenetSchema, SCHEMA_URL } from './lint.js';
|
|
8
|
+
export type { LintIssue, LintResult } from './lint.js';
|
|
9
|
+
export interface TenetResult {
|
|
10
|
+
result?: TenetSchema;
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface TenetVerifyResult {
|
|
14
|
+
valid: boolean;
|
|
15
|
+
error?: string;
|
|
16
|
+
}
|
|
17
|
+
export interface TenetSchema {
|
|
18
|
+
protocol?: string;
|
|
19
|
+
schema_id?: string;
|
|
20
|
+
version?: string;
|
|
21
|
+
valid_from?: string;
|
|
22
|
+
definitions: Record<string, Definition>;
|
|
23
|
+
logic_tree?: Rule[];
|
|
24
|
+
temporal_map?: TemporalBranch[];
|
|
25
|
+
state_model?: StateModel;
|
|
26
|
+
errors?: ValidationError[];
|
|
27
|
+
status?: 'READY' | 'INCOMPLETE' | 'INVALID';
|
|
28
|
+
}
|
|
29
|
+
export interface Definition {
|
|
30
|
+
type: 'string' | 'number' | 'boolean' | 'select' | 'date' | 'attestation' | 'currency';
|
|
31
|
+
value?: unknown;
|
|
32
|
+
options?: string[];
|
|
33
|
+
label?: string;
|
|
34
|
+
required?: boolean;
|
|
35
|
+
visible?: boolean;
|
|
36
|
+
min?: number;
|
|
37
|
+
max?: number;
|
|
38
|
+
step?: number;
|
|
39
|
+
min_length?: number;
|
|
40
|
+
max_length?: number;
|
|
41
|
+
pattern?: string;
|
|
42
|
+
ui_class?: string;
|
|
43
|
+
ui_message?: string;
|
|
44
|
+
}
|
|
45
|
+
export interface Rule {
|
|
46
|
+
id: string;
|
|
47
|
+
law_ref?: string;
|
|
48
|
+
logic_version?: string;
|
|
49
|
+
when: Record<string, unknown>;
|
|
50
|
+
then: Action;
|
|
51
|
+
disabled?: boolean;
|
|
52
|
+
}
|
|
53
|
+
export interface Action {
|
|
54
|
+
set?: Record<string, unknown>;
|
|
55
|
+
ui_modify?: Record<string, unknown>;
|
|
56
|
+
error_msg?: string;
|
|
57
|
+
}
|
|
58
|
+
export interface TemporalBranch {
|
|
59
|
+
valid_range: [string | null, string | null];
|
|
60
|
+
logic_version: string;
|
|
61
|
+
status: 'ACTIVE' | 'ARCHIVED';
|
|
62
|
+
}
|
|
63
|
+
export interface StateModel {
|
|
64
|
+
inputs: string[];
|
|
65
|
+
derived: Record<string, DerivedDef>;
|
|
66
|
+
}
|
|
67
|
+
export interface DerivedDef {
|
|
68
|
+
eval: Record<string, unknown>;
|
|
69
|
+
}
|
|
70
|
+
export interface ValidationError {
|
|
71
|
+
field_id?: string;
|
|
72
|
+
rule_id?: string;
|
|
73
|
+
message: string;
|
|
74
|
+
law_ref?: string;
|
|
75
|
+
}
|
|
76
|
+
declare global {
|
|
77
|
+
var TenetRun: (json: string, date: string) => TenetResult;
|
|
78
|
+
var TenetVerify: (newJson: string, oldJson: string) => TenetVerifyResult;
|
|
79
|
+
var Go: new () => GoInstance;
|
|
80
|
+
}
|
|
81
|
+
interface GoInstance {
|
|
82
|
+
importObject: WebAssembly.Imports;
|
|
83
|
+
run(instance: WebAssembly.Instance): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Initialize the Tenet WASM module.
|
|
87
|
+
* Must be called before using run() or verify().
|
|
88
|
+
*
|
|
89
|
+
* @param wasmPath - Path or URL to tenet.wasm file
|
|
90
|
+
*/
|
|
91
|
+
export declare function init(wasmPath?: string): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Run the Tenet VM on a schema.
|
|
94
|
+
*
|
|
95
|
+
* @param schema - The schema object or JSON string
|
|
96
|
+
* @param date - Effective date (ISO 8601 string or Date object)
|
|
97
|
+
* @returns The transformed schema with computed state, errors, and status
|
|
98
|
+
*/
|
|
99
|
+
export declare function run(schema: TenetSchema | string, date?: Date | string): TenetResult;
|
|
100
|
+
/**
|
|
101
|
+
* Verify that a schema transformation is legal.
|
|
102
|
+
* Re-runs the logic on the old schema and compares with the new schema.
|
|
103
|
+
*
|
|
104
|
+
* @param newSchema - The transformed schema
|
|
105
|
+
* @param oldSchema - The original schema
|
|
106
|
+
* @returns Whether the transformation is valid
|
|
107
|
+
*/
|
|
108
|
+
export declare function verify(newSchema: TenetSchema | string, oldSchema: TenetSchema | string): TenetVerifyResult;
|
|
109
|
+
/**
|
|
110
|
+
* Check if the WASM module is ready.
|
|
111
|
+
*/
|
|
112
|
+
export declare function isReady(): boolean;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tenet - Declarative Logic VM for JSON Schemas
|
|
3
|
+
*
|
|
4
|
+
* This module provides a JavaScript/TypeScript wrapper around the Tenet WASM binary.
|
|
5
|
+
* Works in both browser and Node.js environments.
|
|
6
|
+
*/
|
|
7
|
+
// Re-export lint functions (pure TypeScript, no WASM needed)
|
|
8
|
+
export { lint, isTenetSchema, SCHEMA_URL } from './lint.js';
|
|
9
|
+
let wasmReady = false;
|
|
10
|
+
let wasmReadyPromise = null;
|
|
11
|
+
/**
|
|
12
|
+
* Initialize the Tenet WASM module.
|
|
13
|
+
* Must be called before using run() or verify().
|
|
14
|
+
*
|
|
15
|
+
* @param wasmPath - Path or URL to tenet.wasm file
|
|
16
|
+
*/
|
|
17
|
+
export async function init(wasmPath = './tenet.wasm') {
|
|
18
|
+
if (wasmReady)
|
|
19
|
+
return;
|
|
20
|
+
if (wasmReadyPromise)
|
|
21
|
+
return wasmReadyPromise;
|
|
22
|
+
wasmReadyPromise = loadWasm(wasmPath);
|
|
23
|
+
await wasmReadyPromise;
|
|
24
|
+
wasmReady = true;
|
|
25
|
+
}
|
|
26
|
+
async function loadWasm(wasmPath) {
|
|
27
|
+
// Detect environment
|
|
28
|
+
const isBrowser = typeof window !== 'undefined';
|
|
29
|
+
const isNode = typeof process !== 'undefined' && process.versions?.node;
|
|
30
|
+
if (isBrowser) {
|
|
31
|
+
// Browser environment
|
|
32
|
+
const go = new Go();
|
|
33
|
+
const result = await WebAssembly.instantiateStreaming(fetch(wasmPath), go.importObject);
|
|
34
|
+
go.run(result.instance);
|
|
35
|
+
}
|
|
36
|
+
else if (isNode) {
|
|
37
|
+
// Node.js environment
|
|
38
|
+
const fs = await import('fs');
|
|
39
|
+
const path = await import('path');
|
|
40
|
+
const { fileURLToPath } = await import('url');
|
|
41
|
+
const { createRequire } = await import('module');
|
|
42
|
+
// ESM-compatible __dirname and require
|
|
43
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
44
|
+
const __dirname = path.dirname(__filename);
|
|
45
|
+
const require = createRequire(import.meta.url);
|
|
46
|
+
// Load wasm_exec.js (Go's JS runtime)
|
|
47
|
+
const wasmExecPath = path.resolve(__dirname, '../wasm/wasm_exec.js');
|
|
48
|
+
require(wasmExecPath);
|
|
49
|
+
const go = new Go();
|
|
50
|
+
const wasmBuffer = fs.readFileSync(wasmPath);
|
|
51
|
+
const result = await WebAssembly.instantiate(wasmBuffer, go.importObject);
|
|
52
|
+
go.run(result.instance);
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
throw new Error('Unsupported environment');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Run the Tenet VM on a schema.
|
|
60
|
+
*
|
|
61
|
+
* @param schema - The schema object or JSON string
|
|
62
|
+
* @param date - Effective date (ISO 8601 string or Date object)
|
|
63
|
+
* @returns The transformed schema with computed state, errors, and status
|
|
64
|
+
*/
|
|
65
|
+
export function run(schema, date = new Date()) {
|
|
66
|
+
if (!wasmReady) {
|
|
67
|
+
throw new Error('Tenet not initialized. Call init() first.');
|
|
68
|
+
}
|
|
69
|
+
const jsonStr = typeof schema === 'string' ? schema : JSON.stringify(schema);
|
|
70
|
+
const dateStr = date instanceof Date ? date.toISOString() : date;
|
|
71
|
+
return globalThis.TenetRun(jsonStr, dateStr);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Verify that a schema transformation is legal.
|
|
75
|
+
* Re-runs the logic on the old schema and compares with the new schema.
|
|
76
|
+
*
|
|
77
|
+
* @param newSchema - The transformed schema
|
|
78
|
+
* @param oldSchema - The original schema
|
|
79
|
+
* @returns Whether the transformation is valid
|
|
80
|
+
*/
|
|
81
|
+
export function verify(newSchema, oldSchema) {
|
|
82
|
+
if (!wasmReady) {
|
|
83
|
+
throw new Error('Tenet not initialized. Call init() first.');
|
|
84
|
+
}
|
|
85
|
+
const newJson = typeof newSchema === 'string' ? newSchema : JSON.stringify(newSchema);
|
|
86
|
+
const oldJson = typeof oldSchema === 'string' ? oldSchema : JSON.stringify(oldSchema);
|
|
87
|
+
return globalThis.TenetVerify(newJson, oldJson);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Check if the WASM module is ready.
|
|
91
|
+
*/
|
|
92
|
+
export function isReady() {
|
|
93
|
+
return wasmReady;
|
|
94
|
+
}
|
package/dist/lint.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tenet Linter - Static Analysis for Tenet Schemas
|
|
3
|
+
*
|
|
4
|
+
* Pure TypeScript implementation - no WASM required.
|
|
5
|
+
* Can be used in browsers, Node.js, and edge runtimes.
|
|
6
|
+
*/
|
|
7
|
+
import type { TenetSchema } from './index';
|
|
8
|
+
export declare const SCHEMA_URL = "https://tenet.dev/schema/v1.json";
|
|
9
|
+
export interface LintIssue {
|
|
10
|
+
severity: 'error' | 'warning' | 'info';
|
|
11
|
+
field?: string;
|
|
12
|
+
rule?: string;
|
|
13
|
+
message: string;
|
|
14
|
+
}
|
|
15
|
+
export interface LintResult {
|
|
16
|
+
valid: boolean;
|
|
17
|
+
issues: LintIssue[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Perform static analysis on a Tenet schema without executing it.
|
|
21
|
+
* Detects potential issues like undefined variables, cycles, and missing fields.
|
|
22
|
+
*
|
|
23
|
+
* @param schema - The schema object or JSON string
|
|
24
|
+
* @returns Lint result with issues found
|
|
25
|
+
*/
|
|
26
|
+
export declare function lint(schema: TenetSchema | string): LintResult;
|
|
27
|
+
/**
|
|
28
|
+
* Check if a schema is a valid Tenet schema (basic detection).
|
|
29
|
+
* Useful for IDE integration to detect Tenet files.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isTenetSchema(schema: unknown): schema is TenetSchema;
|
package/dist/lint.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tenet Linter - Static Analysis for Tenet Schemas
|
|
3
|
+
*
|
|
4
|
+
* Pure TypeScript implementation - no WASM required.
|
|
5
|
+
* Can be used in browsers, Node.js, and edge runtimes.
|
|
6
|
+
*/
|
|
7
|
+
// JSON Schema URL for IDE integration
|
|
8
|
+
export const SCHEMA_URL = 'https://tenet.dev/schema/v1.json';
|
|
9
|
+
/**
|
|
10
|
+
* Perform static analysis on a Tenet schema without executing it.
|
|
11
|
+
* Detects potential issues like undefined variables, cycles, and missing fields.
|
|
12
|
+
*
|
|
13
|
+
* @param schema - The schema object or JSON string
|
|
14
|
+
* @returns Lint result with issues found
|
|
15
|
+
*/
|
|
16
|
+
export function lint(schema) {
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = typeof schema === 'string' ? JSON.parse(schema) : schema;
|
|
20
|
+
}
|
|
21
|
+
catch (e) {
|
|
22
|
+
return {
|
|
23
|
+
valid: false,
|
|
24
|
+
issues: [{ severity: 'error', message: `Parse error: ${e}` }]
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const result = {
|
|
28
|
+
valid: true,
|
|
29
|
+
issues: []
|
|
30
|
+
};
|
|
31
|
+
// Collect all defined field names
|
|
32
|
+
const definedFields = new Set();
|
|
33
|
+
if (parsed.definitions) {
|
|
34
|
+
for (const name of Object.keys(parsed.definitions)) {
|
|
35
|
+
definedFields.add(name);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Add derived fields
|
|
39
|
+
if (parsed.state_model?.derived) {
|
|
40
|
+
for (const name of Object.keys(parsed.state_model.derived)) {
|
|
41
|
+
definedFields.add(name);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// Check 1: Schema identification
|
|
45
|
+
if (!parsed.protocol && !parsed['$schema']) {
|
|
46
|
+
result.issues.push({
|
|
47
|
+
severity: 'info',
|
|
48
|
+
message: `Consider adding "protocol": "Tenet_v1.0" or "$schema": "${SCHEMA_URL}" for IDE support`
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
// Check 2: Undefined variables in logic tree
|
|
52
|
+
if (parsed.logic_tree) {
|
|
53
|
+
for (const rule of parsed.logic_tree) {
|
|
54
|
+
if (!rule)
|
|
55
|
+
continue;
|
|
56
|
+
const varsInWhen = extractVars(rule.when);
|
|
57
|
+
for (const v of varsInWhen) {
|
|
58
|
+
if (!definedFields.has(v)) {
|
|
59
|
+
addError(result, v, rule.id, `Undefined variable '${v}' in rule condition`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Check 3: Potential cycles (fields set by multiple rules)
|
|
65
|
+
const fieldSetBy = new Map();
|
|
66
|
+
if (parsed.logic_tree) {
|
|
67
|
+
for (const rule of parsed.logic_tree) {
|
|
68
|
+
if (!rule?.then?.set)
|
|
69
|
+
continue;
|
|
70
|
+
for (const field of Object.keys(rule.then.set)) {
|
|
71
|
+
const rules = fieldSetBy.get(field) || [];
|
|
72
|
+
rules.push(rule.id);
|
|
73
|
+
fieldSetBy.set(field, rules);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const [field, rules] of fieldSetBy) {
|
|
78
|
+
if (rules.length > 1) {
|
|
79
|
+
addWarning(result, field, '', `Field '${field}' may be set by multiple rules: [${rules.sort().join(', ')}] (potential cycle)`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// Check 4: Temporal map validation
|
|
83
|
+
if (parsed.temporal_map) {
|
|
84
|
+
for (let i = 0; i < parsed.temporal_map.length; i++) {
|
|
85
|
+
const branch = parsed.temporal_map[i];
|
|
86
|
+
if (!branch)
|
|
87
|
+
continue;
|
|
88
|
+
if (!branch.logic_version) {
|
|
89
|
+
addWarning(result, '', '', `Temporal branch ${i} has no logic_version`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Check 5: Empty type in definitions
|
|
94
|
+
if (parsed.definitions) {
|
|
95
|
+
for (const [name, def] of Object.entries(parsed.definitions)) {
|
|
96
|
+
if (!def)
|
|
97
|
+
continue;
|
|
98
|
+
if (!def.type) {
|
|
99
|
+
addWarning(result, name, '', `Definition '${name}' has no type specified`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Check if a schema is a valid Tenet schema (basic detection).
|
|
107
|
+
* Useful for IDE integration to detect Tenet files.
|
|
108
|
+
*/
|
|
109
|
+
export function isTenetSchema(schema) {
|
|
110
|
+
if (typeof schema !== 'object' || schema === null)
|
|
111
|
+
return false;
|
|
112
|
+
const obj = schema;
|
|
113
|
+
// Check for $schema URL
|
|
114
|
+
if (obj['$schema'] === SCHEMA_URL)
|
|
115
|
+
return true;
|
|
116
|
+
// Check for protocol field
|
|
117
|
+
if (typeof obj.protocol === 'string' && obj.protocol.startsWith('Tenet'))
|
|
118
|
+
return true;
|
|
119
|
+
// Check for definitions + logic_tree structure
|
|
120
|
+
if (obj.definitions && typeof obj.definitions === 'object')
|
|
121
|
+
return true;
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
// Helper functions
|
|
125
|
+
function addError(result, field, rule, message) {
|
|
126
|
+
result.valid = false;
|
|
127
|
+
result.issues.push({ severity: 'error', field, rule, message });
|
|
128
|
+
}
|
|
129
|
+
function addWarning(result, field, rule, message) {
|
|
130
|
+
result.issues.push({ severity: 'warning', field, rule, message });
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Extract all variable references from a JSON-logic expression.
|
|
134
|
+
*/
|
|
135
|
+
function extractVars(node) {
|
|
136
|
+
if (node === null || node === undefined)
|
|
137
|
+
return [];
|
|
138
|
+
const vars = [];
|
|
139
|
+
if (typeof node === 'object') {
|
|
140
|
+
if (Array.isArray(node)) {
|
|
141
|
+
for (const elem of node) {
|
|
142
|
+
vars.push(...extractVars(elem));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const obj = node;
|
|
147
|
+
// Check if this is a var reference
|
|
148
|
+
if ('var' in obj && typeof obj.var === 'string') {
|
|
149
|
+
// Get root variable name (before any dot notation)
|
|
150
|
+
const varName = obj.var.split('.')[0];
|
|
151
|
+
vars.push(varName);
|
|
152
|
+
}
|
|
153
|
+
// Recurse into all values
|
|
154
|
+
for (const val of Object.values(obj)) {
|
|
155
|
+
vars.push(...extractVars(val));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return vars;
|
|
160
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dlovans/tenet-core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Declarative logic VM for JSON schemas - reactive validation, temporal routing, and computed state",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
},
|
|
13
|
+
"./lint": {
|
|
14
|
+
"import": "./dist/lint.js",
|
|
15
|
+
"types": "./dist/lint.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"wasm"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build:wasm": "cd .. && GOOS=js GOARCH=wasm go build -o js/wasm/tenet.wasm ./cmd/wasm",
|
|
24
|
+
"build:js": "tsc",
|
|
25
|
+
"build": "npm run build:wasm && npm run build:js",
|
|
26
|
+
"test": "node --test dist/*.test.js",
|
|
27
|
+
"prepublishOnly": "npm run build"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"json-logic",
|
|
31
|
+
"validation",
|
|
32
|
+
"reactive",
|
|
33
|
+
"schema",
|
|
34
|
+
"form",
|
|
35
|
+
"wasm",
|
|
36
|
+
"compliance",
|
|
37
|
+
"temporal",
|
|
38
|
+
"linter"
|
|
39
|
+
],
|
|
40
|
+
"author": "Dlovan Sharif",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "https://github.com/tenet-vm/tenet"
|
|
45
|
+
},
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=18.0.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/node": "^25.0.9",
|
|
51
|
+
"typescript": "^5.0.0"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/wasm/tenet.wasm
ADDED
|
Binary file
|
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
// Copyright 2018 The Go Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style
|
|
3
|
+
// license that can be found in the LICENSE file.
|
|
4
|
+
|
|
5
|
+
"use strict";
|
|
6
|
+
|
|
7
|
+
(() => {
|
|
8
|
+
const enosys = () => {
|
|
9
|
+
const err = new Error("not implemented");
|
|
10
|
+
err.code = "ENOSYS";
|
|
11
|
+
return err;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
if (!globalThis.fs) {
|
|
15
|
+
let outputBuf = "";
|
|
16
|
+
globalThis.fs = {
|
|
17
|
+
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
|
|
18
|
+
writeSync(fd, buf) {
|
|
19
|
+
outputBuf += decoder.decode(buf);
|
|
20
|
+
const nl = outputBuf.lastIndexOf("\n");
|
|
21
|
+
if (nl != -1) {
|
|
22
|
+
console.log(outputBuf.substring(0, nl));
|
|
23
|
+
outputBuf = outputBuf.substring(nl + 1);
|
|
24
|
+
}
|
|
25
|
+
return buf.length;
|
|
26
|
+
},
|
|
27
|
+
write(fd, buf, offset, length, position, callback) {
|
|
28
|
+
if (offset !== 0 || length !== buf.length || position !== null) {
|
|
29
|
+
callback(enosys());
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const n = this.writeSync(fd, buf);
|
|
33
|
+
callback(null, n);
|
|
34
|
+
},
|
|
35
|
+
chmod(path, mode, callback) { callback(enosys()); },
|
|
36
|
+
chown(path, uid, gid, callback) { callback(enosys()); },
|
|
37
|
+
close(fd, callback) { callback(enosys()); },
|
|
38
|
+
fchmod(fd, mode, callback) { callback(enosys()); },
|
|
39
|
+
fchown(fd, uid, gid, callback) { callback(enosys()); },
|
|
40
|
+
fstat(fd, callback) { callback(enosys()); },
|
|
41
|
+
fsync(fd, callback) { callback(null); },
|
|
42
|
+
ftruncate(fd, length, callback) { callback(enosys()); },
|
|
43
|
+
lchown(path, uid, gid, callback) { callback(enosys()); },
|
|
44
|
+
link(path, link, callback) { callback(enosys()); },
|
|
45
|
+
lstat(path, callback) { callback(enosys()); },
|
|
46
|
+
mkdir(path, perm, callback) { callback(enosys()); },
|
|
47
|
+
open(path, flags, mode, callback) { callback(enosys()); },
|
|
48
|
+
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
|
|
49
|
+
readdir(path, callback) { callback(enosys()); },
|
|
50
|
+
readlink(path, callback) { callback(enosys()); },
|
|
51
|
+
rename(from, to, callback) { callback(enosys()); },
|
|
52
|
+
rmdir(path, callback) { callback(enosys()); },
|
|
53
|
+
stat(path, callback) { callback(enosys()); },
|
|
54
|
+
symlink(path, link, callback) { callback(enosys()); },
|
|
55
|
+
truncate(path, length, callback) { callback(enosys()); },
|
|
56
|
+
unlink(path, callback) { callback(enosys()); },
|
|
57
|
+
utimes(path, atime, mtime, callback) { callback(enosys()); },
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!globalThis.process) {
|
|
62
|
+
globalThis.process = {
|
|
63
|
+
getuid() { return -1; },
|
|
64
|
+
getgid() { return -1; },
|
|
65
|
+
geteuid() { return -1; },
|
|
66
|
+
getegid() { return -1; },
|
|
67
|
+
getgroups() { throw enosys(); },
|
|
68
|
+
pid: -1,
|
|
69
|
+
ppid: -1,
|
|
70
|
+
umask() { throw enosys(); },
|
|
71
|
+
cwd() { throw enosys(); },
|
|
72
|
+
chdir() { throw enosys(); },
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!globalThis.path) {
|
|
77
|
+
globalThis.path = {
|
|
78
|
+
resolve(...pathSegments) {
|
|
79
|
+
return pathSegments.join("/");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (!globalThis.crypto) {
|
|
85
|
+
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!globalThis.performance) {
|
|
89
|
+
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!globalThis.TextEncoder) {
|
|
93
|
+
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (!globalThis.TextDecoder) {
|
|
97
|
+
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const encoder = new TextEncoder("utf-8");
|
|
101
|
+
const decoder = new TextDecoder("utf-8");
|
|
102
|
+
|
|
103
|
+
globalThis.Go = class {
|
|
104
|
+
constructor() {
|
|
105
|
+
this.argv = ["js"];
|
|
106
|
+
this.env = {};
|
|
107
|
+
this.exit = (code) => {
|
|
108
|
+
if (code !== 0) {
|
|
109
|
+
console.warn("exit code:", code);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
this._exitPromise = new Promise((resolve) => {
|
|
113
|
+
this._resolveExitPromise = resolve;
|
|
114
|
+
});
|
|
115
|
+
this._pendingEvent = null;
|
|
116
|
+
this._scheduledTimeouts = new Map();
|
|
117
|
+
this._nextCallbackTimeoutID = 1;
|
|
118
|
+
|
|
119
|
+
const setInt64 = (addr, v) => {
|
|
120
|
+
this.mem.setUint32(addr + 0, v, true);
|
|
121
|
+
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const setInt32 = (addr, v) => {
|
|
125
|
+
this.mem.setUint32(addr + 0, v, true);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const getInt64 = (addr) => {
|
|
129
|
+
const low = this.mem.getUint32(addr + 0, true);
|
|
130
|
+
const high = this.mem.getInt32(addr + 4, true);
|
|
131
|
+
return low + high * 4294967296;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const loadValue = (addr) => {
|
|
135
|
+
const f = this.mem.getFloat64(addr, true);
|
|
136
|
+
if (f === 0) {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
if (!isNaN(f)) {
|
|
140
|
+
return f;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const id = this.mem.getUint32(addr, true);
|
|
144
|
+
return this._values[id];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const storeValue = (addr, v) => {
|
|
148
|
+
const nanHead = 0x7FF80000;
|
|
149
|
+
|
|
150
|
+
if (typeof v === "number" && v !== 0) {
|
|
151
|
+
if (isNaN(v)) {
|
|
152
|
+
this.mem.setUint32(addr + 4, nanHead, true);
|
|
153
|
+
this.mem.setUint32(addr, 0, true);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.mem.setFloat64(addr, v, true);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (v === undefined) {
|
|
161
|
+
this.mem.setFloat64(addr, 0, true);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let id = this._ids.get(v);
|
|
166
|
+
if (id === undefined) {
|
|
167
|
+
id = this._idPool.pop();
|
|
168
|
+
if (id === undefined) {
|
|
169
|
+
id = this._values.length;
|
|
170
|
+
}
|
|
171
|
+
this._values[id] = v;
|
|
172
|
+
this._goRefCounts[id] = 0;
|
|
173
|
+
this._ids.set(v, id);
|
|
174
|
+
}
|
|
175
|
+
this._goRefCounts[id]++;
|
|
176
|
+
let typeFlag = 0;
|
|
177
|
+
switch (typeof v) {
|
|
178
|
+
case "object":
|
|
179
|
+
if (v !== null) {
|
|
180
|
+
typeFlag = 1;
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
case "string":
|
|
184
|
+
typeFlag = 2;
|
|
185
|
+
break;
|
|
186
|
+
case "symbol":
|
|
187
|
+
typeFlag = 3;
|
|
188
|
+
break;
|
|
189
|
+
case "function":
|
|
190
|
+
typeFlag = 4;
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
|
194
|
+
this.mem.setUint32(addr, id, true);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const loadSlice = (addr) => {
|
|
198
|
+
const array = getInt64(addr + 0);
|
|
199
|
+
const len = getInt64(addr + 8);
|
|
200
|
+
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const loadSliceOfValues = (addr) => {
|
|
204
|
+
const array = getInt64(addr + 0);
|
|
205
|
+
const len = getInt64(addr + 8);
|
|
206
|
+
const a = new Array(len);
|
|
207
|
+
for (let i = 0; i < len; i++) {
|
|
208
|
+
a[i] = loadValue(array + i * 8);
|
|
209
|
+
}
|
|
210
|
+
return a;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const loadString = (addr) => {
|
|
214
|
+
const saddr = getInt64(addr + 0);
|
|
215
|
+
const len = getInt64(addr + 8);
|
|
216
|
+
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const testCallExport = (a, b) => {
|
|
220
|
+
this._inst.exports.testExport0();
|
|
221
|
+
return this._inst.exports.testExport(a, b);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const timeOrigin = Date.now() - performance.now();
|
|
225
|
+
this.importObject = {
|
|
226
|
+
_gotest: {
|
|
227
|
+
add: (a, b) => a + b,
|
|
228
|
+
callExport: testCallExport,
|
|
229
|
+
},
|
|
230
|
+
gojs: {
|
|
231
|
+
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
|
232
|
+
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
|
233
|
+
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
|
234
|
+
// This changes the SP, thus we have to update the SP used by the imported function.
|
|
235
|
+
|
|
236
|
+
// func wasmExit(code int32)
|
|
237
|
+
"runtime.wasmExit": (sp) => {
|
|
238
|
+
sp >>>= 0;
|
|
239
|
+
const code = this.mem.getInt32(sp + 8, true);
|
|
240
|
+
this.exited = true;
|
|
241
|
+
delete this._inst;
|
|
242
|
+
delete this._values;
|
|
243
|
+
delete this._goRefCounts;
|
|
244
|
+
delete this._ids;
|
|
245
|
+
delete this._idPool;
|
|
246
|
+
this.exit(code);
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
|
250
|
+
"runtime.wasmWrite": (sp) => {
|
|
251
|
+
sp >>>= 0;
|
|
252
|
+
const fd = getInt64(sp + 8);
|
|
253
|
+
const p = getInt64(sp + 16);
|
|
254
|
+
const n = this.mem.getInt32(sp + 24, true);
|
|
255
|
+
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
|
256
|
+
},
|
|
257
|
+
|
|
258
|
+
// func resetMemoryDataView()
|
|
259
|
+
"runtime.resetMemoryDataView": (sp) => {
|
|
260
|
+
sp >>>= 0;
|
|
261
|
+
this.mem = new DataView(this._inst.exports.mem.buffer);
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
// func nanotime1() int64
|
|
265
|
+
"runtime.nanotime1": (sp) => {
|
|
266
|
+
sp >>>= 0;
|
|
267
|
+
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
// func walltime() (sec int64, nsec int32)
|
|
271
|
+
"runtime.walltime": (sp) => {
|
|
272
|
+
sp >>>= 0;
|
|
273
|
+
const msec = (new Date).getTime();
|
|
274
|
+
setInt64(sp + 8, msec / 1000);
|
|
275
|
+
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
|
276
|
+
},
|
|
277
|
+
|
|
278
|
+
// func scheduleTimeoutEvent(delay int64) int32
|
|
279
|
+
"runtime.scheduleTimeoutEvent": (sp) => {
|
|
280
|
+
sp >>>= 0;
|
|
281
|
+
const id = this._nextCallbackTimeoutID;
|
|
282
|
+
this._nextCallbackTimeoutID++;
|
|
283
|
+
this._scheduledTimeouts.set(id, setTimeout(
|
|
284
|
+
() => {
|
|
285
|
+
this._resume();
|
|
286
|
+
while (this._scheduledTimeouts.has(id)) {
|
|
287
|
+
// for some reason Go failed to register the timeout event, log and try again
|
|
288
|
+
// (temporary workaround for https://github.com/golang/go/issues/28975)
|
|
289
|
+
console.warn("scheduleTimeoutEvent: missed timeout event");
|
|
290
|
+
this._resume();
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
getInt64(sp + 8),
|
|
294
|
+
));
|
|
295
|
+
this.mem.setInt32(sp + 16, id, true);
|
|
296
|
+
},
|
|
297
|
+
|
|
298
|
+
// func clearTimeoutEvent(id int32)
|
|
299
|
+
"runtime.clearTimeoutEvent": (sp) => {
|
|
300
|
+
sp >>>= 0;
|
|
301
|
+
const id = this.mem.getInt32(sp + 8, true);
|
|
302
|
+
clearTimeout(this._scheduledTimeouts.get(id));
|
|
303
|
+
this._scheduledTimeouts.delete(id);
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
// func getRandomData(r []byte)
|
|
307
|
+
"runtime.getRandomData": (sp) => {
|
|
308
|
+
sp >>>= 0;
|
|
309
|
+
crypto.getRandomValues(loadSlice(sp + 8));
|
|
310
|
+
},
|
|
311
|
+
|
|
312
|
+
// func finalizeRef(v ref)
|
|
313
|
+
"syscall/js.finalizeRef": (sp) => {
|
|
314
|
+
sp >>>= 0;
|
|
315
|
+
const id = this.mem.getUint32(sp + 8, true);
|
|
316
|
+
this._goRefCounts[id]--;
|
|
317
|
+
if (this._goRefCounts[id] === 0) {
|
|
318
|
+
const v = this._values[id];
|
|
319
|
+
this._values[id] = null;
|
|
320
|
+
this._ids.delete(v);
|
|
321
|
+
this._idPool.push(id);
|
|
322
|
+
}
|
|
323
|
+
},
|
|
324
|
+
|
|
325
|
+
// func stringVal(value string) ref
|
|
326
|
+
"syscall/js.stringVal": (sp) => {
|
|
327
|
+
sp >>>= 0;
|
|
328
|
+
storeValue(sp + 24, loadString(sp + 8));
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
// func valueGet(v ref, p string) ref
|
|
332
|
+
"syscall/js.valueGet": (sp) => {
|
|
333
|
+
sp >>>= 0;
|
|
334
|
+
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
|
335
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
336
|
+
storeValue(sp + 32, result);
|
|
337
|
+
},
|
|
338
|
+
|
|
339
|
+
// func valueSet(v ref, p string, x ref)
|
|
340
|
+
"syscall/js.valueSet": (sp) => {
|
|
341
|
+
sp >>>= 0;
|
|
342
|
+
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
|
343
|
+
},
|
|
344
|
+
|
|
345
|
+
// func valueDelete(v ref, p string)
|
|
346
|
+
"syscall/js.valueDelete": (sp) => {
|
|
347
|
+
sp >>>= 0;
|
|
348
|
+
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
|
349
|
+
},
|
|
350
|
+
|
|
351
|
+
// func valueIndex(v ref, i int) ref
|
|
352
|
+
"syscall/js.valueIndex": (sp) => {
|
|
353
|
+
sp >>>= 0;
|
|
354
|
+
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
|
355
|
+
},
|
|
356
|
+
|
|
357
|
+
// valueSetIndex(v ref, i int, x ref)
|
|
358
|
+
"syscall/js.valueSetIndex": (sp) => {
|
|
359
|
+
sp >>>= 0;
|
|
360
|
+
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
|
361
|
+
},
|
|
362
|
+
|
|
363
|
+
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
|
364
|
+
"syscall/js.valueCall": (sp) => {
|
|
365
|
+
sp >>>= 0;
|
|
366
|
+
try {
|
|
367
|
+
const v = loadValue(sp + 8);
|
|
368
|
+
const m = Reflect.get(v, loadString(sp + 16));
|
|
369
|
+
const args = loadSliceOfValues(sp + 32);
|
|
370
|
+
const result = Reflect.apply(m, v, args);
|
|
371
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
372
|
+
storeValue(sp + 56, result);
|
|
373
|
+
this.mem.setUint8(sp + 64, 1);
|
|
374
|
+
} catch (err) {
|
|
375
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
376
|
+
storeValue(sp + 56, err);
|
|
377
|
+
this.mem.setUint8(sp + 64, 0);
|
|
378
|
+
}
|
|
379
|
+
},
|
|
380
|
+
|
|
381
|
+
// func valueInvoke(v ref, args []ref) (ref, bool)
|
|
382
|
+
"syscall/js.valueInvoke": (sp) => {
|
|
383
|
+
sp >>>= 0;
|
|
384
|
+
try {
|
|
385
|
+
const v = loadValue(sp + 8);
|
|
386
|
+
const args = loadSliceOfValues(sp + 16);
|
|
387
|
+
const result = Reflect.apply(v, undefined, args);
|
|
388
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
389
|
+
storeValue(sp + 40, result);
|
|
390
|
+
this.mem.setUint8(sp + 48, 1);
|
|
391
|
+
} catch (err) {
|
|
392
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
393
|
+
storeValue(sp + 40, err);
|
|
394
|
+
this.mem.setUint8(sp + 48, 0);
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
// func valueNew(v ref, args []ref) (ref, bool)
|
|
399
|
+
"syscall/js.valueNew": (sp) => {
|
|
400
|
+
sp >>>= 0;
|
|
401
|
+
try {
|
|
402
|
+
const v = loadValue(sp + 8);
|
|
403
|
+
const args = loadSliceOfValues(sp + 16);
|
|
404
|
+
const result = Reflect.construct(v, args);
|
|
405
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
406
|
+
storeValue(sp + 40, result);
|
|
407
|
+
this.mem.setUint8(sp + 48, 1);
|
|
408
|
+
} catch (err) {
|
|
409
|
+
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
|
410
|
+
storeValue(sp + 40, err);
|
|
411
|
+
this.mem.setUint8(sp + 48, 0);
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
|
|
415
|
+
// func valueLength(v ref) int
|
|
416
|
+
"syscall/js.valueLength": (sp) => {
|
|
417
|
+
sp >>>= 0;
|
|
418
|
+
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
// valuePrepareString(v ref) (ref, int)
|
|
422
|
+
"syscall/js.valuePrepareString": (sp) => {
|
|
423
|
+
sp >>>= 0;
|
|
424
|
+
const str = encoder.encode(String(loadValue(sp + 8)));
|
|
425
|
+
storeValue(sp + 16, str);
|
|
426
|
+
setInt64(sp + 24, str.length);
|
|
427
|
+
},
|
|
428
|
+
|
|
429
|
+
// valueLoadString(v ref, b []byte)
|
|
430
|
+
"syscall/js.valueLoadString": (sp) => {
|
|
431
|
+
sp >>>= 0;
|
|
432
|
+
const str = loadValue(sp + 8);
|
|
433
|
+
loadSlice(sp + 16).set(str);
|
|
434
|
+
},
|
|
435
|
+
|
|
436
|
+
// func valueInstanceOf(v ref, t ref) bool
|
|
437
|
+
"syscall/js.valueInstanceOf": (sp) => {
|
|
438
|
+
sp >>>= 0;
|
|
439
|
+
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
|
|
440
|
+
},
|
|
441
|
+
|
|
442
|
+
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
|
443
|
+
"syscall/js.copyBytesToGo": (sp) => {
|
|
444
|
+
sp >>>= 0;
|
|
445
|
+
const dst = loadSlice(sp + 8);
|
|
446
|
+
const src = loadValue(sp + 32);
|
|
447
|
+
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
|
448
|
+
this.mem.setUint8(sp + 48, 0);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const toCopy = src.subarray(0, dst.length);
|
|
452
|
+
dst.set(toCopy);
|
|
453
|
+
setInt64(sp + 40, toCopy.length);
|
|
454
|
+
this.mem.setUint8(sp + 48, 1);
|
|
455
|
+
},
|
|
456
|
+
|
|
457
|
+
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
|
458
|
+
"syscall/js.copyBytesToJS": (sp) => {
|
|
459
|
+
sp >>>= 0;
|
|
460
|
+
const dst = loadValue(sp + 8);
|
|
461
|
+
const src = loadSlice(sp + 16);
|
|
462
|
+
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
|
463
|
+
this.mem.setUint8(sp + 48, 0);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const toCopy = src.subarray(0, dst.length);
|
|
467
|
+
dst.set(toCopy);
|
|
468
|
+
setInt64(sp + 40, toCopy.length);
|
|
469
|
+
this.mem.setUint8(sp + 48, 1);
|
|
470
|
+
},
|
|
471
|
+
|
|
472
|
+
"debug": (value) => {
|
|
473
|
+
console.log(value);
|
|
474
|
+
},
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async run(instance) {
|
|
480
|
+
if (!(instance instanceof WebAssembly.Instance)) {
|
|
481
|
+
throw new Error("Go.run: WebAssembly.Instance expected");
|
|
482
|
+
}
|
|
483
|
+
this._inst = instance;
|
|
484
|
+
this.mem = new DataView(this._inst.exports.mem.buffer);
|
|
485
|
+
this._values = [ // JS values that Go currently has references to, indexed by reference id
|
|
486
|
+
NaN,
|
|
487
|
+
0,
|
|
488
|
+
null,
|
|
489
|
+
true,
|
|
490
|
+
false,
|
|
491
|
+
globalThis,
|
|
492
|
+
this,
|
|
493
|
+
];
|
|
494
|
+
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
|
|
495
|
+
this._ids = new Map([ // mapping from JS values to reference ids
|
|
496
|
+
[0, 1],
|
|
497
|
+
[null, 2],
|
|
498
|
+
[true, 3],
|
|
499
|
+
[false, 4],
|
|
500
|
+
[globalThis, 5],
|
|
501
|
+
[this, 6],
|
|
502
|
+
]);
|
|
503
|
+
this._idPool = []; // unused ids that have been garbage collected
|
|
504
|
+
this.exited = false; // whether the Go program has exited
|
|
505
|
+
|
|
506
|
+
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
|
|
507
|
+
let offset = 4096;
|
|
508
|
+
|
|
509
|
+
const strPtr = (str) => {
|
|
510
|
+
const ptr = offset;
|
|
511
|
+
const bytes = encoder.encode(str + "\0");
|
|
512
|
+
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
|
513
|
+
offset += bytes.length;
|
|
514
|
+
if (offset % 8 !== 0) {
|
|
515
|
+
offset += 8 - (offset % 8);
|
|
516
|
+
}
|
|
517
|
+
return ptr;
|
|
518
|
+
};
|
|
519
|
+
|
|
520
|
+
const argc = this.argv.length;
|
|
521
|
+
|
|
522
|
+
const argvPtrs = [];
|
|
523
|
+
this.argv.forEach((arg) => {
|
|
524
|
+
argvPtrs.push(strPtr(arg));
|
|
525
|
+
});
|
|
526
|
+
argvPtrs.push(0);
|
|
527
|
+
|
|
528
|
+
const keys = Object.keys(this.env).sort();
|
|
529
|
+
keys.forEach((key) => {
|
|
530
|
+
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
|
531
|
+
});
|
|
532
|
+
argvPtrs.push(0);
|
|
533
|
+
|
|
534
|
+
const argv = offset;
|
|
535
|
+
argvPtrs.forEach((ptr) => {
|
|
536
|
+
this.mem.setUint32(offset, ptr, true);
|
|
537
|
+
this.mem.setUint32(offset + 4, 0, true);
|
|
538
|
+
offset += 8;
|
|
539
|
+
});
|
|
540
|
+
|
|
541
|
+
// The linker guarantees global data starts from at least wasmMinDataAddr.
|
|
542
|
+
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
|
|
543
|
+
const wasmMinDataAddr = 4096 + 8192;
|
|
544
|
+
if (offset >= wasmMinDataAddr) {
|
|
545
|
+
throw new Error("total length of command line and environment variables exceeds limit");
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
this._inst.exports.run(argc, argv);
|
|
549
|
+
if (this.exited) {
|
|
550
|
+
this._resolveExitPromise();
|
|
551
|
+
}
|
|
552
|
+
await this._exitPromise;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
_resume() {
|
|
556
|
+
if (this.exited) {
|
|
557
|
+
throw new Error("Go program has already exited");
|
|
558
|
+
}
|
|
559
|
+
this._inst.exports.resume();
|
|
560
|
+
if (this.exited) {
|
|
561
|
+
this._resolveExitPromise();
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
_makeFuncWrapper(id) {
|
|
566
|
+
const go = this;
|
|
567
|
+
return function () {
|
|
568
|
+
const event = { id: id, this: this, args: arguments };
|
|
569
|
+
go._pendingEvent = event;
|
|
570
|
+
go._resume();
|
|
571
|
+
return event.result;
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
})();
|