mevento 3.0.4 → 4.0.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 CHANGED
@@ -1,59 +1,207 @@
1
- # Mevento
1
+ # MEvento TypeScript
2
2
 
3
- Mevento is a tiny VM one single file that handles `MEvento code` executions inside JS engine. `MEvento` is simple programming language that allows developers exposing an app host function, that way they have the ability to dynamically execute simple script that call host function.
3
+ MEvento is a tiny single-file scripting VM for host applications. The host keeps
4
+ control of native behavior by exposing functions, while scripts stored in a
5
+ database or loaded at runtime can compose those functions without rebuilding the
6
+ host app.
4
7
 
5
- The VM uses a AST Walker to execute MEvento script, so of course the performace is not its concern a lot.
8
+ This module is the TypeScript implementation. It provides synchronous
9
+ `MEvento` and async `MEventoAsync` runtimes.
6
10
 
7
- ## MEvento code syntax
8
- Syntaxically MEvento is a c-like language, but very limited: no function declaration, no class, just assignation, function call and conditional check.
11
+ ## v2 Status
12
+
13
+ v2 is a superset of v1 script syntax, with stricter diagnostics and new
14
+ runtime helpers. Existing v1 scripts should still parse and execute in v2.
15
+
16
+ By default, v2 is stricter: unknown host functions raise `unknown_function`
17
+ instead of silently returning `null`. For existing database scripts that depend
18
+ on the v1 behavior, run the VM with `{ compatV1: true }`. In that mode, missing
19
+ host functions return `null` and instance validation does not report them as
20
+ unknown. New scripts should prefer strict mode and wrap risky calls in `_try_`
21
+ when a script should continue after failure.
22
+
23
+ v2 additions include:
24
+
25
+ - Dot property access: `user.name` is equivalent to `user['name']`.
26
+ - `_try_` result capture and helper functions.
27
+ - Function specs with arity, argument type hints, tags, and return type hints.
28
+ - Script manifest validation for required host functions, inputs, and outputs.
29
+ - Trace mode and execution step budgets.
30
+ - v1 compatibility mode for existing scripts that call optional host functions.
31
+ - Minimal collection built-ins for arrays and maps.
32
+
33
+ ## Script Syntax
34
+
35
+ MEvento is intentionally small and C-like. It has no user-defined functions and
36
+ no classes. The host application owns the real logic.
37
+
38
+ Supported syntax includes assignments, expressions, host calls, object and
39
+ array literals, bracket and dot access, `if`, `while`, numeric `for`,
40
+ `for ... in`, `break`, `continue`, `return`, `??`, comments, and multilingual
41
+ keyword dictionaries.
42
+
43
+ Example:
9
44
 
10
45
  ```js
11
- a = 12
12
- a = 23
13
- b = functon1()
14
- c = function2()
15
- d = a + b
16
- if(a == b) {
17
- log('a = b')
18
- } else {
19
- log("a != b")
46
+ user = loadUser()
47
+ name = user.profile.name ?? 'anonymous'
48
+
49
+ items = []
50
+ _push_(items, name)
51
+
52
+ if (_len_(items) > 0) {
53
+ log(items[0])
20
54
  }
21
55
  ```
22
56
 
