mevento 4.0.1 → 4.0.2
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 +21 -0
- package/README.md +17 -10
- package/dist/cjs/index.js +1 -1
- package/dist/esm/index.mjs +1 -1
- package/package.json +13 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Mahamadou DOUMBIA
|
|
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
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,17 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mevento — Embedded scripting for JavaScript and TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
`mevento` is an npm package providing an embeddable C-like scripting language
|
|
4
|
+
and virtual machine for JavaScript and TypeScript host applications. The host
|
|
5
|
+
keeps control of native behavior by exposing functions, while scripts stored in
|
|
6
|
+
a database or loaded at runtime can compose those functions without rebuilding
|
|
7
|
+
the host application.
|
|
7
8
|
|
|
8
|
-
|
|
9
|
-
`MEvento` and async `MEventoAsync` runtimes.
|
|
9
|
+
It provides the synchronous `MEvento` and asynchronous `MEventoAsync` runtimes.
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Installation
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
```bash
|
|
14
|
+
npm install mevento
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Language v2 Status
|
|
18
|
+
|
|
19
|
+
MEvento language v2 is a superset of v1 script syntax, with stricter diagnostics
|
|
20
|
+
and new runtime helpers. The language version is separate from the npm package
|
|
21
|
+
version. Existing v1 scripts should still parse and execute in language v2.
|
|
15
22
|
|
|
16
23
|
By default, v2 is stricter: unknown host functions raise `unknown_function`
|
|
17
24
|
instead of silently returning `null`. For existing database scripts that depend
|
package/dist/cjs/index.js
CHANGED
|
@@ -5,4 +5,4 @@ var mt=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Lt=Objec
|
|
|
5
5
|
`,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let a=this._literalString(r);return this._advance(),a}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new X("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new X("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new X("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var gt=k,m=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class s extends Error{constructor(e,t,n,r,a,o){var u;super(s.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=a,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof s)return t;let n=t instanceof Error?t.message:String(t);return new s(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let a=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${a}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(s,e){var r;let t={name:s,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map(Vt):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if((e==null?void 0:e.description)!=null&&(t.description=e.description),(e==null?void 0:e.returnDescription)!=null&&(t.returnDescription=e.returnDescription),(e==null?void 0:e.examples)!=null&&(t.examples=e.examples.map(Ct)),(e==null?void 0:e.metadata)!=null&&(t.metadata=lt(e.metadata)),t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=J(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!bt.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function Vt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(s.description!=null&&(e.description=s.description),s.metadata!=null&&(e.metadata=lt(s.metadata)),!qt.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var bt=new Set(["any","null","boolean","number","string","array","object"]),qt=bt;function jt(s){var t,n;let e={maxSteps:s==null?void 0:s.maxSteps,trace:(t=s==null?void 0:s.trace)!=null?t:!1,compatV1:(n=s==null?void 0:s.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function wt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(!bt.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function ct(s){return Array.isArray(s)?s.map(ct):s!=null&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ct(t)])):s}function lt(s){return s==null?void 0:ct(s)}function Ct(s){let e={script:s.script};return s.title!=null&&(e.title=s.title),s.result!==void 0&&(e.result=ct(s.result)),s.description!=null&&(e.description=s.description),e}function Pt(s){var t;let e={name:s.name,minArgs:s.minArgs,maxArgs:s.maxArgs,tags:s.tags?Array.from(s.tags):[],args:s.args?s.args.map(n=>{let r={name:n.name,type:n.type,required:n.required};return n.description!=null&&(r.description=n.description),n.metadata!=null&&(r.metadata=lt(n.metadata)),r}):[],returnType:(t=s.returnType)!=null?t:"any"};return s.description!=null&&(e.description=s.description),s.returnDescription!=null&&(e.returnDescription=s.returnDescription),s.examples!=null&&(e.examples=s.examples.map(Ct)),s.metadata!=null&&(e.metadata=lt(s.metadata)),e}function Tt(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,Pt(t)]))}function dt(s,e){let t=J(s);return!(t!=null&&e<t||s.maxArgs!=null&&e>s.maxArgs)}function J(s){var n;let e=0;if(s.args){for(let r=s.args.length-1;r>=0;r-=1)if((n=s.args[r].required)==null||n){e=r+1;break}}let t=[s.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function _t(s){let e=J(s);return e==null&&s.maxArgs==null?"any number of":e!=null&&s.maxArgs!=null&&e===s.maxArgs?String(e):e!=null&&s.maxArgs!=null?`${e}..${s.maxArgs}`:e!=null?`at least ${e}`:`at most ${s.maxArgs}`}function et(s){return s==null?"null":typeof s=="boolean"?"boolean":typeof s=="number"?"number":typeof s=="string"?"string":Array.isArray(s)?"array":"object"}var q=class extends m{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
|
|
6
6
|
`;return e+="}",e}},F=class extends m{constructor(e,t){super(t.line,t.col),this.body=e}toString(){return`{
|
|
7
7
|
${this.body.map(e=>e.toString()).join(`
|
|
8
|
-
`)}}`}},E=class extends m{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},A=class extends m{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends m{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},G=class extends m{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},j=class extends m{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},P=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},z=class extends m{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},U=class extends m{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},D=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends m{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},I=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},$=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends m{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},W=class extends m{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},B=class extends m{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},K=class extends m{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},N=class extends m{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},Z=class extends m{constructor(e,t){super(e,t)}},H=class extends m{constructor(e,t,n){super(t,n),this.value=e}},tt=class extends m{constructor(e,t){super(e,t)}};function zt(s){return s instanceof q?"RootAST":s instanceof F?"BlockStatementAST":s instanceof E?"IdentifierAST":s instanceof A?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof G?"ExpressionStatementAST":s instanceof j?"CallExpressionAST":s instanceof P?"BinaryExpressionAST":s instanceof z?"UnaryExpressionAST":s instanceof U?"IfStatementAST":s instanceof D?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof I?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof $?"ArrayExpression":s instanceof W?"WhileLoopStatement":s instanceof B?"ForLoopStatement":s instanceof K?"ForOfStatement":s instanceof N?"TupleExpression":s instanceof Z?"BreakAST":s instanceof H?"ReturnAST":s instanceof tt?"ContinueAST":s.constructor.name}var St=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},nt=class nt{constructor(e){this._loopTrack=new St;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new E(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new H(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new z(e,this._term());case i.numberConst:return this._eat(i.numberConst),new A(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new A(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new A(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new A(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new Z((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new tt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new D(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof E||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new A(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new A(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new I(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new $(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new A(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=nt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=nt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new P(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof E||T(this.currentToken),new j(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){var n;if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new F([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),((n=this.currentToken)==null?void 0:n.type)===i.rbrace&&this._eat(i.rbrace),new F(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new U(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new W(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new N(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new A(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new B(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new q(n,t,e)}parse(){return this._root()}};nt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var yt=nt,R=class{},C=class extends R{},M=class extends R{},y=class{constructor(e){this.value=e}},At=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},ht=class extends At{constructor(){super(),this.registerVisitor(q,this.visitRootAST),this.registerVisitor(F,this.visitBlockStatementAST),this.registerVisitor(E,this.visitIdentifierAST),this.registerVisitor(A,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(G,this.visitExpressionStatementAST),this.registerVisitor(j,this.visitCallExpressionAST),this.registerVisitor(P,this.visitBinaryExpressionAST),this.registerVisitor(z,this.visitUnaryExpressionAST),this.registerVisitor(U,this.visitIfStatementAST),this.registerVisitor(D,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor(I,this.visitObjectExpression),this.registerVisitor($,this.visitArrayExpression),this.registerVisitor(W,this.visitWhileLoopStatement),this.registerVisitor(B,this.visitForLoopStatement),this.registerVisitor(K,this.visitForOfStatement),this.registerVisitor(Z,this.visitBreakAST),this.registerVisitor(tt,this.visitContinueAST),this.registerVisitor(H,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},rt=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},st={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function at(s){return typeof s=="object"&&s!=null&&s.ok===!0}function ut(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function V(s){return typeof s=="number"?s:void 0}function Q(s){return typeof s=="string"?s:void 0}function Ut(s){var t,n;let e=ut(s);return new S((t=Q(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",V(e==null?void 0:e.line),V(e==null?void 0:e.col),Q(e==null?void 0:e.node),void 0,{code:(n=Q(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:Q(e==null?void 0:e.name),argCount:V(e==null?void 0:e.argCount),minArgs:V(e==null?void 0:e.minArgs),maxArgs:V(e==null?void 0:e.maxArgs),argIndex:V(e==null?void 0:e.argIndex),expectedType:Q(e==null?void 0:e.expectedType),actualType:Q(e==null?void 0:e.actualType),stepCount:V(e==null?void 0:e.stepCount),maxSteps:V(e==null?void 0:e.maxSteps)})}function ft(s,e,t,n){let r=et(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function ot(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ft(s,t,"array",n)}function vt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ft(s,t,"object",n)}function kt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ft(s,t,"number",n)}function Dt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Wt={_ok_:s=>at(s[0]),_err_:s=>!at(s[0]),_value_:s=>{var e,t;return at(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=ut(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(at(s[0]))return(e=s[0].value)!=null?e:null;throw Ut(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ft("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=ot("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=ot("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=ot("_insert_",s,0),t=kt("_insert_",s,1);if(t<0||t>e.length)throw Dt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=ot("_remove_at_",s,0),t=kt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(vt("_has_",s,0),s[1]),_keys_:s=>Object.keys(vt("_keys_",s,0)),_values_:s=>Object.values(vt("_values_",s,0))},_=class _ extends ht{constructor(t){super();this.rootScope=new rt("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=jt(t),this._functionsRegistry={...Wt,..._._globalFunctionsRegistry},this._functionSpecs={...st,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:zt(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new rt(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof R||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof E&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var v,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let x=this.visit(r[0]);return x instanceof R||x instanceof y?x:this.successResult(x)}catch(x){if(x instanceof S)return this.errorResult(x);throw x}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!dt(u,r.length))throw new S(`Function '${a}' expects ${_t(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:J(u),maxArgs:u.maxArgs});let p=r.map(x=>this.visit(x));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(v=u==null?void 0:u.returnType)!=null?v:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:et(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(Y(o)&&h(u))return o.repeat(u);if(h(o)&&Y(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return b(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return b(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=b(r);return t.operator.type===i.and?a?b(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:b(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=Y(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;b(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return b(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof N){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return Tt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(st).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:st[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof q||t instanceof F?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof G?this.validateNode(t.expression,n,r,a):t instanceof j?this.validateCallExpression(t,n,r,a):t instanceof P?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof z?this.validateNode(t.argument,n,r,a):t instanceof U?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof D?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof I?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof $?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof W?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof B?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof N?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof H&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?dt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${_t(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:J(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var v,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(v=o.type)!=null?v:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof A)return et(t.value);if(t instanceof $)return"array";if(t instanceof I)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(wt),o=((f=n.outputs)!=null?f:[]).map(wt),u={knownInputs:new Set(a.map(v=>v.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(v=>{var x,Et,xt;if(((x=v.required)==null||x)&&!u.assigned.has(v.name)){r.push(this.validationError("missing_output",t,`Required output '${v.name}' is not assigned`,v.name));return}let d=u.assignedTypes.get(v.name);!d||this.valueSpecTypeMatches(v,d)||r.push(this.validationError("invalid_output_type",t,`Output '${v.name}' expects ${(Et=v.type)!=null?Et:"any"}, got ${d}`,v.name,{expectedType:(xt=v.type)!=null?xt:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof q||t instanceof F?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof G?this.analyzeManifestNode(t.expression,n,r):t instanceof j?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof P?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof z?this.analyzeManifestNode(t.argument,n,r):t instanceof U?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof D?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof I?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof $?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof W?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof B?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof K?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof N?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof H?this.analyzeManifestNode(t.value,n,r):t instanceof E&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof E?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof N&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,v;if(u>=r.length)return;let p=et(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(v=o.type)!=null?v:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Rt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new gt(t),u=new yt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return Tt({...st,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=pt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var it=_,pt=class s extends it{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof R||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof E&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,v;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof R||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!dt(o,n.length))throw new S(`Function '${r}' expects ${_t(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:J(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(v=o==null?void 0:o.returnType)!=null?v:"any",actualType:et(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(Y(a)&&h(o))return a.repeat(o);if(h(a)&&Y(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return b(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return b(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=b(n);return e.operator.type===i.and?r?b(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:b(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=Y(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;b(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return b(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=it.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};0&&(module.exports={AST,ArrayExpression,AssignmentExpressionAST,BinaryExpressionAST,BlockStatementAST,BreakAST,BreakBranch,CallExpressionAST,ContinueAST,ContinueBranch,ExpressionStatementAST,ForLoopStatement,ForOfStatement,IdentifierAST,IfStatementAST,IndexAccessorAST,LexerDictionary,LiteralAST,LogicalExpressionAST,LoopControl,MEventScope,MEvento,MEventoAsync,MEventoRuntimeError,NodeVisitor,ObjectExpression,ObjectProperty,ReturnAST,ReturnBranch,RootAST,Token,TokenType,TupleExpression,UnaryExpressionAST,WhileLoopStatement});
|
|
8
|
+
`)}}`}},E=class extends m{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},A=class extends m{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends m{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},G=class extends m{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},j=class extends m{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},P=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},z=class extends m{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},U=class extends m{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},D=class extends m{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends m{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},I=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},$=class extends m{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends m{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},W=class extends m{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},B=class extends m{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},K=class extends m{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},N=class extends m{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},Z=class extends m{constructor(e,t){super(e,t)}},H=class extends m{constructor(e,t,n){super(t,n),this.value=e}},tt=class extends m{constructor(e,t){super(e,t)}};function zt(s){return s instanceof q?"RootAST":s instanceof F?"BlockStatementAST":s instanceof E?"IdentifierAST":s instanceof A?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof G?"ExpressionStatementAST":s instanceof j?"CallExpressionAST":s instanceof P?"BinaryExpressionAST":s instanceof z?"UnaryExpressionAST":s instanceof U?"IfStatementAST":s instanceof D?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof I?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof $?"ArrayExpression":s instanceof W?"WhileLoopStatement":s instanceof B?"ForLoopStatement":s instanceof K?"ForOfStatement":s instanceof N?"TupleExpression":s instanceof Z?"BreakAST":s instanceof H?"ReturnAST":s instanceof tt?"ContinueAST":s.constructor.name}var St=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},nt=class nt{constructor(e){this._loopTrack=new St;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new E(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new H(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new z(e,this._term());case i.numberConst:return this._eat(i.numberConst),new A(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new A(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new A(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new A(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new Z((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new tt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new D(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof E||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new A(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new A(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new I(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new $(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new A(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=nt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=nt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new P(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof E||T(this.currentToken),new j(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof,i.rbrace].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new F([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),new F(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new U(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new W(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new N(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new A(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new B(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new q(n,t,e)}parse(){return this._root()}};nt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var yt=nt,R=class{},C=class extends R{},M=class extends R{},y=class{constructor(e){this.value=e}},At=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},ht=class extends At{constructor(){super(),this.registerVisitor(q,this.visitRootAST),this.registerVisitor(F,this.visitBlockStatementAST),this.registerVisitor(E,this.visitIdentifierAST),this.registerVisitor(A,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(G,this.visitExpressionStatementAST),this.registerVisitor(j,this.visitCallExpressionAST),this.registerVisitor(P,this.visitBinaryExpressionAST),this.registerVisitor(z,this.visitUnaryExpressionAST),this.registerVisitor(U,this.visitIfStatementAST),this.registerVisitor(D,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor(I,this.visitObjectExpression),this.registerVisitor($,this.visitArrayExpression),this.registerVisitor(W,this.visitWhileLoopStatement),this.registerVisitor(B,this.visitForLoopStatement),this.registerVisitor(K,this.visitForOfStatement),this.registerVisitor(Z,this.visitBreakAST),this.registerVisitor(tt,this.visitContinueAST),this.registerVisitor(H,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},rt=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},st={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function at(s){return typeof s=="object"&&s!=null&&s.ok===!0}function ut(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function V(s){return typeof s=="number"?s:void 0}function Q(s){return typeof s=="string"?s:void 0}function Ut(s){var t,n;let e=ut(s);return new S((t=Q(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",V(e==null?void 0:e.line),V(e==null?void 0:e.col),Q(e==null?void 0:e.node),void 0,{code:(n=Q(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:Q(e==null?void 0:e.name),argCount:V(e==null?void 0:e.argCount),minArgs:V(e==null?void 0:e.minArgs),maxArgs:V(e==null?void 0:e.maxArgs),argIndex:V(e==null?void 0:e.argIndex),expectedType:Q(e==null?void 0:e.expectedType),actualType:Q(e==null?void 0:e.actualType),stepCount:V(e==null?void 0:e.stepCount),maxSteps:V(e==null?void 0:e.maxSteps)})}function ft(s,e,t,n){let r=et(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function ot(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ft(s,t,"array",n)}function vt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ft(s,t,"object",n)}function kt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ft(s,t,"number",n)}function Dt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Wt={_ok_:s=>at(s[0]),_err_:s=>!at(s[0]),_value_:s=>{var e,t;return at(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=ut(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=ut(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(at(s[0]))return(e=s[0].value)!=null?e:null;throw Ut(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ft("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=ot("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=ot("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=ot("_insert_",s,0),t=kt("_insert_",s,1);if(t<0||t>e.length)throw Dt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=ot("_remove_at_",s,0),t=kt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(vt("_has_",s,0),s[1]),_keys_:s=>Object.keys(vt("_keys_",s,0)),_values_:s=>Object.values(vt("_values_",s,0))},_=class _ extends ht{constructor(t){super();this.rootScope=new rt("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=jt(t),this._functionsRegistry={...Wt,..._._globalFunctionsRegistry},this._functionSpecs={...st,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:zt(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new rt(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof R||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof E&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var v,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let x=this.visit(r[0]);return x instanceof R||x instanceof y?x:this.successResult(x)}catch(x){if(x instanceof S)return this.errorResult(x);throw x}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!dt(u,r.length))throw new S(`Function '${a}' expects ${_t(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:J(u),maxArgs:u.maxArgs});let p=r.map(x=>this.visit(x));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(v=u==null?void 0:u.returnType)!=null?v:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:et(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(Y(o)&&h(u))return o.repeat(u);if(h(o)&&Y(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return b(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return b(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=b(r);return t.operator.type===i.and?a?b(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:b(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=Y(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;b(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return b(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof N){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return Tt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(st).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:st[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof q||t instanceof F?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof G?this.validateNode(t.expression,n,r,a):t instanceof j?this.validateCallExpression(t,n,r,a):t instanceof P?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof z?this.validateNode(t.argument,n,r,a):t instanceof U?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof D?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof I?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof $?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof W?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof B?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof N?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof H&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?dt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${_t(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:J(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var v,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(v=o.type)!=null?v:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof A)return et(t.value);if(t instanceof $)return"array";if(t instanceof I)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(wt),o=((f=n.outputs)!=null?f:[]).map(wt),u={knownInputs:new Set(a.map(v=>v.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(v=>{var x,Et,xt;if(((x=v.required)==null||x)&&!u.assigned.has(v.name)){r.push(this.validationError("missing_output",t,`Required output '${v.name}' is not assigned`,v.name));return}let d=u.assignedTypes.get(v.name);!d||this.valueSpecTypeMatches(v,d)||r.push(this.validationError("invalid_output_type",t,`Output '${v.name}' expects ${(Et=v.type)!=null?Et:"any"}, got ${d}`,v.name,{expectedType:(xt=v.type)!=null?xt:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof q||t instanceof F?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof G?this.analyzeManifestNode(t.expression,n,r):t instanceof j?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof P?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof z?this.analyzeManifestNode(t.argument,n,r):t instanceof U?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof D?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof I?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof $?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof W?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof B?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof K?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof N?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof H?this.analyzeManifestNode(t.value,n,r):t instanceof E&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof E?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof N&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,v;if(u>=r.length)return;let p=et(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(v=o.type)!=null?v:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Rt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new gt(t),u=new yt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return Tt({...st,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=pt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var it=_,pt=class s extends it{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof R||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof E&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,v;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof R||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!dt(o,n.length))throw new S(`Function '${r}' expects ${_t(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:J(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(v=o==null?void 0:o.returnType)!=null?v:"any",actualType:et(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(Y(a)&&h(o))return a.repeat(o);if(h(a)&&Y(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return b(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return b(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=b(n);return e.operator.type===i.and?r?b(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:b(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=Y(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;b(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof E))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return b(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=it.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};0&&(module.exports={AST,ArrayExpression,AssignmentExpressionAST,BinaryExpressionAST,BlockStatementAST,BreakAST,BreakBranch,CallExpressionAST,ContinueAST,ContinueBranch,ExpressionStatementAST,ForLoopStatement,ForOfStatement,IdentifierAST,IfStatementAST,IndexAccessorAST,LexerDictionary,LiteralAST,LogicalExpressionAST,LoopControl,MEventScope,MEvento,MEventoAsync,MEventoRuntimeError,NodeVisitor,ObjectExpression,ObjectProperty,ReturnAST,ReturnBranch,RootAST,Token,TokenType,TupleExpression,UnaryExpressionAST,WhileLoopStatement});
|
package/dist/esm/index.mjs
CHANGED
|
@@ -5,4 +5,4 @@ function T(s,e){let t=`Invalid token ${s.type}[${s.value}] at ${s.line}, ${s.col
|
|
|
5
5
|
`,e,t);if(this._isWhiteSpace(this._currentChar)){this._skipWhiteSpace();continue}if(this._currentChar==c.shebang){this._advance(),this._currentChar===c.star?(this._advance(),this._skipComment()):this._skipLineComment();continue}if(this._isDigit(this._currentChar))return this._number();if(this._isIdStart(this._currentChar))return this._id();if(this._currentChar===c.equal)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.eqeq,"==",e,t)):new l(i.equal,"=",e,t);if(this._currentChar===c.great)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.greatEq,">=",e,t)):new l(i.great,">",e,t);if(this._currentChar===c.less)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.lessEq,"<=",e,t)):new l(i.less,"<",e,t);if(this._currentChar===c.semiColon)return this._advance(),new l(i.semi,";",e,t);if(this._currentChar===c.lparen)return this._advance(),new l(i.lparen,"(",e,t);if(this._currentChar===c.rparen)return this._advance(),new l(i.rparen,")",e,t);if(this._currentChar===c.comma)return this._advance(),new l(i.comma,",",e,t);if(this._currentChar===c.lbrace)return this._advance(),new l(i.lbrace,"{",e,t);if(this._currentChar===c.rbrace)return this._advance(),new l(i.rbrace,"}",e,t);if(this._currentChar===c.lbracket)return this._advance(),new l(i.lbracket,"[",e,t);if(this._currentChar===c.rbracket)return this._advance(),new l(i.rbracket,"]",e,t);if(this._currentChar===c.plus)return this._advance(),new l(i.plus,"+",e,t);if(this._currentChar===c.minus)return this._advance(),new l(i.minus,"-",e,t);if(this._currentChar===c.slash)return this._advance(),new l(i.div,"/",e,t);if(this._currentChar===c.star)return this._advance(),new l(i.mult,"*",e,t);if(this._currentChar===c.percent)return this._advance(),new l(i.mod,"%",e,t);if(this._currentChar===c.colon)return this._advance(),new l(i.colon,":",e,t);if(this._currentChar===c.dot)return this._advance(),new l(i.dot,".",e,t);if(this._currentChar===c.not)return this._advance(),this._currentChar===c.equal?(this._advance(),new l(i.notEq,"!=",e,t)):new l(i.not,"!",e,t);if(this._currentChar===c.and&&this._pick()===c.and)return this._advance(),this._advance(),new l(i.and,"&&",e,t);if(this._currentChar===c.pipe&&this._pick()===c.pipe)return this._advance(),this._advance(),new l(i.or,"||",e,t);if(this._currentChar===c.questionMark&&this._pick()===c.questionMark)return this._advance(),this._advance(),new l(i.nullity,"??",e,t);if(this._currentChar===c.quote||this._currentChar===c.squote){let r=this._currentChar;this._advance();let a=this._literalString(r);return this._advance(),a}return new l(i.invalid,String.fromCharCode(this._currentChar),e,t)}return new l(i.eof,"",e,t)}};k._defaultLanguage=new J("en",{if:"if",else:"else",true:"true",false:"false",null:"null",while:"while",for:"for",with:"with",up:"up",down:"down",till:"till",in:"in",break:"break",continue:"continue",return:"return"}),k.languages=[k._defaultLanguage,new J("fr",{si:"if",sinon:"else",vrai:"true",faux:"false",nul:"null",tanque:"while",pour:"for",avec:"with",mont:"up",desc:"down",jusqua:"till",dans:"in",couper:"break",continuer:"continue",returner:"return"}),new J("bm",{nii:"if",note:"else",tien:"true",galon:"false",gansan:"null",foo:"while",seginka:"for",niin:"with",kay:"up",kaj:"down",kata:"till",kono:"in",tike:"break",ipan:"continue",segin:"return"})],k.RESERVED={if:l.from(i.IF,"if"),else:l.from(i.ELSE,"else"),true:l.from(i.TRUE,!0),false:l.from(i.FALSE,!1),null:l.from(i.NULL,null),for:l.from(i.FOR_LOOP,"for"),while:l.from(i.WHILE_TILL,"while"),with:l.from(i.with,"with"),up:l.from(i.up,"up"),down:l.from(i.down,"down"),till:l.from(i.TILL,"till"),in:l.from(i.in,"in"),break:l.from(i.BREAK,"break"),continue:l.from(i.CONTINUE,"continue"),return:l.from(i.RETURN,"return")};var ft=k,v=class{constructor(e,t){this.line=e,this.col=t}dump(){return this.toString()}},S=class s extends Error{constructor(e,t,n,r,a,o){var u;super(s.format(e,t,n,r)),this.name="MEventoRuntimeError",this.detail=e,this.line=t,this.col=n,this.nodeType=r,this.cause=a,this.code=(u=o==null?void 0:o.code)!=null?u:"runtime_error",this.diagnosticName=o==null?void 0:o.name,this.argCount=o==null?void 0:o.argCount,this.minArgs=o==null?void 0:o.minArgs,this.maxArgs=o==null?void 0:o.maxArgs,this.argIndex=o==null?void 0:o.argIndex,this.expectedType=o==null?void 0:o.expectedType,this.actualType=o==null?void 0:o.actualType,this.stepCount=o==null?void 0:o.stepCount,this.maxSteps=o==null?void 0:o.maxSteps}static fromNode(e,t){if(t instanceof s)return t;let n=t instanceof Error?t.message:String(t);return new s(n,e.line,e.col,e.constructor.name,t)}static format(e,t,n,r){let a=t!=null&&n!=null?` at ${t}:${n}`:"",o=r?` [${r}]`:"";return`MEvento runtime error${a}${o}: ${e}`}diagnostic(){return{code:this.code,message:this.detail,line:this.line,col:this.col,node:this.nodeType,name:this.diagnosticName,argCount:this.argCount,minArgs:this.minArgs,maxArgs:this.maxArgs,argIndex:this.argIndex,expectedType:this.expectedType,actualType:this.actualType,stepCount:this.stepCount,maxSteps:this.maxSteps}}};function g(s,e){var r;let t={name:s,minArgs:e==null?void 0:e.minArgs,maxArgs:e==null?void 0:e.maxArgs,tags:e!=null&&e.tags?Array.from(e.tags):[],args:e!=null&&e.args?e.args.map(Lt):[],returnType:(r=e==null?void 0:e.returnType)!=null?r:"any"};if((e==null?void 0:e.description)!=null&&(t.description=e.description),(e==null?void 0:e.returnDescription)!=null&&(t.returnDescription=e.returnDescription),(e==null?void 0:e.examples)!=null&&(t.examples=e.examples.map(kt)),(e==null?void 0:e.metadata)!=null&&(t.metadata=ut(e.metadata)),t.minArgs!=null&&t.minArgs<0)throw new Error("minArgs must be greater than or equal to 0");if(t.maxArgs!=null&&t.maxArgs<0)throw new Error("maxArgs must be greater than or equal to 0");let n=Q(t);if(n!=null&&t.maxArgs!=null&&n>t.maxArgs)throw new Error("minArgs must be less than or equal to maxArgs");if(!At.has(t.returnType))throw new Error(`Unsupported return type '${t.returnType}'`);return t}function Lt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(s.description!=null&&(e.description=s.description),s.metadata!=null&&(e.metadata=ut(s.metadata)),!Ot.has(e.type))throw new Error(`Unsupported argument type '${e.type}'`);return e}var At=new Set(["any","null","boolean","number","string","array","object"]),Ot=At;function Nt(s){var t,n;let e={maxSteps:s==null?void 0:s.maxSteps,trace:(t=s==null?void 0:s.trace)!=null?t:!1,compatV1:(n=s==null?void 0:s.compatV1)!=null?n:!1};if(e.maxSteps!=null&&(!Number.isInteger(e.maxSteps)||e.maxSteps<=0))throw new Error("maxSteps must be a positive integer");return e}function xt(s){var t,n;let e={name:s.name,type:(t=s.type)!=null?t:"any",required:(n=s.required)!=null?n:!0};if(!At.has(e.type))throw new Error(`Unsupported value type '${e.type}'`);return e}function ot(s){return Array.isArray(s)?s.map(ot):s!=null&&typeof s=="object"?Object.fromEntries(Object.entries(s).map(([e,t])=>[e,ot(t)])):s}function ut(s){return s==null?void 0:ot(s)}function kt(s){let e={script:s.script};return s.title!=null&&(e.title=s.title),s.result!==void 0&&(e.result=ot(s.result)),s.description!=null&&(e.description=s.description),e}function It(s){var t;let e={name:s.name,minArgs:s.minArgs,maxArgs:s.maxArgs,tags:s.tags?Array.from(s.tags):[],args:s.args?s.args.map(n=>{let r={name:n.name,type:n.type,required:n.required};return n.description!=null&&(r.description=n.description),n.metadata!=null&&(r.metadata=ut(n.metadata)),r}):[],returnType:(t=s.returnType)!=null?t:"any"};return s.description!=null&&(e.description=s.description),s.returnDescription!=null&&(e.returnDescription=s.returnDescription),s.examples!=null&&(e.examples=s.examples.map(kt)),s.metadata!=null&&(e.metadata=ut(s.metadata)),e}function wt(s){return Object.fromEntries(Object.entries(s).map(([e,t])=>[e,It(t)]))}function mt(s,e){let t=Q(s);return!(t!=null&&e<t||s.maxArgs!=null&&e>s.maxArgs)}function Q(s){var n;let e=0;if(s.args){for(let r=s.args.length-1;r>=0;r-=1)if((n=s.args[r].required)==null||n){e=r+1;break}}let t=[s.minArgs,e>0?e:void 0].filter(r=>r!=null);return t.length>0?Math.max(...t):void 0}function vt(s){let e=Q(s);return e==null&&s.maxArgs==null?"any number of":e!=null&&s.maxArgs!=null&&e===s.maxArgs?String(e):e!=null&&s.maxArgs!=null?`${e}..${s.maxArgs}`:e!=null?`at least ${e}`:`at most ${s.maxArgs}`}function Z(s){return s==null?"null":typeof s=="boolean"?"boolean":typeof s=="number"?"number":typeof s=="string"?"string":Array.isArray(s)?"array":"object"}var j=class extends v{constructor(e,t,n){super(1,1),this.body=e,this.name=t,this.source=n}dump(){let e=`Module ${this.name} Start {`;for(let t of this.body)e+=`${t.dump()}
|
|
6
6
|
`;return e+="}",e}},R=class extends v{constructor(e,t){super(t.line,t.col),this.body=e}toString(){return`{
|
|
7
7
|
${this.body.map(e=>e.toString()).join(`
|
|
8
|
-
`)}}`}},x=class extends v{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},E=class extends v{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends v{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},X=class extends v{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},P=class extends v{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},z=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},U=class extends v{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},D=class extends v{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},W=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends v{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},$=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},F=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends v{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},B=class extends v{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},K=class extends v{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},H=class extends v{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},I=class extends v{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},et=class extends v{constructor(e,t){super(e,t)}},Y=class extends v{constructor(e,t,n){super(t,n),this.value=e}},nt=class extends v{constructor(e,t){super(e,t)}};function $t(s){return s instanceof j?"RootAST":s instanceof R?"BlockStatementAST":s instanceof x?"IdentifierAST":s instanceof E?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof X?"ExpressionStatementAST":s instanceof P?"CallExpressionAST":s instanceof z?"BinaryExpressionAST":s instanceof U?"UnaryExpressionAST":s instanceof D?"IfStatementAST":s instanceof W?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof $?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof F?"ArrayExpression":s instanceof B?"WhileLoopStatement":s instanceof K?"ForLoopStatement":s instanceof H?"ForOfStatement":s instanceof I?"TupleExpression":s instanceof et?"BreakAST":s instanceof Y?"ReturnAST":s instanceof nt?"ContinueAST":s.constructor.name}var gt=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},tt=class tt{constructor(e){this._loopTrack=new gt;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new x(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new Y(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new U(e,this._term());case i.numberConst:return this._eat(i.numberConst),new E(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new E(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new E(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new E(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new et((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new nt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new W(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof x||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new E(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new E(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new $(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new F(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new E(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=tt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=tt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new z(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof x||T(this.currentToken),new P(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){var n;if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new R([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),((n=this.currentToken)==null?void 0:n.type)===i.rbrace&&this._eat(i.rbrace),new R(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new D(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new B(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new I(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new E(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new H(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new j(n,t,e)}parse(){return this._root()}};tt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var dt=tt,V=class{},C=class extends V{},M=class extends V{},y=class{constructor(e){this.value=e}},_t=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},St=class extends _t{constructor(){super(),this.registerVisitor(j,this.visitRootAST),this.registerVisitor(R,this.visitBlockStatementAST),this.registerVisitor(x,this.visitIdentifierAST),this.registerVisitor(E,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(X,this.visitExpressionStatementAST),this.registerVisitor(P,this.visitCallExpressionAST),this.registerVisitor(z,this.visitBinaryExpressionAST),this.registerVisitor(U,this.visitUnaryExpressionAST),this.registerVisitor(D,this.visitIfStatementAST),this.registerVisitor(W,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor($,this.visitObjectExpression),this.registerVisitor(F,this.visitArrayExpression),this.registerVisitor(B,this.visitWhileLoopStatement),this.registerVisitor(K,this.visitForLoopStatement),this.registerVisitor(H,this.visitForOfStatement),this.registerVisitor(et,this.visitBreakAST),this.registerVisitor(nt,this.visitContinueAST),this.registerVisitor(Y,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},ct=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},rt={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function it(s){return typeof s=="object"&&s!=null&&s.ok===!0}function at(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function N(s){return typeof s=="number"?s:void 0}function G(s){return typeof s=="string"?s:void 0}function Ft(s){var t,n;let e=at(s);return new S((t=G(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",N(e==null?void 0:e.line),N(e==null?void 0:e.col),G(e==null?void 0:e.node),void 0,{code:(n=G(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:G(e==null?void 0:e.name),argCount:N(e==null?void 0:e.argCount),minArgs:N(e==null?void 0:e.minArgs),maxArgs:N(e==null?void 0:e.maxArgs),argIndex:N(e==null?void 0:e.argIndex),expectedType:G(e==null?void 0:e.expectedType),actualType:G(e==null?void 0:e.actualType),stepCount:N(e==null?void 0:e.stepCount),maxSteps:N(e==null?void 0:e.maxSteps)})}function ht(s,e,t,n){let r=Z(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function st(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ht(s,t,"array",n)}function pt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ht(s,t,"object",n)}function Tt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ht(s,t,"number",n)}function Rt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Vt={_ok_:s=>it(s[0]),_err_:s=>!it(s[0]),_value_:s=>{var e,t;return it(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=at(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(it(s[0]))return(e=s[0].value)!=null?e:null;throw Ft(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ht("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=st("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=st("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=st("_insert_",s,0),t=Tt("_insert_",s,1);if(t<0||t>e.length)throw Rt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=st("_remove_at_",s,0),t=Tt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(pt("_has_",s,0),s[1]),_keys_:s=>Object.keys(pt("_keys_",s,0)),_values_:s=>Object.values(pt("_values_",s,0))},_=class _ extends St{constructor(t){super();this.rootScope=new ct("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=Nt(t),this._functionsRegistry={...Vt,..._._globalFunctionsRegistry},this._functionSpecs={...rt,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:$t(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new ct(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof V||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof x&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var m,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let b=this.visit(r[0]);return b instanceof V||b instanceof y?b:this.successResult(b)}catch(b){if(b instanceof S)return this.errorResult(b);throw b}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!mt(u,r.length))throw new S(`Function '${a}' expects ${vt(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:Q(u),maxArgs:u.maxArgs});let p=r.map(b=>this.visit(b));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(m=u==null?void 0:u.returnType)!=null?m:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:Z(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(q(o)&&h(u))return o.repeat(u);if(h(o)&&q(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return A(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return A(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=A(r);return t.operator.type===i.and?a?A(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:A(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=q(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;A(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return A(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof I){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return wt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(rt).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:rt[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof j||t instanceof R?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof X?this.validateNode(t.expression,n,r,a):t instanceof P?this.validateCallExpression(t,n,r,a):t instanceof z?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof U?this.validateNode(t.argument,n,r,a):t instanceof D?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof W?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof $?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof F?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof B?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof H?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof I?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof Y&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?mt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${vt(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:Q(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var m,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(m=o.type)!=null?m:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof E)return Z(t.value);if(t instanceof F)return"array";if(t instanceof $)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(xt),o=((f=n.outputs)!=null?f:[]).map(xt),u={knownInputs:new Set(a.map(m=>m.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(m=>{var b,bt,Et;if(((b=m.required)==null||b)&&!u.assigned.has(m.name)){r.push(this.validationError("missing_output",t,`Required output '${m.name}' is not assigned`,m.name));return}let d=u.assignedTypes.get(m.name);!d||this.valueSpecTypeMatches(m,d)||r.push(this.validationError("invalid_output_type",t,`Output '${m.name}' expects ${(bt=m.type)!=null?bt:"any"}, got ${d}`,m.name,{expectedType:(Et=m.type)!=null?Et:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof j||t instanceof R?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof X?this.analyzeManifestNode(t.expression,n,r):t instanceof P?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof z?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof U?this.analyzeManifestNode(t.argument,n,r):t instanceof D?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof W?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof $?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof F?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof B?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof K?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof H?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof I?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof Y?this.analyzeManifestNode(t.value,n,r):t instanceof x&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof x?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof I&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,m;if(u>=r.length)return;let p=Z(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(m=o.type)!=null?m:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Mt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new ft(t),u=new dt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return wt({...rt,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=yt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var lt=_,yt=class s extends lt{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof V||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof x&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,m;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof V||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!mt(o,n.length))throw new S(`Function '${r}' expects ${vt(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:Q(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(m=o==null?void 0:o.returnType)!=null?m:"any",actualType:Z(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(q(a)&&h(o))return a.repeat(o);if(h(a)&&q(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return A(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return A(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=A(n);return e.operator.type===i.and?r?A(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:A(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=q(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;A(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return A(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=lt.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};export{v as AST,F as ArrayExpression,L as AssignmentExpressionAST,z as BinaryExpressionAST,R as BlockStatementAST,et as BreakAST,C as BreakBranch,P as CallExpressionAST,nt as ContinueAST,M as ContinueBranch,X as ExpressionStatementAST,K as ForLoopStatement,H as ForOfStatement,x as IdentifierAST,D as IfStatementAST,w as IndexAccessorAST,J as LexerDictionary,E as LiteralAST,W as LogicalExpressionAST,V as LoopControl,ct as MEventScope,lt as MEvento,yt as MEventoAsync,S as MEventoRuntimeError,St as NodeVisitor,$ as ObjectExpression,O as ObjectProperty,Y as ReturnAST,y as ReturnBranch,j as RootAST,l as Token,i as TokenType,I as TupleExpression,U as UnaryExpressionAST,B as WhileLoopStatement};
|
|
8
|
+
`)}}`}},x=class extends v{constructor(e){super(e.line,e.col),this.value=e.value.toString()}toString(){return this.value}},E=class extends v{constructor(e,t){super(e.line,e.col),this.value=e.value,this.raw=t}toString(){return this.value.toString()}},L=class extends v{constructor(e,t){super(e.line,e.col),this.identifier=e,this.init=t}toString(){return`${this.identifier} = ${this.init}`}},X=class extends v{constructor(e){super(e.line,e.col),this.expression=e}toString(){return this.expression.toString()}},P=class extends v{constructor(e,t){super(e.line,e.col),this.callee=e,this.arguments=t}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},z=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operation=t,this.right=n}toString(){return`${this.left} ${this.operation} ${this.right}`}},U=class extends v{constructor(e,t){super(e.line,e.col),this.operation=e,this.argument=t}toString(){return`${this.operation} ${this.argument}`}},D=class extends v{constructor(e,t,n){super(e.line,e.col),this.test=e,this.consequent=t,this.alternate=n}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},W=class extends v{constructor(e,t,n){super(e.line,e.col),this.left=e,this.operator=t,this.right=n}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},w=class extends v{constructor(t,n,r=!1){super(t.line,t.col);this.computed=!1;this.owner=t,this.key=n,this.computed=r}toString(){return`${this.owner}[${this.key}]`}},$=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.properties=e}toString(){return"{...}"}},F=class extends v{constructor(e,t,n){super(t==null?void 0:t.line,t==null?void 0:t.col),this.elements=e}toString(){return"[...]"}},O=class extends v{constructor(e,t){super(e.line,e.col),this.value=t,this.key=e}},B=class extends v{constructor(t,n,r,a,o=!1){super(r==null?void 0:r.line,r==null?void 0:r.col);this.retain=!1;this.test=t,this.body=n,this.retain=o}},K=class extends v{constructor(t,n,r,a,o,u,p,f=!1){super(u==null?void 0:u.line,u==null?void 0:u.col);this.init=t;this.test=n;this.update=r;this.direction=a;this.body=o;this.retain=f}},H=class extends v{constructor(t,n,r,a,o,u=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.identifier=t;this.collection=n;this.body=r;this.retain=u}},I=class extends v{constructor(t,n){super(t.line,t.col);this.first=t;this.second=n}},et=class extends v{constructor(e,t){super(e,t)}},Y=class extends v{constructor(e,t,n){super(t,n),this.value=e}},nt=class extends v{constructor(e,t){super(e,t)}};function $t(s){return s instanceof j?"RootAST":s instanceof R?"BlockStatementAST":s instanceof x?"IdentifierAST":s instanceof E?"LiteralAST":s instanceof L?"AssignmentExpressionAST":s instanceof X?"ExpressionStatementAST":s instanceof P?"CallExpressionAST":s instanceof z?"BinaryExpressionAST":s instanceof U?"UnaryExpressionAST":s instanceof D?"IfStatementAST":s instanceof W?"LogicalExpressionAST":s instanceof w?"IndexAccessorAST":s instanceof $?"ObjectExpression":s instanceof O?"ObjectProperty":s instanceof F?"ArrayExpression":s instanceof B?"WhileLoopStatement":s instanceof K?"ForLoopStatement":s instanceof H?"ForOfStatement":s instanceof I?"TupleExpression":s instanceof et?"BreakAST":s instanceof Y?"ReturnAST":s instanceof nt?"ContinueAST":s.constructor.name}var gt=class{constructor(e=1/0){this.capacity=e;this.storage=[]}push(e){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(e)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},tt=class tt{constructor(e){this._loopTrack=new gt;this.currentToken=e.nextToken(),this.lexer=e}_eat(e){var t;((t=this.currentToken)==null?void 0:t.type)===e?this.currentToken=this.lexer.nextToken():T(this.currentToken,e)}_eatEOL(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol;)this._eat(i.eol)}_eatSemiOrEOL(){var e,t;for(;((e=this.currentToken)==null?void 0:e.type)===i.eol||((t=this.currentToken)==null?void 0:t.type)===i.semi;)this._eat(this.currentToken.type)}_eatSemi(){var e;for(;((e=this.currentToken)==null?void 0:e.type)===i.semi;)this._eat(i.semi)}_variable(){let e=new x(this.currentToken);return this._eat(i.id),e}_return(){let e=this.currentToken,t;return!this._expect(i.eol)&&!this._expect(i.semi)&&(t=this._expression()),new Y(t,e==null?void 0:e.line,e==null?void 0:e.col)}_factor(){let e=this.currentToken;switch(e.type){case i.plus:case i.minus:case i.not:return this._eat(this.currentToken.type),new U(e,this._term());case i.numberConst:return this._eat(i.numberConst),new E(e,e.value.toString());case i.stringConst:return this._eat(i.stringConst),new E(e,e.value.toString());case i.lparen:this._eat(i.lparen);let t=this._expression();return this._eat(i.rparen),t;case i.TRUE:case i.FALSE:return this._eat(this.currentToken.type),new E(e,e.value.toString());case i.NULL:return this._eat(i.NULL),new E(e,"null");case i.lbracket:return this._arrayExpression();case i.lbrace:return this._objectExpression();case i.IF:return this._ifStatement();case i.WHILE_TILL:return this._whileLoop(!0);case i.FOR_LOOP:return this._forLoop(!0);case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.BREAK),new et((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_continueExpression(){var e,t;return this._loopTrack.isEmpty&&T(this.currentToken),this._eat(i.CONTINUE),new nt((e=this.currentToken)==null?void 0:e.line,(t=this.currentToken)==null?void 0:t.col)}_term(){let e=this._factor();return e=this._tryParsingFunctionCall(e),e=this._tryParsingMemberExpression(e),e}_expression(){let e=this._term();for(e=this._tryBinaryExpression(0,e);[i.and,i.or,i.nullity].includes(this.currentToken.type);){let t=this.currentToken;this._eat(t.type),e=new W(e,t,this._expression())}if(this._expect(i.equal))if(e instanceof x||e instanceof w){let t=this.currentToken;this._eat(i.equal),e=new L(e,this._expression())}else throw new Error("Unexpected token");return e}_objectProperty(){var r;let e;switch((r=this.currentToken)==null?void 0:r.type){case i.stringConst:{e=new E(this.currentToken,this.currentToken.value),this._eat(i.stringConst);break}case i.lbracket:{this._eat(i.lbracket);var t=this._expression();this._eat(i.rbracket),e=t;break}case i.id:{let a=this._variable();e=new E(new l(i.id,a.value,a.line,a.col),a.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(i.colon);var n=this._expression();return new O(e,n)}_property(){return this._objectProperty()}_objectProperties(){var t,n;let e=[];for(((t=this.currentToken)==null?void 0:t.type)!=i.rbrace&&(this._eatEOL(),e.push(this._property()),this._eatEOL());((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbrace));)e.push(this._property()),this._eatEOL();return e}_objectExpression(e){var t=e!=null?e:this.currentToken;e||this._eat(i.lbrace);var n=this._objectProperties();return this._eat(i.rbrace),new $(n,t,this.currentToken)}_arrayExpression(){this._eat(i.lbracket);let e=this._expect(i.rbracket)?[]:this._expressionsList();this._eat(i.rbracket);var t=e.length!==0?e[0]:void 0,n=e.length!==0?e[e.length-1]:void 0;return new F(e,t,n)}_tryParsingMemberExpression(e){let t=e;for(;this.currentToken.type===i.lbracket||this.currentToken.type===i.dot;)if(this.currentToken.type===i.lbracket){this._eat(i.lbracket);let n=this._expression();t=new w(t,n,!0),this._eat(i.rbracket)}else{this._eat(i.dot);let n=this.currentToken;n.type!==i.id&&T(n);let r=new E(new l(i.stringConst,n.value,n.line,n.col),n.value);this._eat(i.id),t=new w(t,r)}return t}_tryBinaryExpression(e,t){let n=t;for(;;){let r=tt._binopPrecdences[this.currentToken.type]||-1;if(r<e)return n;let a=this.currentToken;this._eat(a.type);let o=this._term(),u=tt._binopPrecdences[this.currentToken.type]||-1;if(r<u){let p=this._tryBinaryExpression(r+1,o);if(p===n)return p;o=p}n=new z(n,a,o)}}_expressionsList(){var n;this._eatEOL();let e=this._expression();this._eatEOL();let t=[e];for(;((n=this.currentToken)==null?void 0:n.type)===i.comma&&(this._eat(i.comma),this._eatEOL(),!this._expect(i.rbracket));)e=this._expression(),t.push(e),this._eatEOL();return t}_callExpression(e){this._eat(i.lparen);let t=[];return this._expect(i.rparen)||(t=this._expressionsList()),this._eat(i.rparen),e instanceof x||T(this.currentToken),new P(e,t)}_tryParsingFunctionCall(e){let t=e;for(;this.currentToken.type===i.lparen;)t=this._callExpression(t);return t}_statementExpression(){let e=this._expression();return[i.semi,i.eol,i.eof,i.rbrace].includes(this.currentToken.type)||T(this.currentToken),e}_blockStatement(e=!1){if(e||this._eat(i.lbrace),this._eatEOL(),this._expect(i.rbrace))return this._eat(i.rbrace),new R([],this.currentToken);let t=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===i.rbrace||this.currentToken.type===i.eof||(t.push(this._statement()),this._expect(i.rbrace)));)this.currentToken.type!==i.eol&&this.currentToken.type!==i.semi&&this.currentToken.type!==i.eof&&T(this.currentToken);return this._eat(i.rbrace),new R(t,this.currentToken)}_ifStatement(){this._eat(i.IF);let e=this.currentToken.type===i.lparen;e&&this._eat(i.lparen);let t=this._expression();e&&this._eat(i.rparen);let n;this.currentToken.type===i.lbrace?n=this._blockStatement():n=this._expression();let r;if(this.currentToken.type===i.ELSE)switch(this._eat(i.ELSE),this.currentToken.type){case i.IF:r=this._ifStatement();break;case i.lbrace:r=this._blockStatement();break;default:r=this._expression()}return new D(t,n,r)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(e=!1){let t=this.currentToken;this._eat(i.WHILE_TILL),this._pushLoop();let n=this._expression(),r=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();return this._popLoop(),new B(n,r,t,this.currentToken,e)}_forOfIdentifier(){switch(this.currentToken.type){case i.lparen:{this._eat(i.lparen);let e=this._variable();this._eat(i.comma);let t=this._variable();return this._eat(i.rparen),new I(e,t)}default:return this._variable()}}_forLoop(e=!1){let t=this.currentToken;this._eat(i.FOR_LOOP),this._pushLoop();let n=[i.lparen].includes(this.currentToken.type),r;if(n)r=this._forOfIdentifier();else{let a=this._expression();a instanceof L||(n=!0),r=a}if(!n&&r instanceof L){this._eat(i.TILL);let a=this._expression(),o;if(this.currentToken.type===i.up||this.currentToken.type===i.down){let f=this.currentToken;this._eat(f.type),o=f}else o=new l(i.up,"up");let u;this._expect(i.with)?(this._eat(i.with),u=this._expression()):u=new E(new l(i.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new K(r,a,u,o,p,t,this.currentToken,e),this._popLoop()}else if(n){this._eat(i.in);let a=this._expression(),o=this.currentToken.type===i.lbrace?this._blockStatement():this._expression();r=new H(r,a,o,t,this.currentToken,e),this._popLoop()}else T(this.currentToken);return r}_statement(){switch(this.currentToken.type){case i.BREAK:return this._breakExpression();case i.CONTINUE:return this._continueExpression();case i.RETURN:return this._eat(i.RETURN),this._return();case i.semi:return this._eatSemi(),this._statement();case i.eol:return this._eatEOL(),this._statement();case i.WHILE_TILL:return this._whileLoop();case i.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(e){var t;return((t=this.currentToken)==null?void 0:t.type)===e}_definition(){if(this._eatSemiOrEOL(),this._expect(i.eof))return[];let e=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===i.eof){this._eat(i.eof);break}this.currentToken.type===i.lbrace?e.push(this._blockStatement()):e.push(this._statement())}return e}_root(){let e=this.lexer.source,t="<module>",n=this._definition();return new j(n,t,e)}parse(){return this._root()}};tt._binopPrecdences={[i.eqeq]:10,[i.notEq]:10,[i.great]:10,[i.greatEq]:10,[i.less]:10,[i.lessEq]:10,[i.plus]:20,[i.minus]:20,[i.mult]:40,[i.div]:40,[i.mod]:40};var dt=tt,V=class{},C=class extends V{},M=class extends V{},y=class{constructor(e){this.value=e}},_t=class{constructor(){this._nodesVisitors={}}registerVisitor(e,t){let n=`visit${e.name}`;this._nodesVisitors[n]=t}},St=class extends _t{constructor(){super(),this.registerVisitor(j,this.visitRootAST),this.registerVisitor(R,this.visitBlockStatementAST),this.registerVisitor(x,this.visitIdentifierAST),this.registerVisitor(E,this.visitLiteralAST),this.registerVisitor(L,this.visitAssignmentExpressionAST),this.registerVisitor(X,this.visitExpressionStatementAST),this.registerVisitor(P,this.visitCallExpressionAST),this.registerVisitor(z,this.visitBinaryExpressionAST),this.registerVisitor(U,this.visitUnaryExpressionAST),this.registerVisitor(D,this.visitIfStatementAST),this.registerVisitor(W,this.visitLogicalExpressionAST),this.registerVisitor(w,this.visitIndexAccessorAST),this.registerVisitor(O,this.visitObjectProperty),this.registerVisitor($,this.visitObjectExpression),this.registerVisitor(F,this.visitArrayExpression),this.registerVisitor(B,this.visitWhileLoopStatement),this.registerVisitor(K,this.visitForLoopStatement),this.registerVisitor(H,this.visitForOfStatement),this.registerVisitor(et,this.visitBreakAST),this.registerVisitor(nt,this.visitContinueAST),this.registerVisitor(Y,this.visitReturnAST)}visit(e){this.beforeVisit(e);let t=`visit${e.constructor.name}`,n=this._nodesVisitors[t];if(!n)throw new S(`No ${t} declared`,e.line,e.col,e.constructor.name);try{let r=n.call(this,e);return r&&typeof r.then=="function"?r.catch(a=>{throw S.fromNode(e,a)}):r!=null?r:null}catch(r){throw S.fromNode(e,r)}}beforeVisit(e){}assignProperty(e,t,n){(Array.isArray(e)||typeof e=="object")&&(e[t]=n)}},ct=class{constructor(e,t,n){this.memory={};this.name=e,this.memory=t,this.parent=n}resolve(e){var t,n;return Object.keys(this.memory).includes(e)?this.memory[e]:(n=(t=this.parent)==null?void 0:t.resolve(e))!=null?n:null}change(e,t,n=!0){return Object.keys(this.memory).includes(e)?(this.memory[e]=t,!0):this.parent&&this.parent.change(e,t,!1)?!0:n?(this.memory[e]=t,!0):!1}},rt={_ok_:g("_ok_",{name:"_ok_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_err_:g("_err_",{name:"_err_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"boolean"}),_value_:g("_value_",{name:"_value_",minArgs:1,maxArgs:2,args:[{name:"result"},{name:"fallback",required:!1}],returnType:"any"}),_error_:g("_error_",{name:"_error_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"object"}),_code_:g("_code_",{name:"_code_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_message_:g("_message_",{name:"_message_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"string"}),_unwrap_:g("_unwrap_",{name:"_unwrap_",minArgs:1,maxArgs:1,args:[{name:"result"}],returnType:"any"}),_len_:g("_len_",{name:"_len_",minArgs:1,maxArgs:1,args:[{name:"target"}],returnType:"number"}),_push_:g("_push_",{name:"_push_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"value"}],returnType:"array"}),_pop_:g("_pop_",{name:"_pop_",minArgs:1,maxArgs:1,args:[{name:"array",type:"array"}],returnType:"any"}),_insert_:g("_insert_",{name:"_insert_",minArgs:3,maxArgs:3,args:[{name:"array",type:"array"},{name:"index",type:"number"},{name:"value"}],returnType:"array"}),_remove_at_:g("_remove_at_",{name:"_remove_at_",minArgs:2,maxArgs:2,args:[{name:"array",type:"array"},{name:"index",type:"number"}],returnType:"any"}),_has_:g("_has_",{name:"_has_",minArgs:2,maxArgs:2,args:[{name:"object",type:"object"},{name:"key"}],returnType:"boolean"}),_keys_:g("_keys_",{name:"_keys_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"}),_values_:g("_values_",{name:"_values_",minArgs:1,maxArgs:1,args:[{name:"object",type:"object"}],returnType:"array"})};function it(s){return typeof s=="object"&&s!=null&&s.ok===!0}function at(s){if(typeof s!="object"||s==null)return;let e=s;if(!(e.ok!==!1||typeof e.error!="object"||e.error==null))return e.error}function N(s){return typeof s=="number"?s:void 0}function G(s){return typeof s=="string"?s:void 0}function Ft(s){var t,n;let e=at(s);return new S((t=G(e==null?void 0:e.message))!=null?t:"Cannot unwrap failed _try_ result",N(e==null?void 0:e.line),N(e==null?void 0:e.col),G(e==null?void 0:e.node),void 0,{code:(n=G(e==null?void 0:e.code))!=null?n:"invalid_try_result",name:G(e==null?void 0:e.name),argCount:N(e==null?void 0:e.argCount),minArgs:N(e==null?void 0:e.minArgs),maxArgs:N(e==null?void 0:e.maxArgs),argIndex:N(e==null?void 0:e.argIndex),expectedType:G(e==null?void 0:e.expectedType),actualType:G(e==null?void 0:e.actualType),stepCount:N(e==null?void 0:e.stepCount),maxSteps:N(e==null?void 0:e.maxSteps)})}function ht(s,e,t,n){let r=Z(n);return new S(`Function '${s}' argument ${e} expects ${t}, got ${r}`,void 0,void 0,void 0,void 0,{code:"invalid_argument_type",name:s,argIndex:e,expectedType:t,actualType:r})}function st(s,e,t){let n=e[t];if(Array.isArray(n))return n;throw ht(s,t,"array",n)}function pt(s,e,t){let n=e[t];if(typeof n=="object"&&n!=null&&!Array.isArray(n))return n;throw ht(s,t,"object",n)}function Tt(s,e,t){let n=e[t];if(typeof n=="number")return Math.trunc(n);throw ht(s,t,"number",n)}function Rt(s,e,t){return new S(`Function '${s}' index ${e} is out of range for array of length ${t}`,void 0,void 0,void 0,void 0,{code:"index_out_of_range",name:s})}var Vt={_ok_:s=>it(s[0]),_err_:s=>!it(s[0]),_value_:s=>{var e,t;return it(s[0])?(e=s[0].value)!=null?e:null:(t=s[1])!=null?t:null},_error_:s=>{var e;return(e=at(s[0]))!=null?e:null},_code_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.code)!=null?t:null},_message_:s=>{var e,t;return(t=(e=at(s[0]))==null?void 0:e.message)!=null?t:null},_unwrap_:s=>{var e;if(it(s[0]))return(e=s[0].value)!=null?e:null;throw Ft(s[0])},_len_:s=>{let e=s[0];if(Array.isArray(e)||typeof e=="string")return e.length;if(typeof e=="object"&&e!=null)return Object.keys(e).length;throw ht("_len_",0,"array|object|string",e)},_push_:s=>{var t;let e=st("_push_",s,0);return e.push((t=s[1])!=null?t:null),e},_pop_:s=>{var t;let e=st("_pop_",s,0);return e.length===0?null:(t=e.pop())!=null?t:null},_insert_:s=>{var n;let e=st("_insert_",s,0),t=Tt("_insert_",s,1);if(t<0||t>e.length)throw Rt("_insert_",t,e.length);return e.splice(t,0,(n=s[2])!=null?n:null),e},_remove_at_:s=>{var n;let e=st("_remove_at_",s,0),t=Tt("_remove_at_",s,1);return t<0||t>=e.length?null:(n=e.splice(t,1)[0])!=null?n:null},_has_:s=>Object.prototype.hasOwnProperty.call(pt("_has_",s,0),s[1]),_keys_:s=>Object.keys(pt("_keys_",s,0)),_values_:s=>Object.values(pt("_values_",s,0))},_=class _ extends St{constructor(t){super();this.rootScope=new ct("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionSpecs={};this._executionStepCount=0;this._traceEvents=[];this._options=Nt(t),this._functionsRegistry={...Vt,..._._globalFunctionsRegistry},this._functionSpecs={...rt,..._._globalFunctionSpecs}}get options(){return{...this._options}}get executionStepCount(){return this._executionStepCount}trace(){return this._traceEvents.map(t=>({...t,detail:{...t.detail}}))}resetExecutionBudget(){this._executionStepCount=0}beforeVisit(t){this._executionStepCount+=1,this.recordTrace("visit",t);let n=this._options.maxSteps;if(n!=null&&this._executionStepCount>n)throw new S(`Execution budget exceeded after ${this._executionStepCount} step(s)`,t.line,t.col,t.constructor.name,void 0,{code:"execution_budget_exceeded",stepCount:this._executionStepCount,maxSteps:n})}clearTrace(){this._traceEvents=[]}recordTrace(t,n,r,a={}){this._options.trace&&this._traceEvents.push({kind:t,line:n.line,col:n.col,node:$t(n),name:r,stepCount:this._executionStepCount,detail:a})}resolve(t){var n,r;return(r=(n=this.currentScope)==null?void 0:n.resolve(t))!=null?r:null}changeVariable(t,n){var r;return(r=this.currentScope)!=null&&r.change(t,n)?n:null}pushScope(t){let n=new ct(t,{},this.currentScope);this.currentScope=n}popScope(){var t;this.currentScope=(t=this.currentScope)==null?void 0:t.parent}log(t){this.debug&&console.log(t)}successResult(t){return{ok:!0,value:t,error:null}}errorResult(t){return{ok:!1,value:null,error:t.diagnostic()}}visitRootAST(t){var a;let n=t.body,r;for(let o of n)if(r=this.visit(o),r instanceof y)return(a=r.value)!=null?a:null;return r!=null?r:null}visitBlockStatementAST(t){let n=t.body,r;this.pushScope("Block");for(let a of n)if(r=this.visit(a),r instanceof V||r instanceof y)break;return this.popScope(),r!=null?r:null}visitIdentifierAST(t){var r;let n=t.value;return(r=this==null?void 0:this.resolve(n))!=null?r:null}visitLiteralAST(t){return t.value}visitAssignmentExpressionAST(t){let n=t.identifier,r=t.init,a=null;if(n instanceof w){var o=this.visit(n.owner);a=this.visit(t.init);var u=this.visit(n.key);this.assignProperty(o,u,a)}else n instanceof x&&(a=this.visit(r),this.changeVariable(n.value,a));return a}visitExpressionStatementAST(t){let n=t.expression;return this.visit(n)}visitCallExpressionAST(t){var m,d;let n=t.callee,r=t.arguments,a=n.value;if(a==="_try_"){if(r.length!==1)throw new S("_try_ expects exactly one expression",t.line,t.col,t.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:r.length,minArgs:1,maxArgs:1});try{let b=this.visit(r[0]);return b instanceof V||b instanceof y?b:this.successResult(b)}catch(b){if(b instanceof S)return this.errorResult(b);throw b}}let o=this.resolveFunction(a);if(!o){if(this._options.compatV1)return null;throw new S(`Unknown function '${a}'`,t.line,t.col,t.constructor.name,void 0,{code:"unknown_function",name:a})}let u=this.resolveFunctionSpec(a);if(u&&!mt(u,r.length))throw new S(`Function '${a}' expects ${vt(u)} argument(s), got ${r.length}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_function_arity",name:a,argCount:r.length,minArgs:Q(u),maxArgs:u.maxArgs});let p=r.map(b=>this.visit(b));u&&this.validateRuntimeArgumentTypes(t,u,p),this.recordTrace("call",t,a,{argCount:p.length,returnType:(m=u==null?void 0:u.returnType)!=null?m:"any"});let f=o(p,this);return this.recordTrace("call_result",t,a,{returnType:(d=u==null?void 0:u.returnType)!=null?d:"any",actualType:Z(f)}),f}visitBinaryExpressionAST(t){let n=t.left,r=t.right,a=t.operation,o=this.visit(n),u=this.visit(r);switch(a.type){case i.plus:return h(o)&&h(u)?o+u:`${o}${u}`;case i.minus:if(h(o)&&h(u))return o-u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.mult:if(h(o)&&h(u))return o*u;if(q(o)&&h(u))return o.repeat(u);if(h(o)&&q(u))return u.repeat(o);throw new Error(`Operation ${a.value} not allowed no num value`);case i.div:if(h(o)&&h(u)){if(u===0)throw new Error("Invalid division by 0");return o/u}throw new Error(`Operation ${a.value} not allowed no num value`);case i.mod:if(h(o)&&h(u))return o%u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.great:if(h(o)&&h(u))return o>u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.greatEq:if(h(o)&&h(u))return o>=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.less:if(h(o)&&h(u))return o<u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.lessEq:if(h(o)&&h(u))return o<=u;throw new Error(`Operation ${a.value} not allowed no num value`);case i.eqeq:return o===u;case i.notEq:return o!==u;default:throw new Error(`Operation ${a.value} not allowed no num value`)}}visitUnaryExpressionAST(t){let n=t.argument,r=t.operation,a=this.visit(n);if(r.type===i.not)return A(a)===!1;if(!h(a))throw new Error(`Operation ${r.value} not allowed no num value`);if(r.type===i.plus)return a;if(r.type===i.minus)return-a;throw new Error(`Operation ${r.value} not allowed no num value`)}visitIfStatementAST(t){let n=t.test,r=this.visit(n);return A(r)?this.visit(t.consequent):t.alternate?this.visit(t.alternate):null}visitLogicalExpressionAST(t){let n=t.left,r=this.visit(n);if(t.operator.type===i.nullity)return r!=null?r:this.visit(t.right);let a=A(r);return t.operator.type===i.and?a?A(this.visit(t.right)):!1:t.operator.type===i.or?a?!0:A(this.visit(t.right)):null}visitIndexAccessorAST(t){var a,o;let n=t.owner,r=this.visit(n);if(r==null)return null;if(Array.isArray(r)){let u=this.visit(t.key);return h(u)&&Number.isInteger(u)&&r.length>u&&u>=0&&(a=r[u])!=null?a:null}else if(typeof r=="object"){let u=this.visit(t.key);return(o=r[u])!=null?o:null}return null}visitObjectProperty(t){}visitObjectExpression(t){let n={},r=t;for(let a of r.properties)if(a instanceof O){let o=this.visit(a.key);o=q(o)?o:o.toString(),n[o]=this.visit(a.value)}return n}visitArrayExpression(t){let n=t;return this.resolveArguments(n.elements)}visitBreakAST(t){return new C}visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let n=t.retain?[]:void 0;for(;A(this.visit(t.test));){let r=this.visit(t.body);if(r instanceof C)break;if(!(r instanceof M)){if(r instanceof y)return this.popScope(),r;n==null||n.push(r)}}return n!=null?n:null}visitForLoopStatement(t){let n=t.retain?[]:void 0,r=t.init.identifier;if(!(r instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let a=this.visit(t.init.init);this.changeVariable(r.value,a);let o=()=>{let p=this.visit(t.test);if(h(p)){let f=this.resolve(r.value);return t.direction.type===i.up?p>=f:p<=f}return A(p)},u=()=>{let p=this.visit(t.update);if(h(p)){let f=this.resolve(r.value);if(!h(f))throw Error("Cant update value");this.changeVariable(r.value,t.direction.type===i.up?f+p:f-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(t.body);if(p instanceof C)break;if(p instanceof M){u();continue}if(p instanceof y)return this.popScope(),p;n==null||n.push(p),u()}return this.popScope(),n!=null?n:null}visitForOfStatement(t){let n=this.visit(t.collection);if(!Array.isArray(n))throw Error("Can iterate non array object");let r=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let a of n){this._declareForIdentifier(t.identifier,a);let o=this.visit(t.body);if(o instanceof C)break;if(!(o instanceof M)){if(o instanceof y)return this.popScope(),o;r==null||r.push(o)}}return this.popScope(),r!=null?r:null}visitContinueAST(t){return new M}visitReturnAST(t){return new y(t.value!=null?this.visit(t.value):null)}_declareForIdentifier(t,n){if(t instanceof I){if(!Array.isArray(n))throw Error("Unable to make a tuple from non Array element");this.changeVariable(t.first.value,n[0]),this.changeVariable(t.second.value,n[1])}this.changeVariable(t.value,n)}resolveArguments(t){return t.map(n=>this.visit(n))}setFunctionResolver(t){this._functionResolver=t}resolveFunction(t){var n,r;return(r=this._functionsRegistry[t])!=null?r:(n=this._functionResolver)==null?void 0:n.call(this,t)}resolveFunctionSpec(t){return this._functionSpecs[t]}capabilities(){return wt(this._functionSpecs)}registerFunction(t,n,r){this._functionsRegistry[t]=n,this._functionSpecs[t]=g(t,r)}unregisterFunction(t){delete this._functionsRegistry[t],delete this._functionSpecs[t]}validate(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n);try{this.validateNode(_.compile(t,r),o,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validateManifest(t,n,r=!1){let a=[],o=this.validationFunctionSpecs(n.functions);try{let u=_.compile(t,r);this.validateNode(u,o,a),this.validateManifestNode(u,n,a)}catch(u){a.push({code:"syntax_error",message:u instanceof Error?u.message:String(u)})}return{ok:a.length===0,errors:a}}validationFunctionSpecs(t){let n=new Map;return Object.keys(rt).forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:rt[r])}),t==null?(Object.keys(this._functionSpecs).forEach(r=>n.set(r,this._functionSpecs[r])),n):t instanceof Set?(t.forEach(r=>{var a;return n.set(r,(a=this._functionSpecs[r])!=null?a:g(r))}),n):Array.isArray(t)?(t.forEach(r=>{var a;typeof r=="string"?n.set(r,(a=this._functionSpecs[r])!=null?a:g(r)):n.set(r.name,g(r.name,r))}),n):(Object.keys(t).forEach(r=>n.set(r,g(r,t[r]))),n)}validateNode(t,n,r,a=!1){t&&(t instanceof j||t instanceof R?t.body.forEach(o=>this.validateNode(o,n,r,a)):t instanceof L?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.init,n,r,a)):t instanceof X?this.validateNode(t.expression,n,r,a):t instanceof P?this.validateCallExpression(t,n,r,a):t instanceof z?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof U?this.validateNode(t.argument,n,r,a):t instanceof D?(this.validateNode(t.test,n,r,a),this.validateNode(t.consequent,n,r,a),this.validateNode(t.alternate,n,r,a)):t instanceof W?(this.validateNode(t.left,n,r,a),this.validateNode(t.right,n,r,a)):t instanceof w?(this.validateNode(t.owner,n,r,a),this.validateNode(t.key,n,r,a)):t instanceof $?t.properties.forEach(o=>this.validateNode(o,n,r,a)):t instanceof O?(this.validateNode(t.key,n,r,a),this.validateNode(t.value,n,r,a)):t instanceof F?t.elements.forEach(o=>this.validateNode(o,n,r,a)):t instanceof B?(this.validateNode(t.test,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof K?(this.validateNode(t.init,n,r,a),this.validateNode(t.test,n,r,a),this.validateNode(t.update,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof H?(this.validateNode(t.identifier,n,r,a),this.validateNode(t.collection,n,r,a),this.validateNode(t.body,n,r,a)):t instanceof I?(this.validateNode(t.first,n,r,a),this.validateNode(t.second,n,r,a)):t instanceof Y&&this.validateNode(t.value,n,r,a))}validateCallExpression(t,n,r,a){let o=t.callee.value;if(o==="_try_"){t.arguments.length!==1&&r.push(this.validationError("invalid_try_arity",t,"_try_ expects exactly one expression","_try_",{argCount:t.arguments.length,minArgs:1,maxArgs:1})),t.arguments.forEach(u=>this.validateNode(u,n,r,!0));return}if(!a){let u=n.get(o);u?mt(u,t.arguments.length)?this.validateStaticArgumentTypes(t,u,r):r.push(this.validationError("invalid_function_arity",t,`Function '${o}' expects ${vt(u)} argument(s), got ${t.arguments.length}`,o,{argCount:t.arguments.length,minArgs:Q(u),maxArgs:u.maxArgs})):this._options.compatV1||r.push(this.validationError("unknown_function",t,`Unknown function '${o}'`,o))}t.arguments.forEach(u=>this.validateNode(u,n,r,a))}validateStaticArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var m,d;let p=t.arguments[u];if(!p)return;let f=this.staticArgumentType(p);!f||this.argumentTypeMatches(o,f)||r.push(this.validationError("invalid_argument_type",t,`Function '${n.name}' argument ${u} expects ${(m=o.type)!=null?m:"any"}, got ${f}`,n.name,{argIndex:u,expectedType:(d=o.type)!=null?d:"any",actualType:f}))})}staticArgumentType(t){if(t instanceof E)return Z(t.value);if(t instanceof F)return"array";if(t instanceof $)return"object"}argumentTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validateManifestNode(t,n,r){var p,f;let a=((p=n.inputs)!=null?p:[]).map(xt),o=((f=n.outputs)!=null?f:[]).map(xt),u={knownInputs:new Set(a.map(m=>m.name)),assigned:new Set,assignedTypes:new Map,reportedInputs:new Set};this.analyzeManifestNode(t,u,r),o.forEach(m=>{var b,bt,Et;if(((b=m.required)==null||b)&&!u.assigned.has(m.name)){r.push(this.validationError("missing_output",t,`Required output '${m.name}' is not assigned`,m.name));return}let d=u.assignedTypes.get(m.name);!d||this.valueSpecTypeMatches(m,d)||r.push(this.validationError("invalid_output_type",t,`Output '${m.name}' expects ${(bt=m.type)!=null?bt:"any"}, got ${d}`,m.name,{expectedType:(Et=m.type)!=null?Et:"any",actualType:d}))})}analyzeManifestNode(t,n,r){t&&(t instanceof j||t instanceof R?t.body.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof L?(this.analyzeManifestNode(t.init,n,r),t.identifier instanceof w&&this.analyzeManifestNode(t.identifier,n,r),this.markAssignedTarget(t.identifier,this.staticArgumentType(t.init),n)):t instanceof X?this.analyzeManifestNode(t.expression,n,r):t instanceof P?t.arguments.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof z?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof U?this.analyzeManifestNode(t.argument,n,r):t instanceof D?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.consequent,n,r),this.analyzeManifestNode(t.alternate,n,r)):t instanceof W?(this.analyzeManifestNode(t.left,n,r),this.analyzeManifestNode(t.right,n,r)):t instanceof w?(this.analyzeManifestNode(t.owner,n,r),this.analyzeManifestNode(t.key,n,r)):t instanceof $?t.properties.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof O?(this.analyzeManifestNode(t.key,n,r),this.analyzeManifestNode(t.value,n,r)):t instanceof F?t.elements.forEach(a=>this.analyzeManifestNode(a,n,r)):t instanceof B?(this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r)):t instanceof K?(this.analyzeManifestNode(t.init,n,r),this.analyzeManifestNode(t.test,n,r),this.analyzeManifestNode(t.body,n,r),this.analyzeManifestNode(t.update,n,r)):t instanceof H?(this.analyzeManifestNode(t.collection,n,r),this.markAssignedTarget(t.identifier,void 0,n),this.analyzeManifestNode(t.body,n,r)):t instanceof I?(this.analyzeManifestNode(t.first,n,r),this.analyzeManifestNode(t.second,n,r)):t instanceof Y?this.analyzeManifestNode(t.value,n,r):t instanceof x&&!n.knownInputs.has(t.value)&&!n.assigned.has(t.value)&&!n.reportedInputs.has(t.value)&&(n.reportedInputs.add(t.value),r.push(this.validationError("unknown_input",t,`Unknown input '${t.value}'`,t.value))))}markAssignedTarget(t,n,r){t instanceof x?(r.assigned.add(t.value),n&&r.assignedTypes.set(t.value,n)):t instanceof I&&(this.markAssignedTarget(t.first,void 0,r),this.markAssignedTarget(t.second,void 0,r))}valueSpecTypeMatches(t,n){var a;let r=(a=t.type)!=null?a:"any";return r==="any"||t.required===!1&&n==="null"?!0:r===n}validationError(t,n,r,a,o){return{code:t,message:r,name:a,line:n.line,col:n.col,node:n.constructor.name,argCount:o==null?void 0:o.argCount,minArgs:o==null?void 0:o.minArgs,maxArgs:o==null?void 0:o.maxArgs,argIndex:o==null?void 0:o.argIndex,expectedType:o==null?void 0:o.expectedType,actualType:o==null?void 0:o.actualType}}validateRuntimeArgumentTypes(t,n,r){var a;(a=n.args)==null||a.forEach((o,u)=>{var f,m;if(u>=r.length)return;let p=Z(r[u]);if(!this.argumentTypeMatches(o,p))throw new S(`Function '${n.name}' argument ${u} expects ${(f=o.type)!=null?f:"any"}, got ${p}`,t.line,t.col,t.constructor.name,void 0,{code:"invalid_argument_type",name:n.name,argIndex:u,expectedType:(m=o.type)!=null?m:"any",actualType:p})})}execute(t,n=!0,r){let a=_.compile(t,n);return r&&Object.keys(r).forEach(o=>this.changeVariable(o,r[o])),this.resetExecutionBudget(),this.clearTrace(),this.visit(a)}static compile(t,n=!1){let r=Mt(t);if(n&&this._cache.has(r))return this._cache.get(r);let a=new ft(t),u=new dt(a).parse();return n&&this._cache.set(r,u),u}static register(t,n,r){_._globalFunctionsRegistry[t]=n,_._globalFunctionSpecs[t]=g(t,r)}static unregister(t){delete _._globalFunctionsRegistry[t],delete _._globalFunctionSpecs[t]}static capabilities(){return wt({...rt,..._._globalFunctionSpecs})}static validateSource(t,n,r=!1){return new _().validate(t,n,r)}static validateManifestSource(t,n,r=!1){return new _().validateManifest(t,n,r)}static run(t,n=!1,r,a){return new _(a).execute(t,n,r)}static newInstance(t){return new _(t)}clone(){var t=new _(this.options);return t._functionsRegistry={...this._functionsRegistry},t._functionSpecs={...this._functionSpecs},t.rootScope.memory={...this.rootScope.memory},t}newAsyncInstance(){let t=yt.newInstance(this.options);return t.rootScope.memory=this.rootScope.memory,t._functionsRegistry=this._functionsRegistry,t._functionSpecs=this._functionSpecs,t}};_._globalFunctionsRegistry={},_._globalFunctionSpecs={},_._cache=new Map;var lt=_,yt=class s extends lt{constructor(e){super(e)}async visitRootAST(e){var r;let t=e.body,n;for(let a of t)if(n=await this.visit(a),n instanceof y)return(r=n.value)!=null?r:null;return n!=null?n:null}async visitBlockStatementAST(e){let t=e.body,n;this.pushScope("Block");for(let r of t)if(n=await this.visit(r),n instanceof V||n instanceof y)break;return this.popScope(),n}async visitIdentifierAST(e){let t=e.value;return this.resolve(t)}async visitLiteralAST(e){return e.value}async visitAssignmentExpressionAST(e){let t=e.identifier,n=e.init,r=null;if(t instanceof w){var a=await this.visit(t.owner);r=await this.visit(e.init);var o=await this.visit(t.key);this.assignProperty(a,o,r)}else t instanceof x&&(r=await this.visit(n),this.changeVariable(t.value,r));return r}async visitExpressionStatementAST(e){let t=e.expression;return await this.visit(t)}async visitCallExpressionAST(e){var f,m;let t=e.callee,n=e.arguments,r=t.value;if(r==="_try_"){if(n.length!==1)throw new S("_try_ expects exactly one expression",e.line,e.col,e.constructor.name,void 0,{code:"invalid_try_arity",name:"_try_",argCount:n.length,minArgs:1,maxArgs:1});try{let d=await this.visit(n[0]);return d instanceof V||d instanceof y?d:this.successResult(d)}catch(d){if(d instanceof S)return this.errorResult(d);throw d}}let a=this.resolveFunction(r);if(!a){if(this._options.compatV1)return null;throw new S(`Unknown function '${r}'`,e.line,e.col,e.constructor.name,void 0,{code:"unknown_function",name:r})}let o=this.resolveFunctionSpec(r);if(o&&!mt(o,n.length))throw new S(`Function '${r}' expects ${vt(o)} argument(s), got ${n.length}`,e.line,e.col,e.constructor.name,void 0,{code:"invalid_function_arity",name:r,argCount:n.length,minArgs:Q(o),maxArgs:o.maxArgs});let u=await Promise.all(n.map(d=>this.visit(d)));o&&this.validateRuntimeArgumentTypes(e,o,u),this.recordTrace("call",e,r,{argCount:u.length,returnType:(f=o==null?void 0:o.returnType)!=null?f:"any"});let p=await a(u,this);return this.recordTrace("call_result",e,r,{returnType:(m=o==null?void 0:o.returnType)!=null?m:"any",actualType:Z(p)}),p}async visitBinaryExpressionAST(e){let t=e.left,n=e.right,r=e.operation,a=await this.visit(t),o=await this.visit(n);switch(r.type){case i.plus:return h(a)&&h(o)?a+o:`${a}${o}`;case i.minus:if(h(a)&&h(o))return a-o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.mult:if(h(a)&&h(o))return a*o;if(q(a)&&h(o))return a.repeat(o);if(h(a)&&q(o))return o.repeat(a);throw new Error(`Operation ${r.value} not allowed no num value`);case i.div:if(h(a)&&h(o)){if(o===0)throw new Error("Invalid division by 0");return a/o}throw new Error(`Operation ${r.value} not allowed no num value`);case i.mod:if(h(a)&&h(o))return a%o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.great:if(h(a)&&h(o))return a>o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.greatEq:if(h(a)&&h(o))return a>=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.less:if(h(a)&&h(o))return a<o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.lessEq:if(h(a)&&h(o))return a<=o;throw new Error(`Operation ${r.value} not allowed no num value`);case i.eqeq:return a===o;case i.notEq:return a!==o;default:throw new Error(`Operation ${r.value} not allowed no num value`)}}async visitUnaryExpressionAST(e){let t=e.argument,n=e.operation,r=await this.visit(t);if(n.type===i.not)return A(r)===!1;if(!h(r))throw new Error(`Operation ${n.value} not allowed no num value`);if(n.type===i.plus)return r;if(n.type===i.minus)return-r;throw new Error(`Operation ${n.value} not allowed no num value`)}async visitIfStatementAST(e){let t=e.test,n=await this.visit(t);return A(n)?await this.visit(e.consequent):e.alternate?await this.visit(e.alternate):null}async visitLogicalExpressionAST(e){let t=e.left,n=await this.visit(t);if(e.operator.type===i.nullity)return n!=null?n:await this.visit(e.right);let r=A(n);return e.operator.type===i.and?r?A(await this.visit(e.right)):!1:e.operator.type===i.or?r?!0:A(await this.visit(e.right)):!1}async visitIndexAccessorAST(e){var r,a;let t=e.owner,n=await this.visit(t);if(n==null)return null;if(Array.isArray(n)){let o=await this.visit(e.key);return h(o)&&Number.isInteger(o)&&n.length>o&&o>=0&&(r=n[o])!=null?r:null}else if(typeof n=="object"){let o=await this.visit(e.key);return(a=n[o])!=null?a:null}return null}async visitObjectProperty(e){}async visitObjectExpression(e){let t={},n=e;for(let r of n.properties)if(r instanceof O){let a=await this.visit(r.key);a=q(a)?a:a.toString(),t[a]=await this.visit(r.value)}return t}async visitArrayExpression(e){let t=e;return await this.resolveArgumentsAsync(t.elements)}async visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let t=e.retain?[]:void 0;for(;A(await this.visit(e.test));){let n=await this.visit(e.body);if(n instanceof C)break;if(!(n instanceof M)){if(n instanceof y)return this.popScope(),n;t==null||t.push(n)}}return t}async visitForLoopStatement(e){let t=e.retain?[]:void 0,n=e.init.identifier;if(!(n instanceof x))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let r=await this.visit(e.init.init);this.changeVariable(n.value,r);let a=async()=>{let u=await this.visit(e.test);if(h(u)){let p=this.resolve(n.value);return e.direction.type===i.up?u>=p:u<=p}return A(u)},o=async()=>{let u=await this.visit(e.update);if(h(u)){let p=this.resolve(n.value);if(!h(p))throw Error("Cant update value");this.changeVariable(n.value,e.direction.type===i.up?p+u:p-u)}else throw Error("Update value cant be non number")};for(;await a();){let u=await this.visit(e.body);if(u instanceof C)break;if(u instanceof M){await o();continue}if(u instanceof y)return this.popScope(),u;t==null||t.push(u),await o()}return this.popScope(),t!=null?t:null}async visitForOfStatement(e){let t=await this.visit(e.collection);if(!Array.isArray(t))throw Error("Can iterate non array object");let n=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let r of t){this._declareForIdentifier(e.identifier,r);let a=await this.visit(e.body);if(a instanceof C)break;if(!(a instanceof M)){if(a instanceof y)return this.popScope(),a;n==null||n.push(a)}}return this.popScope(),n}async visitReturnAST(e){return new y(e.value!=null?await this.visit(e.value):null)}async resolveArgumentsAsync(e){return await Promise.all(e.map(async t=>await this.visit(t)))}registerFunction(e,t,n){this._functionsRegistry[e]=t,this._functionSpecs[e]=g(e,n)}unregisterFunction(e){delete this._functionsRegistry[e],delete this._functionSpecs[e]}async execute(e,t=!0,n){let r=lt.compile(e,t);return n&&Object.keys(n).forEach(a=>this.changeVariable(a,n[a])),this.resetExecutionBudget(),this.clearTrace(),await this.visit(r)}static async run(e,t=!1,n,r){return await new s(r).execute(e,t,n)}static newInstance(e){return new s(e)}clone(){var e=new s(this.options);return e._functionsRegistry={...this._functionsRegistry},e._functionSpecs={...this._functionSpecs},e.rootScope.memory={...this.rootScope.memory},e}};export{v as AST,F as ArrayExpression,L as AssignmentExpressionAST,z as BinaryExpressionAST,R as BlockStatementAST,et as BreakAST,C as BreakBranch,P as CallExpressionAST,nt as ContinueAST,M as ContinueBranch,X as ExpressionStatementAST,K as ForLoopStatement,H as ForOfStatement,x as IdentifierAST,D as IfStatementAST,w as IndexAccessorAST,J as LexerDictionary,E as LiteralAST,W as LogicalExpressionAST,V as LoopControl,ct as MEventScope,lt as MEvento,yt as MEventoAsync,S as MEventoRuntimeError,St as NodeVisitor,$ as ObjectExpression,O as ObjectProperty,Y as ReturnAST,y as ReturnBranch,j as RootAST,l as Token,i as TokenType,I as TupleExpression,U as UnaryExpressionAST,B as WhileLoopStatement};
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mevento",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.2",
|
|
4
|
+
"description": "An embeddable C-like scripting language with synchronous and asynchronous VMs for JavaScript and TypeScript host applications.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"embedded-scripting",
|
|
8
|
+
"scripting-language",
|
|
9
|
+
"scripting-engine",
|
|
10
|
+
"interpreter",
|
|
11
|
+
"virtual-machine",
|
|
12
|
+
"typescript",
|
|
13
|
+
"javascript",
|
|
14
|
+
"dsl"
|
|
15
|
+
],
|
|
4
16
|
"main": "dist/cjs/index.js",
|
|
5
17
|
"module": "dist/esm/index.mjs",
|
|
6
18
|
"types": "dist/esm/index.d.mts",
|