23
- ## How to use
24
- The host application can expose functions through Mevento VM that way:
57
+ ## Built-In Functions
58
+
59
+ Result helpers:
60
+
61
+ ```text
62
+ _try_(expression) # returns {ok, value, error}; evaluates lazily
63
+ _ok_(result)
64
+ _err_(result)
65
+ _value_(result, fallback)
66
+ _error_(result)
67
+ _code_(result)
68
+ _message_(result)
69
+ _unwrap_(result)
70
+ ```
71
+
72
+ Collection helpers:
73
+
74
+ ```text
75
+ _len_(array|object|string)
76
+ _push_(array, value) # mutates array, returns array
77
+ _pop_(array) # mutates array, returns removed value or null
78
+ _insert_(array, index, value)
79
+ _remove_at_(array, index) # mutates array, returns removed value or null
80
+ _has_(object, key)
81
+ _keys_(object)
82
+ _values_(object)
83
+ ```
84
+
85
+ Invalid built-in argument types raise `invalid_argument_type` and can be
86
+ captured with `_try_`.
87
+
88
+ ## Usage
89
+
90
+ Register global functions:
91
+
92
+ ```ts
93
+ import { MEvento } from "mevento";
94
+
95
+ MEvento.register("log", (args) => {
96
+ console.log(...args);
97
+ return null;
98
+ });
99
+
100
+ MEvento.register("add", (args) => Number(args[0]) + Number(args[1]), {
101
+ name: "add",
102
+ minArgs: 2,
103
+ maxArgs: 2,
104
+ args: [
105
+ { name: "left", type: "number" },
106
+ { name: "right", type: "number" },
107
+ ],
108
+ returnType: "number",
109
+ });
110
+
111
+ const value = MEvento.run("add(12, 23)");
112
+ ```
113
+
114
+ Use one VM instance:
115
+
25
116
  ```ts
26
- import {MEvento} from 'mevento';
27
- MEvento.register('log', (args) => console.log); // exposes console.log through MEvento as log function
28
- MEvento.register('cos2', (args) => Math.cos);
117
+ import { MEvento } from "mevento";
118
+
119
+ const vm = MEvento.newInstance();
120
+
121
+ vm.registerFunction("loadUser", () => ({ profile: { name: "Awa" } }), {
122
+ name: "loadUser",
123
+ maxArgs: 0,
124
+ returnType: "object",
125
+ });
126
+
127
+ const result = vm.execute("loadUser().profile.name");
29
128
  ```
30
129
 
31
- Let's assume you want to execute a `MEvento code`:
130
+ Use async host functions:
32
131
 
33
132
  ```ts
34
- import {MEvento} from 'mevento';
133
+ import { MEventoAsync } from "mevento";
134
+
135
+ const vm = MEventoAsync.newInstance();
35
136
 
36
- const mevento = MEvento.newInstance();
137
+ vm.registerFunction("fetchUser", async () => ({ name: "Awa" }), {
138
+ name: "fetchUser",
139
+ maxArgs: 0,
140
+ returnType: "object",
141
+ });
37
142
 
38
- mevento.execute(`log("molo")`)
143
+ const name = await vm.execute("fetchUser().name");
144
+ ```
39
145
 
146
+ Inject host input for one run:
147
+
148
+ ```ts
149
+ const total = MEvento.run("base + bonus", false, {
150
+ base: 12,
151
+ bonus: 23,
152
+ });
40
153
  ```
41
154
 
42
- `MEvento` instance execution is syncrhrone, that's to say, if you wan to consume `async` function exposed through Mevento, you nee to use `MEventoAsync` instead.
155
+ ## Validation And Manifests
43
156
 
157
+ Function specs drive preflight validation and runtime argument checks:
44
158
 
45
159
  ```ts
46
- import {MEvento} from 'mevento';
160
+ const validation = vm.validate("add(12)");
161
+ if (!validation.ok) {
162
+ console.log(validation.errors);
163
+ }
164
+ ```
165
+
166
+ Manifest validation checks required functions, inputs, and outputs:
167
+
168
+ ```ts
169
+ const manifest = {
170
+ functions: {
171
+ add: { name: "add", minArgs: 2, maxArgs: 2, returnType: "number" },
172
+ },
173
+ inputs: [{ name: "base", type: "number" }],
174
+ outputs: [{ name: "result", type: "number" }],
175
+ };
176
+
177
+ const checked = MEvento.validateManifestSource(
178
+ "result = add(base, 2)",
179
+ manifest,
180
+ );
181
+ ```
182
+
183
+ ## Options: Compatibility, Trace And Budgets
47
184
 
48
- MEvento.register('async', async (args) => await asyncF(args[0]));
49
- const mevento = MEventoAsync.newInstance();
185
+ Use options to enable v1 compatibility for existing scripts, cap execution
186
+ steps, or collect a lightweight trace:
50
187
 
51
- await mevento.execute(`async("molo")`)
188
+ ```ts
189
+ const legacyVm = MEvento.newInstance({ compatV1: true });
190
+ legacyVm.execute("optionalHostFunction()"); // returns null when missing
52
191
 
192
+ const vm = MEvento.newInstance({ maxSteps: 1000, trace: true });
193
+ vm.execute("log('ok')");
194
+
195
+ const trace = vm.trace();
53
196
  ```
54
- `execute` method on `MEventoAsync` instance return a `Promise`.
55
197
 
198
+ ## Development
56
199
 
57
- ## Notes
58
- MEvento does not have scope variables, all variables are visible everywhere.
200
+ ```bash
201
+ npm install
202
+ npm run build
203
+ npm run test:conformance
204
+ ```
59
205
 
206
+ The package currently uses a custom conformance command. Do not use `npm test`
207
+ unless package metadata is updated.
@@ -45,6 +45,7 @@ declare class TokenType {
45
45
  static CONTINUE: number;
46
46
  static nullity: number;
47
47
  static RETURN: number;
48
+ static dot: number;
48
49
  }
49
50
  declare class Token {
50
51
  type: number;
@@ -73,6 +74,90 @@ declare abstract class AST {
73
74
  constructor(line?: number, col?: number);
74
75
  dump(): string;
75
76
  }
77
+ declare class MEventoRuntimeError extends Error {
78
+ line?: number;
79
+ col?: number;
80
+ nodeType?: string;
81
+ cause?: unknown;
82
+ detail: string;
83
+ code: string;
84
+ diagnosticName?: string;
85
+ argCount?: number;
86
+ minArgs?: number;
87
+ maxArgs?: number;
88
+ argIndex?: number;
89
+ expectedType?: string;
90
+ actualType?: string;
91
+ stepCount?: number;
92
+ maxSteps?: number;
93
+ constructor(detail: string, line?: number, col?: number, nodeType?: string, cause?: unknown, diagnostic?: Partial<Omit<MEventoDiagnostic, "message" | "line" | "col" | "node">>);
94
+ static fromNode(node: AST, error: unknown): MEventoRuntimeError;
95
+ private static format;
96
+ diagnostic(): MEventoDiagnostic;
97
+ }
98
+ type MEventoDiagnostic = {
99
+ code: string;
100
+ message: string;
101
+ name?: string;
102
+ line?: number;
103
+ col?: number;
104
+ node?: string;
105
+ argCount?: number;
106
+ minArgs?: number;
107
+ maxArgs?: number;
108
+ argIndex?: number;
109
+ expectedType?: string;
110
+ actualType?: string;
111
+ stepCount?: number;
112
+ maxSteps?: number;
113
+ };
114
+ type MEventoValidationError = MEventoDiagnostic;
115
+ type MEventoValidationResult = {
116
+ ok: boolean;
117
+ errors: MEventoValidationError[];
118
+ };
119
+ type MEventoFunctionSpec = {
120
+ name: string;
121
+ minArgs?: number;
122
+ maxArgs?: number;
123
+ tags?: Iterable<string>;
124
+ args?: MEventoArgSpec[];
125
+ returnType?: string;
126
+ };
127
+ type MEventoArgSpec = {
128
+ name: string;
129
+ type?: string;
130
+ required?: boolean;
131
+ };
132
+ type MEventoOptions = {
133
+ maxSteps?: number;
134
+ trace?: boolean;
135
+ compatV1?: boolean;
136
+ };
137
+ type MEventoValueSpec = {
138
+ name: string;
139
+ type?: string;
140
+ required?: boolean;
141
+ };
142
+ type MEventoScriptManifest = {
143
+ functions?: MEventoFunctionList;
144
+ inputs?: MEventoValueSpec[];
145
+ outputs?: MEventoValueSpec[];
146
+ };
147
+ type MEventoTraceEvent = {
148
+ kind: string;
149
+ line?: number;
150
+ col?: number;
151
+ node?: string;
152
+ name?: string;
153
+ stepCount?: number;
154
+ detail: {
155
+ [name: string]: unknown;
156
+ };
157
+ };
158
+ type MEventoFunctionList = Set<string> | string[] | MEventoFunctionSpec[] | {
159
+ [name: string]: MEventoFunctionSpec;
160
+ };
76
161
  declare class RootAST extends AST {
77
162
  body: AST[];
78
163
  source: string;
@@ -220,6 +305,7 @@ declare abstract class ANodeVisitor {
220
305
  declare abstract class NodeVisitor extends ANodeVisitor {
221
306
  constructor();
222
307
  visit(node: AST): any;
308
+ protected beforeVisit(_node: AST): void;
223
309
  protected assignProperty(owner: any, property: any, value: any): any;
224
310
  protected abstract visitRootAST(node: RootAST): any;
225
311
  protected abstract visitBlockStatementAST(node: BlockStatementAST): any;
@@ -261,17 +347,43 @@ declare class MEvento extends NodeVisitor {
261
347
  protected currentScope?: MEventScope;
262
348
  debug: boolean;
263
349
  private static _globalFunctionsRegistry;
350
+ private static _globalFunctionSpecs;
264
351
  private static _cache;
265
352
  protected _functionsRegistry: {
266
353
  [k: string]: MEventoFBinding;
267
354
  };
355
+ protected _functionSpecs: {
356
+ [k: string]: MEventoFunctionSpec;
357
+ };
268
358
  protected _functionResolver?: (name: string) => MEventoFBinding | undefined;
269
- constructor();
359
+ protected _options: MEventoOptions;
360
+ private _executionStepCount;
361
+ private _traceEvents;
362
+ constructor(options?: MEventoOptions);
363
+ get options(): MEventoOptions;
364
+ get executionStepCount(): number;
365
+ trace(): MEventoTraceEvent[];
366
+ protected resetExecutionBudget(): void;
367
+ protected beforeVisit(node: AST): void;
368
+ protected clearTrace(): void;
369
+ protected recordTrace(kind: string, node: AST, name?: string, detail?: {
370
+ [name: string]: unknown;
371
+ }): void;
270
372
  protected resolve(name: string): any;
271
373
  protected changeVariable(name: string, value: any): any;
272
374
  protected pushScope(name: string): void;
273
375
  protected popScope(): void;
274
376
  protected log(message: any): void;
377
+ protected successResult(value: any): {
378
+ ok: boolean;
379
+ value: any;
380
+ error: any;
381
+ };
382
+ protected errorResult(error: MEventoRuntimeError): {
383
+ ok: boolean;
384
+ value: any;
385
+ error: MEventoDiagnostic;
386
+ };
275
387
  protected visitRootAST(node: RootAST): any;
276
388
  protected visitBlockStatementAST(node: BlockStatementAST): any;
277
389
  protected visitIdentifierAST(node: IdentifierAST): any;
@@ -297,23 +409,54 @@ declare class MEvento extends NodeVisitor {
297
409
  resolveArguments(args: AST[]): any;
298
410
  setFunctionResolver(resolver: (name: string) => MEventoFBinding | undefined): void;
299
411
  resolveFunction(name: string): MEventoFBinding | undefined;
300
- registerFunction(id: string, fn: MEventoFBinding): void;
412
+ resolveFunctionSpec(name: string): MEventoFunctionSpec | undefined;
413
+ capabilities(): {
414
+ [name: string]: MEventoFunctionSpec;
415
+ };
416
+ registerFunction(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
301
417
  unregisterFunction(id: string): void;
418
+ validate(source: string, functions?: MEventoFunctionList, cache?: boolean): MEventoValidationResult;
419
+ validateManifest(source: string, manifest: MEventoScriptManifest, cache?: boolean): MEventoValidationResult;
420
+ protected validationFunctionSpecs(functions?: MEventoFunctionList): Map<string, MEventoFunctionSpec>;
421
+ protected validateNode(node: AST | null | undefined, knownFunctions: Map<string, MEventoFunctionSpec>, errors: MEventoValidationError[], protectedByTry?: boolean): void;
422
+ protected validateCallExpression(node: CallExpressionAST, knownFunctions: Map<string, MEventoFunctionSpec>, errors: MEventoValidationError[], protectedByTry: boolean): void;
423
+ protected validateStaticArgumentTypes(node: CallExpressionAST, spec: MEventoFunctionSpec, errors: MEventoValidationError[]): void;
424
+ protected staticArgumentType(node: AST): string | undefined;
425
+ protected argumentTypeMatches(spec: MEventoArgSpec, actualType: string): boolean;
426
+ protected validateManifestNode(module: AST, manifest: MEventoScriptManifest, errors: MEventoValidationError[]): void;
427
+ protected analyzeManifestNode(node: AST | null | undefined, analysis: {
428
+ knownInputs: Set<string>;
429
+ assigned: Set<string>;
430
+ assignedTypes: Map<string, string>;
431
+ reportedInputs: Set<string>;
432
+ }, errors: MEventoValidationError[]): void;
433
+ protected markAssignedTarget(node: AST, assignedType: string | undefined, analysis: {
434
+ assigned: Set<string>;
435
+ assignedTypes: Map<string, string>;
436
+ }): void;
437
+ protected valueSpecTypeMatches(spec: MEventoValueSpec, actualType: string): boolean;
438
+ protected validationError(code: string, node: AST, message: string, name?: string, diagnostic?: Pick<MEventoDiagnostic, "argCount" | "minArgs" | "maxArgs" | "argIndex" | "expectedType" | "actualType">): MEventoValidationError;
439
+ protected validateRuntimeArgumentTypes(node: AST, spec: MEventoFunctionSpec, values: unknown[]): void;
302
440
  execute(source: string, cache?: boolean, input?: {
303
441
  [k: string]: any;
304
442
  }): any;
305
443
  static compile(source: string, cache?: boolean): AST;
306
- static register(id: string, fn: MEventoFBinding): void;
444
+ static register(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
307
445
  static unregister(id: string): void;
446
+ static capabilities(): {
447
+ [name: string]: MEventoFunctionSpec;
448
+ };
449
+ static validateSource(source: string, functions: MEventoFunctionList, cache?: boolean): MEventoValidationResult;
450
+ static validateManifestSource(source: string, manifest: MEventoScriptManifest, cache?: boolean): MEventoValidationResult;
308
451
  static run(source: string, cache?: boolean, input?: {
309
452
  [k: string]: any;
310
- }): any;
311
- static newInstance(): MEvento;
453
+ }, options?: MEventoOptions): any;
454
+ static newInstance(options?: MEventoOptions): MEvento;
312
455
  clone(): MEvento;
313
456
  newAsyncInstance(): MEventoAsync;
314
457
  }
315
458
  declare class MEventoAsync extends MEvento {
316
- constructor();
459
+ constructor(options?: MEventoOptions);
317
460
  protected visitRootAST(node: RootAST): Promise<any>;
318
461
  protected visitBlockStatementAST(node: BlockStatementAST): Promise<any>;
319
462
  protected visitIdentifierAST(node: AST): Promise<any>;
@@ -334,16 +477,16 @@ declare class MEventoAsync extends MEvento {
334
477
  protected visitForOfStatement(node: ForOfStatement): Promise<any[] | ReturnBranch>;
335
478
  protected visitReturnAST(node: ReturnAST): Promise<any>;
336
479
  resolveArgumentsAsync(args: AST[]): Promise<any[]>;
337
- registerFunction(id: string, fn: MEventoFBinding): void;
480
+ registerFunction(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
338
481
  unregisterFunction(id: string): void;
339
482
  execute(source: string, cache?: boolean, input?: {
340
483
  [k: string]: any;
341
484
  }): Promise<any>;
342
485
  static run(source: string, cache?: boolean, input?: {
343
486
  [k: string]: any;
344
- }): Promise<any>;
345
- static newInstance(): MEventoAsync;
487
+ }, options?: MEventoOptions): Promise<any>;
488
+ static newInstance(options?: MEventoOptions): MEventoAsync;
346
489
  clone(): MEventoAsync;
347
490
  }
348
491
 
349
- export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, MEventoAsync, type MEventoFBinding, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
492
+ export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };