mevento 3.0.4 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +192 -31
- package/dist/cjs/index.d.ts +169 -10
- package/dist/cjs/index.js +8 -8
- package/dist/esm/index.d.mts +169 -10
- package/dist/esm/index.mjs +8 -8
- package/package.json +14 -15
package/dist/cjs/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;throw Error(
|
|
3
|
-
`,"\r","\u2028","\u2029"].includes(String.fromCharCode(
|
|
4
|
-
`;break;case"r":
|
|
5
|
-
`,t
|
|
6
|
-
`;return
|
|
7
|
-
${this.body.map(
|
|
8
|
-
`)}}`}},g=class extends d{constructor(t){super(t.line,t.col),this.value=t.value.toString()}toString(){return this.value}},m=class extends d{constructor(t,e){super(t.line,t.col),this.value=t.value,this.raw=e}toString(){return this.value.toString()}},E=class extends d{constructor(t,e){super(t.line,t.col),this.identifier=t,this.init=e}toString(){return`${this.identifier} = ${this.init}`}},X=class extends d{constructor(t){super(t.line,t.col),this.expression=t}toString(){return this.expression.toString()}},R=class extends d{constructor(t,e){super(t.line,t.col),this.callee=t,this.arguments=e}toString(){return`${this.callee.toString()}(...${this.arguments.length})`}},V=class extends d{constructor(t,e,i){super(t.line,t.col),this.left=t,this.operation=e,this.right=i}toString(){return`${this.left} ${this.operation} ${this.right}`}},q=class extends d{constructor(t,e){super(t.line,t.col),this.operation=t,this.argument=e}toString(){return`${this.operation} ${this.argument}`}},B=class extends d{constructor(t,e,i){super(t.line,t.col),this.test=t,this.consequent=e,this.alternate=i}toString(){return`if ${this.test} ${this.consequent} ${this.alternate?`else ${this.alternate} `:""}`}},P=class extends d{constructor(t,e,i){super(t.line,t.col),this.left=t,this.operator=e,this.right=i}toString(){return`${this.left} ${this.operator.value} ${this.right}`}},T=class extends d{constructor(e,i,s=!1){super(e.line,e.col);this.computed=!1;this.owner=e,this.key=i,this.computed=s}toString(){return`${this.owner}[${this.key}]`}},j=class extends d{constructor(t,e,i){super(e==null?void 0:e.line,e==null?void 0:e.col),this.properties=t}toString(){return"{...}"}},N=class extends d{constructor(t,e,i){super(e==null?void 0:e.line,e==null?void 0:e.col),this.elements=t}toString(){return"[...]"}},k=class extends d{constructor(t,e){super(t.line,t.col),this.value=e,this.key=t}},U=class extends d{constructor(e,i,s,n,o=!1){super(s==null?void 0:s.line,s==null?void 0:s.col);this.retain=!1;this.test=e,this.body=i,this.retain=o}},M=class extends d{constructor(e,i,s,n,o,a,p,S=!1){super(a==null?void 0:a.line,a==null?void 0:a.col);this.init=e;this.test=i;this.update=s;this.direction=n;this.body=o;this.retain=S}},W=class extends d{constructor(e,i,s,n,o,a=!1){super(n==null?void 0:n.line,n==null?void 0:n.col);this.identifier=e;this.collection=i;this.body=s;this.retain=a}},D=class extends d{constructor(e,i){super(e.line,e.col);this.first=e;this.second=i}},H=class extends d{constructor(t,e){super(t,e)}},K=class extends d{constructor(t,e,i){super(e,i),this.value=t}},z=class extends d{constructor(t,e){super(t,e)}},tt=class{constructor(t=1/0){this.capacity=t;this.storage=[]}push(t){if(this.size()===this.capacity)throw Error("Stack has reached max capacity, you cannot add more items");this.storage.push(t)}pop(){return this.storage.pop()}peek(){return this.storage[this.size()-1]}size(){return this.storage.length}get isEmpty(){return this.storage.length===0}},$=class ${constructor(t){this._loopTrack=new tt;this.currentToken=t.nextToken(),this.lexer=t}_eat(t){var e;((e=this.currentToken)==null?void 0:e.type)===t?this.currentToken=this.lexer.nextToken():b(this.currentToken,t)}_eatEOL(){var t;for(;((t=this.currentToken)==null?void 0:t.type)===r.eol;)this._eat(r.eol)}_eatSemiOrEOL(){var t,e;for(;((t=this.currentToken)==null?void 0:t.type)===r.eol||((e=this.currentToken)==null?void 0:e.type)===r.semi;)this._eat(this.currentToken.type)}_eatSemi(){var t;for(;((t=this.currentToken)==null?void 0:t.type)===r.semi;)this._eat(r.semi)}_variable(){let t=new g(this.currentToken);return this._eat(r.id),t}_return(){let t=this.currentToken,e;return!this._expect(r.eol)&&!this._expect(r.semi)&&(e=this._expression()),new K(e,t==null?void 0:t.line,t==null?void 0:t.col)}_factor(){let t=this.currentToken;switch(t.type){case r.plus:case r.minus:case r.not:return this._eat(this.currentToken.type),new q(t,this._term());case r.numberConst:return this._eat(r.numberConst),new m(t,t.value.toString());case r.stringConst:return this._eat(r.stringConst),new m(t,t.value.toString());case r.lparen:this._eat(r.lparen);let e=this._expression();return this._eat(r.rparen),e;case r.TRUE:case r.FALSE:return this._eat(this.currentToken.type),new m(t,t.value.toString());case r.NULL:return this._eat(r.NULL),new m(t,"null");case r.lbracket:return this._arrayExpression();case r.lbrace:return this._objectExpression();case r.IF:return this._ifStatement();case r.WHILE_TILL:return this._whileLoop(!0);case r.FOR_LOOP:return this._forLoop(!0);case r.BREAK:return this._breakExpression();case r.CONTINUE:return this._continueExpression();default:return this._variable()}}_breakExpression(){var t,e;return this._loopTrack.isEmpty&&b(this.currentToken),this._eat(r.BREAK),new H((t=this.currentToken)==null?void 0:t.line,(e=this.currentToken)==null?void 0:e.col)}_continueExpression(){var t,e;return this._loopTrack.isEmpty&&b(this.currentToken),this._eat(r.CONTINUE),new z((t=this.currentToken)==null?void 0:t.line,(e=this.currentToken)==null?void 0:e.col)}_term(){let t=this._factor();return t=this._tryParsingFunctionCall(t),t=this._tryParsingMemberExpression(t),t}_expression(){let t=this._term();for(t=this._tryBinaryExpression(0,t);[r.and,r.or,r.nullity].includes(this.currentToken.type);){let e=this.currentToken;this._eat(e.type),t=new P(t,e,this._expression())}if(this._expect(r.equal))if(t instanceof g||t instanceof T){let e=this.currentToken;this._eat(r.equal),t=new E(t,this._expression())}else throw new Error("Unexpected token");return t}_objectProperty(){var s;let t;switch((s=this.currentToken)==null?void 0:s.type){case r.stringConst:{t=new m(this.currentToken,this.currentToken.value),this._eat(r.stringConst);break}case r.lbracket:{this._eat(r.lbracket);var e=this._expression();this._eat(r.rbracket),t=e;break}case r.id:{let n=this._variable();t=new m(new h(r.id,n.value,n.line,n.col),n.value);break}default:throw`Unexpected token ${this.currentToken}`}this._eat(r.colon);var i=this._expression();return new k(t,i)}_property(){return this._objectProperty()}_objectProperties(){var e,i;let t=[];for(((e=this.currentToken)==null?void 0:e.type)!=r.rbrace&&(this._eatEOL(),t.push(this._property()),this._eatEOL());((i=this.currentToken)==null?void 0:i.type)===r.comma&&(this._eat(r.comma),this._eatEOL(),!this._expect(r.rbrace));)t.push(this._property()),this._eatEOL();return t}_objectExpression(t){var e=t!=null?t:this.currentToken;t||this._eat(r.lbrace);var i=this._objectProperties();return this._eat(r.rbrace),new j(i,e,this.currentToken)}_arrayExpression(){this._eat(r.lbracket);let t=this._expect(r.rbracket)?[]:this._expressionsList();this._eat(r.rbracket);var e=t.length!==0?t[0]:void 0,i=t.length!==0?t[t.length-1]:void 0;return new N(t,e,i)}_tryParsingMemberExpression(t){let e=t;for(;this.currentToken.type===r.lbracket;){this._eat(r.lbracket);let i=this._expression();e=new T(e,i),this._eat(r.rbracket)}return e}_tryBinaryExpression(t,e){let i=e;for(;;){let s=$._binopPrecdences[this.currentToken.type]||-1;if(s<t)return i;let n=this.currentToken;this._eat(n.type);let o=this._term(),a=$._binopPrecdences[this.currentToken.type]||-1;if(s<a){let p=this._tryBinaryExpression(s+1,o);if(p===i)return p;o=p}i=new V(i,n,o)}}_expressionsList(){var i;this._eatEOL();let t=this._expression();this._eatEOL();let e=[t];for(;((i=this.currentToken)==null?void 0:i.type)===r.comma&&(this._eat(r.comma),this._eatEOL(),!this._expect(r.rbracket));)t=this._expression(),e.push(t),this._eatEOL();return e}_callExpression(t){this._eat(r.lparen);let e=[];return this._expect(r.rparen)||(e=this._expressionsList()),this._eat(r.rparen),t instanceof g||b(this.currentToken),new R(t,e)}_tryParsingFunctionCall(t){let e=t;for(;this.currentToken.type===r.lparen;)e=this._callExpression(e);return e}_statementExpression(){let t=this._expression();return[r.semi,r.eol,r.eof].includes(this.currentToken.type)||b(this.currentToken),t}_blockStatement(t=!1){var i;if(t||this._eat(r.lbrace),this._eatEOL(),this._expect(r.rbrace))return this._eat(r.rbrace),new I([],this.currentToken);let e=[this._statement()];for(;this._eatSemiOrEOL(),!(this.currentToken.type===r.rbrace||this.currentToken.type===r.eof||(e.push(this._statement()),this._expect(r.rbrace)));)this.currentToken.type!==r.eol&&this.currentToken.type!==r.semi&&this.currentToken.type!==r.eof&&b(this.currentToken);return this._eat(r.rbrace),((i=this.currentToken)==null?void 0:i.type)===r.rbrace&&this._eat(r.rbrace),new I(e,this.currentToken)}_ifStatement(){this._eat(r.IF);let t=this.currentToken.type===r.lparen;t&&this._eat(r.lparen);let e=this._expression();t&&this._eat(r.rparen);let i;this.currentToken.type===r.lbrace?i=this._blockStatement():i=this._expression();let s;if(this.currentToken.type===r.ELSE)switch(this._eat(r.ELSE),this.currentToken.type){case r.IF:s=this._ifStatement();break;case r.lbrace:s=this._blockStatement();break;default:s=this._expression()}return new B(e,i,s)}_pushLoop(){this._loopTrack.push(!0)}_popLoop(){this._loopTrack.pop()}_whileLoop(t=!1){let e=this.currentToken;this._eat(r.WHILE_TILL),this._pushLoop();let i=this._expression(),s=this.currentToken.type===r.lbrace?this._blockStatement():this._expression();return this._popLoop(),new U(i,s,e,this.currentToken,t)}_forOfIdentifier(){switch(this.currentToken.type){case r.lparen:{this._eat(r.lparen);let t=this._variable();this._eat(r.comma);let e=this._variable();return this._eat(r.rparen),new D(t,e)}default:return this._variable()}}_forLoop(t=!1){let e=this.currentToken;this._eat(r.FOR_LOOP),this._pushLoop();let i=[r.lparen].includes(this.currentToken.type),s;if(i)s=this._forOfIdentifier();else{let n=this._expression();n instanceof E||(i=!0),s=n}if(!i&&s instanceof E){this._eat(r.TILL);let n=this._expression(),o;if(this.currentToken.type===r.up||this.currentToken.type===r.down){let S=this.currentToken;this._eat(S.type),o=S}else o=new h(r.up,"up");let a;this._expect(r.with)?(this._eat(r.with),a=this._expression()):a=new m(new h(r.numberConst,1,this.currentToken.line,this.currentToken.col),"1");let p=this.currentToken.type===r.lbrace?this._blockStatement():this._expression();s=new M(s,n,a,o,p,e,this.currentToken,t),this._popLoop()}else if(i){this._eat(r.in);let n=this._expression(),o=this.currentToken.type===r.lbrace?this._blockStatement():this._expression();s=new W(s,n,o,e,this.currentToken,t),this._popLoop()}else b(this.currentToken);return s}_statement(){switch(this.currentToken.type){case r.BREAK:return this._breakExpression();case r.CONTINUE:return this._continueExpression();case r.RETURN:return this._eat(r.RETURN),this._return();case r.semi:return this._eatSemi(),this._statement();case r.eol:return this._eatEOL(),this._statement();case r.WHILE_TILL:return this._whileLoop();case r.FOR_LOOP:return this._forLoop();default:return this._statementExpression()}}_expect(t){var e;return((e=this.currentToken)==null?void 0:e.type)===t}_definition(){if(this._eatSemiOrEOL(),this._expect(r.eof))return[];let t=[this._statement()];for(;;){if(this._eatSemiOrEOL(),this.currentToken.type===r.eof){this._eat(r.eof);break}this.currentToken.type===r.lbrace?t.push(this._blockStatement()):t.push(this._statement())}return t}_root(){let t=this.lexer.source,e="<module>",i=this._definition();return new F(i,e,t)}parse(){return this._root()}};$._binopPrecdences={[r.eqeq]:10,[r.notEq]:10,[r.great]:10,[r.greatEq]:10,[r.less]:10,[r.lessEq]:10,[r.plus]:20,[r.minus]:20,[r.mult]:40,[r.div]:40,[r.mod]:40};var et=$,C=class{},A=class extends C{},w=class extends C{},f=class{constructor(t){this.value=t}},rt=class{constructor(){this._nodesVisitors={}}registerVisitor(t,e){let i=`visit${t.name}`;this._nodesVisitors[i]=e}},G=class extends rt{constructor(){super(),this.registerVisitor(F,this.visitRootAST),this.registerVisitor(I,this.visitBlockStatementAST),this.registerVisitor(g,this.visitIdentifierAST),this.registerVisitor(m,this.visitLiteralAST),this.registerVisitor(E,this.visitAssignmentExpressionAST),this.registerVisitor(X,this.visitExpressionStatementAST),this.registerVisitor(R,this.visitCallExpressionAST),this.registerVisitor(V,this.visitBinaryExpressionAST),this.registerVisitor(q,this.visitUnaryExpressionAST),this.registerVisitor(B,this.visitIfStatementAST),this.registerVisitor(P,this.visitLogicalExpressionAST),this.registerVisitor(T,this.visitIndexAccessorAST),this.registerVisitor(k,this.visitObjectProperty),this.registerVisitor(j,this.visitObjectExpression),this.registerVisitor(N,this.visitArrayExpression),this.registerVisitor(U,this.visitWhileLoopStatement),this.registerVisitor(M,this.visitForLoopStatement),this.registerVisitor(W,this.visitForOfStatement),this.registerVisitor(H,this.visitBreakAST),this.registerVisitor(z,this.visitContinueAST),this.registerVisitor(K,this.visitReturnAST)}visit(t){var e;try{let i=`visit${t.constructor.name}`,s=this._nodesVisitors[i];return(e=s==null?void 0:s.call(this,t))!=null?e:null}catch{return null}}assignProperty(t,e,i){(Array.isArray(t)||typeof t=="object")&&(t[e]=i)}},Q=class{constructor(t,e,i){this.memory={};this.name=t,this.memory=e,this.parent=i}resolve(t){var e,i;return Object.keys(this.memory).includes(t)?this.memory[t]:(i=(e=this.parent)==null?void 0:e.resolve(t))!=null?i:null}change(t,e,i=!0){return Object.keys(this.memory).includes(t)?(this.memory[t]=e,!0):this.parent&&this.parent.change(t,e,!1)?!0:i?(this.memory[t]=e,!0):!1}},_=class _ extends G{constructor(){super();this.rootScope=new Q("Program",{});this.currentScope=this.rootScope;this.debug=!1;this._functionsRegistry={};this._functionsRegistry={..._._globalFunctionsRegistry}}resolve(e){var i,s;return(s=(i=this.currentScope)==null?void 0:i.resolve(e))!=null?s:null}changeVariable(e,i){var s;return(s=this.currentScope)!=null&&s.change(e,i)?i:null}pushScope(e){let i=new Q(e,{},this.currentScope);this.currentScope=i}popScope(){var e;this.currentScope=(e=this.currentScope)==null?void 0:e.parent}log(e){this.debug&&console.log(e)}visitRootAST(e){var n;let i=e.body,s;for(let o of i)if(s=this.visit(o),s instanceof f)return(n=s.value)!=null?n:null;return s!=null?s:null}visitBlockStatementAST(e){let i=e.body,s;this.pushScope("Block");for(let n of i)if(s=this.visit(n),s instanceof C||s instanceof f)break;return this.popScope(),s!=null?s:null}visitIdentifierAST(e){var s;let i=e.value;return(s=this==null?void 0:this.resolve(i))!=null?s:null}visitLiteralAST(e){return e.value}visitAssignmentExpressionAST(e){let i=e.identifier,s=e.init,n=null;if(i instanceof T){var o=this.visit(i.owner);n=this.visit(e.init);var a=this.visit(i.key);this.assignProperty(o,a,n)}else i instanceof g&&(n=this.visit(s),this.changeVariable(i.value,n));return n}visitExpressionStatementAST(e){let i=e.expression;return this.visit(i)}visitCallExpressionAST(e){let i=e.callee,s=e.arguments,n=i.value,o=this.resolveFunction(n),a=s.map(p=>this.visit(p));return o==null?void 0:o(a,this)}visitBinaryExpressionAST(e){let i=e.left,s=e.right,n=e.operation,o=this.visit(i),a=this.visit(s);switch(n.type){case r.plus:return l(o)&&l(a)?o+a:`${o}${a}`;case r.minus:if(l(o)&&l(a))return o-a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.mult:if(l(o)&&l(a))return o*a;if(x(o)&&l(a))return o.repeat(a);if(l(o)&&x(a))return a.repeat(o);throw new Error(`Operation ${n.value} not allowed no num value`);case r.div:if(l(o)&&l(a)){if(a===0)throw new Error("Invalid division by 0");return o/a}throw new Error(`Operation ${n.value} not allowed no num value`);case r.mod:if(l(o)&&l(a))return o%a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.great:if(l(o)&&l(a))return o>a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.greatEq:if(l(o)&&l(a))return o>=a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.less:if(l(o)&&l(a))return o<a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.lessEq:if(l(o)&&l(a))return o<=a;throw new Error(`Operation ${n.value} not allowed no num value`);case r.eqeq:return o===a;case r.notEq:return o!==a;default:throw new Error(`Operation ${n.value} not allowed no num value`)}}visitUnaryExpressionAST(e){let i=e.argument,s=e.operation,n=this.visit(i);if(s.type===r.not)return v(n)===!1;if(!l(n))throw new Error(`Operation ${s.value} not allowed no num value`);if(s.type===r.plus)return n;if(s.type===r.minus)return-n;throw new Error(`Operation ${s.value} not allowed no num value`)}visitIfStatementAST(e){let i=e.test,s=this.visit(i);return v(s)?this.visit(e.consequent):e.alternate?this.visit(e.alternate):null}visitLogicalExpressionAST(e){let i=e.left,s=this.visit(i);if(e.operator.type===r.nullity)return s!=null?s:this.visit(e.right);let n=v(s);return e.operator.type===r.and?n?v(this.visit(e.right)):!1:e.operator.type===r.or?n?!0:v(this.visit(e.right)):null}visitIndexAccessorAST(e){var n,o;let i=e.owner,s=this.visit(i);if(s==null)return null;if(typeof s=="object"){let a=this.visit(e.key);return(n=s[a])!=null?n:null}else if(Array.isArray(s)){let a=this.visit(e.key);return l(a)&&s.length<a&&a>=0&&(o=s[a])!=null?o:null}return null}visitObjectProperty(e){}visitObjectExpression(e){let i={},s=e;for(let n of s.properties)if(n instanceof k){let o=this.visit(n.key);o=x(o)?o:o.toString(),i[o]=this.visit(n.value)}return i}visitArrayExpression(e){let i=e;return this.resolveArguments(i.elements)}visitBreakAST(e){return new A}visitWhileLoopStatement(e){this.log(`WhileLoopStatement ${e.test} ${e.body}`);let i=e.retain?[]:void 0;for(;v(this.visit(e.test));){let s=this.visit(e.body);if(s instanceof A)break;if(!(s instanceof w)){if(s instanceof f)return this.popScope(),s;i==null||i.push(s)}}return i!=null?i:null}visitForLoopStatement(e){let i=e.retain?[]:void 0,s=e.init.identifier;if(!(s instanceof g))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let n=this.visit(e.init.init);this.changeVariable(s.value,n);let o=()=>{let p=this.visit(e.test);if(l(p)){let S=this.resolve(s.value);return e.direction.type===r.up?p>=S:p<=S}return v(p)},a=()=>{let p=this.visit(e.update);if(l(p)){let S=this.resolve(s.value);if(!l(S))throw Error("Cant update value");this.changeVariable(s.value,e.direction.type===r.up?S+p:S-p)}else throw Error("Update value cant be non number")};for(;o();){let p=this.visit(e.body);if(p instanceof A)break;if(p instanceof w){a();continue}if(p instanceof f)return this.popScope(),p;i==null||i.push(p),a()}return this.popScope(),i!=null?i:null}visitForOfStatement(e){let i=this.visit(e.collection);if(!Array.isArray(i))throw Error("Can iterate non array object");let s=e.retain?[]:void 0;this.pushScope("ForOfStatement");for(let n of i){this._declareForIdentifier(e.identifier,n);let o=this.visit(e.body);if(o instanceof A)break;if(!(o instanceof w)){if(o instanceof f)return this.popScope(),o;s==null||s.push(o)}}return this.popScope(),s!=null?s:null}visitContinueAST(e){return new w}visitReturnAST(e){return new f(e.value!=null?this.visit(e.value):null)}_declareForIdentifier(e,i){if(e instanceof D){if(!Array.isArray(i))throw Error("Unable to make a tuple from non Array element");this.changeVariable(e.first.value,i[0]),this.changeVariable(e.second.value,i[1])}this.changeVariable(e.value,i)}resolveArguments(e){return e.map(i=>this.visit(i))}setFunctionResolver(e){this._functionResolver=e}resolveFunction(e){var i,s;return(s=this._functionsRegistry[e])!=null?s:(i=this._functionResolver)==null?void 0:i.call(this,e)}registerFunction(e,i){this._functionsRegistry[e]=i}unregisterFunction(e){delete this._functionsRegistry[e]}execute(e,i=!0,s){let n=_.compile(e,i);return s&&Object.keys(s).forEach(o=>this.changeVariable(o,s[o])),this.visit(n)}static compile(e,i=!1){let s=ht(e);if(i&&this._cache.has(s))return this._cache.get(s);let n=new Z(e),a=new et(n).parse();return i&&this._cache.set(s,a),a}static register(e,i){_._globalFunctionsRegistry[e]=i}static unregister(e){delete _._globalFunctionsRegistry[e]}static run(e,i=!1,s){let n=new _,o=_.compile(e,i);return s&&Object.keys(s).forEach(a=>n.changeVariable(a,s[a])),n.visit(o)}static newInstance(){return new _}clone(){var e=new _;return e._functionsRegistry={...this._functionsRegistry},e.rootScope.memory={...this.rootScope.memory},e}newAsyncInstance(){let e=J.newInstance();return e.rootScope.memory=this.rootScope.memory,e._functionsRegistry=this._functionsRegistry,e}};_._globalFunctionsRegistry={},_._cache=new Map;var O=_,J=class c extends O{constructor(){super()}async visitRootAST(t){var s;let e=t.body,i;for(let n of e)if(i=await this.visit(n),i instanceof f)return(s=i.value)!=null?s:null;return i!=null?i:null}async visitBlockStatementAST(t){let e=t.body,i;this.pushScope("Block");for(let s of e)if(i=await this.visit(s),i instanceof C||i instanceof f)break;return this.popScope(),i}async visitIdentifierAST(t){let e=t.value;return this.resolve(e)}async visitLiteralAST(t){return t.value}async visitAssignmentExpressionAST(t){let e=t.identifier,i=t.init,s=null;if(e instanceof T){var n=await this.visit(e.owner);s=await this.visit(t.init);var o=await this.visit(e.key);this.assignProperty(n,o,s)}else e instanceof g&&(s=await this.visit(i),this.changeVariable(e.value,s));return s}async visitExpressionStatementAST(t){let e=t.expression;return await this.visit(e)}async visitCallExpressionAST(t){let e=t.callee,i=t.arguments,s=e.value,n=this._functionsRegistry[s],o=await Promise.all(i.map(a=>this.visit(a)));return await(n==null?void 0:n(o,this))}async visitBinaryExpressionAST(t){let e=t.left,i=t.right,s=t.operation,n=await this.visit(e),o=await this.visit(i);switch(s.type){case r.plus:return l(n)&&l(o)?n+o:`${n}${o}`;case r.minus:if(l(n)&&l(o))return n-o;if(x(n)&&l(o))return n.repeat(o);if(l(n)&&x(o))return o.repeat(n);throw new Error(`Operation ${s.value} not allowed no num value`);case r.mult:if(l(n)&&l(o))return n*o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.div:if(l(n)&&l(o)){if(o===0)throw new Error("Invalid division by 0");return n/o}throw new Error(`Operation ${s.value} not allowed no num value`);case r.mod:if(l(n)&&l(o))return n%o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.great:if(l(n)&&l(o))return n>o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.greatEq:if(l(n)&&l(o))return n>=o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.less:if(l(n)&&l(o))return n<o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.lessEq:if(l(n)&&l(o))return n<=o;throw new Error(`Operation ${s.value} not allowed no num value`);case r.eqeq:return n===o;case r.notEq:return n!==o;default:throw new Error(`Operation ${s.value} not allowed no num value`)}}async visitUnaryExpressionAST(t){let e=t.argument,i=t.operation,s=await this.visit(e);if(i.type===r.not)return v(s)===!1;if(!l(s))throw new Error(`Operation ${i.value} not allowed no num value`);if(i.type===r.plus)return s;if(i.type===r.minus)return-s;throw new Error(`Operation ${i.value} not allowed no num value`)}async visitIfStatementAST(t){let e=t.test,i=await this.visit(e);return v(i)?await this.visit(t.consequent):t.alternate?await this.visit(t.alternate):null}async visitLogicalExpressionAST(t){let e=t.left,i=await this.visit(e);if(t.operator.type===r.nullity)return i!=null?i:await this.visit(t.right);let s=v(i);return t.operator.type===r.and?s?v(await this.visit(t.right)):!1:t.operator.type===r.or?s?!0:v(await this.visit(t.right)):!1}async visitIndexAccessorAST(t){var s,n;let e=t.owner,i=await this.visit(e);if(i==null)return null;if(typeof i=="object"){let o=await this.visit(t.key);return(s=i[o])!=null?s:null}else if(Array.isArray(i)){let o=await this.visit(t.key);return l(o)&&i.length<o&&o>=0&&(n=i[o])!=null?n:null}return null}async visitObjectProperty(t){}async visitObjectExpression(t){let e={},i=t;for(let s of i.properties)if(s instanceof k){let n=await this.visit(s.key);n=x(n)?n:n.toString(),e[n]=await this.visit(s.value)}return e}async visitArrayExpression(t){let e=t;return await this.resolveArgumentsAsync(e.elements)}async visitWhileLoopStatement(t){this.log(`WhileLoopStatement ${t.test} ${t.body}`);let e=t.retain?[]:void 0;for(;v(await this.visit(t.test));){let i=await this.visit(t.body);if(i instanceof A)break;if(!(i instanceof w)){if(i instanceof f)return this.popScope(),i;e==null||e.push(i)}}return e}async visitForLoopStatement(t){let e=t.retain?[]:void 0,i=t.init.identifier;if(!(i instanceof g))throw new Error("Unexpected identifer found");this.pushScope("ForLoopStatement");let s=await this.visit(t.init.init);this.changeVariable(i.value,s);let n=async()=>{let a=await this.visit(t.test);if(l(a)){let p=this.resolve(i.value);return t.direction.type===r.up?a>=p:a<=p}return v(a)},o=async()=>{let a=await this.visit(t.update);if(l(a)){let p=this.resolve(i.value);if(!l(p))throw Error("Cant update value");this.changeVariable(i.value,t.direction.type===r.up?p+a:p-a)}else throw Error("Update value cant be non number")};for(;await n();){let a=await this.visit(t.body);if(a instanceof A)break;if(a instanceof w){await o();continue}if(a instanceof f)return this.popScope(),a;e==null||e.push(a),await o()}return this.popScope(),e!=null?e:null}async visitForOfStatement(t){let e=await this.visit(t.collection);if(!Array.isArray(e))throw Error("Can iterate non array object");let i=t.retain?[]:void 0;this.pushScope("ForOfStatement");for(let s of e){this._declareForIdentifier(t.identifier,s);let n=await this.visit(t.body);if(n instanceof A)break;if(!(n instanceof w)){if(n instanceof f)return this.popScope(),n;i==null||i.push(n)}}return this.popScope(),i}async visitReturnAST(t){return new f(t.value!=null?await this.visit(t.value):null)}async resolveArgumentsAsync(t){return await Promise.all(t.map(async e=>await this.visit(e)))}registerFunction(t,e){this._functionsRegistry[t]=e}unregisterFunction(t){delete this._functionsRegistry[t]}async execute(t,e=!0,i){let s=O.compile(t,e);return i&&Object.keys(i).forEach(n=>this.changeVariable(n,i[n])),await this.visit(s)}static async run(t,e=!1,i){let s=new c,n=O.compile(t,e);return i&&Object.keys(i).forEach(o=>s.changeVariable(o,i[o])),await s.visit(n)}static newInstance(){return new c}clone(){var t=new c;return t._functionsRegistry={...this._functionsRegistry},t.rootScope.memory={...this.rootScope.memory},t}};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,NodeVisitor,ObjectExpression,ObjectProperty,ReturnAST,ReturnBranch,RootAST,Token,TokenType,TupleExpression,UnaryExpressionAST,WhileLoopStatement});
|
|
1
|
+
var mt=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Lt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Nt=(s,e)=>{for(var t in e)mt(s,t,{get:e[t],enumerable:!0})},It=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lt(e))!Ot.call(s,r)&&r!==t&&mt(s,r,{get:()=>e[r],enumerable:!(n=Mt(e,r))||n.enumerable});return s};var $t=s=>It(mt({},"__esModule",{value:!0}),s);var Bt={};Nt(Bt,{AST:()=>m,ArrayExpression:()=>$,AssignmentExpressionAST:()=>L,BinaryExpressionAST:()=>P,BlockStatementAST:()=>F,BreakAST:()=>Z,BreakBranch:()=>C,CallExpressionAST:()=>j,ContinueAST:()=>tt,ContinueBranch:()=>M,ExpressionStatementAST:()=>G,ForLoopStatement:()=>B,ForOfStatement:()=>K,IdentifierAST:()=>E,IfStatementAST:()=>U,IndexAccessorAST:()=>w,LexerDictionary:()=>X,LiteralAST:()=>A,LogicalExpressionAST:()=>D,LoopControl:()=>R,MEventScope:()=>rt,MEvento:()=>it,MEventoAsync:()=>pt,MEventoRuntimeError:()=>S,NodeVisitor:()=>ht,ObjectExpression:()=>I,ObjectProperty:()=>O,ReturnAST:()=>H,ReturnBranch:()=>y,RootAST:()=>q,Token:()=>l,TokenType:()=>i,TupleExpression:()=>N,UnaryExpressionAST:()=>z,WhileLoopStatement:()=>W});module.exports=$t(Bt);function T(s,e){let t=`Invalid token ${s.type}[${s.value}] at ${s.line}, ${s.col} ${e?`: expecting ${e} token`:""}
|
|
2
|
+
`;throw Error(t)}function h(s){return typeof s=="number"}function Ft(s){return typeof s=="boolean"}function Y(s){return typeof s=="string"}function b(s){return!(s===null||h(s)&&s===0||Y(s)&&s.length===0||Ft(s)&&!s)}function Rt(s){let e=0,t=0,n;if(s.length===0)return e;for(t=0;t<s.length;t++)n=s.charCodeAt(t),e=(e<<5)-e+n,e|=0;return e}var i=class{};i.id=0,i.comma=1,i.semi=2,i.numberConst=3,i.stringConst=4,i.equal=5,i.lparen=6,i.rparen=7,i.eol=8,i.eof=9,i.lbrace=10,i.rbrace=11,i.lbracket=12,i.rbracket=13,i.great=14,i.greatEq=15,i.less=16,i.lessEq=17,i.eqeq=18,i.IF=19,i.ELSE=20,i.TRUE=21,i.FALSE=22,i.NULL=23,i.not=24,i.notEq=25,i.and=26,i.or=27,i.plus=28,i.minus=29,i.div=30,i.mult=31,i.mod=32,i.invalid=33,i.colon=34,i.WHILE_TILL=35,i.FOR_LOOP=36,i.up=37,i.down=38,i.with=39,i.in=40,i.TILL=41,i.BREAK=42,i.CONTINUE=43,i.nullity=44,i.RETURN=45,i.dot=46;var l=class s{constructor(e,t,n=1,r=1){this.type=e,this.value=t,this.line=n,this.col=r}static from(e,t){return new s(e,t)}toString(){return`[${this.type.toString()}, ${this.value}]`}},c=class{};c.equal=61,c.comma=44,c.semiColon=59,c.lparen=40,c.rparen=41,c.backslash=92,c.quote=34,c.squote=39,c.plus=43,c.minus=45,c.star=42,c.slash=47,c.percent=37,c.lbrace=123,c.rbrace=125,c.lbracket=91,c.rbracket=93,c.not=33,c.great=62,c.less=60,c.and=38,c.pipe=124,c.colon=58,c.questionMark=63,c.shebang=35,c.dot=46;var X=class{constructor(e,t){this.keywords={};this.keywords={...t},this.lang=e}},k=class k{constructor(e){this._position=0;this._line=1;this._col=1;this._currentChar=-1;this._source=e,this._currentChar=this._source[this._position].charCodeAt(0),this._resolveLanguage()}get source(){return this._source}_resolveLanguage(){var t;let e=this.nextToken();if(e.type===i.less){let n=this.nextToken();n.type!==i.id&&T(e);let r=n.value.toString();this._language=(t=k.languages.find(a=>a.lang===r))!=null?t:k._defaultLanguage,e=this.nextToken(),e.type!==i.great&&T(e)}else this._language=k._defaultLanguage,this._position=0,this._currentChar=this._source[this._position].charCodeAt(0)}_advance(){if(this._position++,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col++}_jump(e){if(this._position+=e,this._position>=this._source.length){this._currentChar=-1;return}this._currentChar=this._source[this._position].charCodeAt(0),this._col+=e}_pick(){return this._position+1>=this._source.length?-1:this._source[this._position+1].charCodeAt(0)}_isId(e){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123}_isIdStart(e){return e<65?e===36:e<91?!0:e<97?e===95:e<123}_id(){var o,u;let e="",t=this._col,n=this._position,r=this._line;for(;this._isId(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();let a=this._language&&(o=this._language.keywords[e])!=null?o:e;return(u=k.RESERVED[a])!=null?u:new l(i.id,e,r,t)}_isLineEnd(e){return e===10||e===13||[`
|
|
3
|
+
`,"\r","\u2028","\u2029"].includes(String.fromCharCode(e))}_isWhiteSpace(e){return[" "," "].includes(String.fromCharCode(e))}_isDigit(e){return e>0&&(e^48)<=9}_skipWhiteSpace(){for(;this._isWhiteSpace(this._currentChar)===!0;)this._advance()}_number(){let e="",t=this._col,n=this._position,r=this._line,a=String.fromCharCode(this._currentChar);this._advance();let o=String.fromCharCode(this._currentChar),u=10;if(a==="0"&&["b","B","x","X","o","O"].includes(o))switch(this._advance(),o.toLowerCase()){case"b":u=2;break;case"o":u=8;break;case"x":u=16;break;default:u=10}else e+=a,u=10;for(;this._isDigit(this._currentChar)||u===16&&["A","a","B","b","C","c","D","d","E","e","F","f"].includes(String.fromCharCode(this._currentChar));)e+=String.fromCharCode(this._currentChar),this._advance();if(String.fromCharCode(this._currentChar)==="."&&this._isDigit(this._pick())===!0){for(u!==10&&T(new l(i.id,o,r,n)),e+=String.fromCharCode(this._currentChar),this._advance();this._isDigit(this._currentChar);)e+=String.fromCharCode(this._currentChar),this._advance();return new l(i.numberConst,parseFloat(e),r,t)}return new l(i.numberConst,parseInt(e,u),r,t)}_literalString(e){let t="",n=-1,r=this._position,a=this._col,o=this._line;for(;this._currentChar!==-1;){let u=String.fromCharCode(this._pick());if(this._currentChar==c.backslash){switch(u){case"\\":t+="\\";break;case"0":t+="\0";break;case"a":t+="a";break;case"b":t+="\b";break;case"f":t+="\f";break;case"n":t+=`
|
|
4
|
+
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+6),16)),this._jump(4);break;case"v":t+="\v";break;case"x":t+=String.fromCharCode(Number.parseInt(this._source.substring(this._position+2,this._position+4),16)),this._jump(2);break;default:if(String.fromCharCode(e)==u)t+=String.fromCharCode(e);else{this._advance(),n=this._currentChar,t+=String.fromCharCode(this._currentChar),this._advance();continue}}this._jump(2),n=this._currentChar;continue}if(this._currentChar===e&&n!==c.backslash)break;t+=String.fromCharCode(this._currentChar),n=this._currentChar,this._advance()}return new l(i.stringConst,t,o,a)}_skipLineComment(){for(;!this._isLineEnd(this._currentChar)&&this._currentChar!=-1;)this._advance()}_skipComment(){for(;this._currentChar!==-1;){if(this._currentChar===c.star&&this._pick()===c.shebang){this._advance(),this._advance();break}this._advance()}}nextToken(){let e=this._line,t=this._col,n=this._position;for(;this._currentChar!==-1;){if(this._isLineEnd(this._currentChar))return this._line++,this._col=1,this._advance(),new l(i.eol,`
|
|
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
|
+
`;return e+="}",e}},F=class extends m{constructor(e,t){super(t.line,t.col),this.body=e}toString(){return`{
|
|
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});
|
package/dist/esm/index.d.mts
CHANGED
|
@@ -45,6 +45,7 @@ declare class TokenType {
|
|
|
45
45
|
static CONTINUE: number;
|
|
46
46
|
static nullity: number;
|
|
47
47
|
static RETURN: number;
|
|
48
|
+
static dot: number;
|
|
48
49
|
}
|
|
49
50
|
declare class Token {
|
|
50
51
|
type: number;
|
|
@@ -73,6 +74,106 @@ declare abstract class AST {
|
|
|
73
74
|
constructor(line?: number, col?: number);
|
|
74
75
|
dump(): string;
|
|
75
76
|
}
|
|
77
|
+
declare class MEventoRuntimeError extends Error {
|
|
78
|
+
line?: number;
|
|
79
|
+
col?: number;
|
|
80
|
+
nodeType?: string;
|
|
81
|
+
cause?: unknown;
|
|
82
|
+
detail: string;
|
|
83
|
+
code: string;
|
|
84
|
+
diagnosticName?: string;
|
|
85
|
+
argCount?: number;
|
|
86
|
+
minArgs?: number;
|
|
87
|
+
maxArgs?: number;
|
|
88
|
+
argIndex?: number;
|
|
89
|
+
expectedType?: string;
|
|
90
|
+
actualType?: string;
|
|
91
|
+
stepCount?: number;
|
|
92
|
+
maxSteps?: number;
|
|
93
|
+
constructor(detail: string, line?: number, col?: number, nodeType?: string, cause?: unknown, diagnostic?: Partial<Omit<MEventoDiagnostic, "message" | "line" | "col" | "node">>);
|
|
94
|
+
static fromNode(node: AST, error: unknown): MEventoRuntimeError;
|
|
95
|
+
private static format;
|
|
96
|
+
diagnostic(): MEventoDiagnostic;
|
|
97
|
+
}
|
|
98
|
+
type MEventoDiagnostic = {
|
|
99
|
+
code: string;
|
|
100
|
+
message: string;
|
|
101
|
+
name?: string;
|
|
102
|
+
line?: number;
|
|
103
|
+
col?: number;
|
|
104
|
+
node?: string;
|
|
105
|
+
argCount?: number;
|
|
106
|
+
minArgs?: number;
|
|
107
|
+
maxArgs?: number;
|
|
108
|
+
argIndex?: number;
|
|
109
|
+
expectedType?: string;
|
|
110
|
+
actualType?: string;
|
|
111
|
+
stepCount?: number;
|
|
112
|
+
maxSteps?: number;
|
|
113
|
+
};
|
|
114
|
+
type MEventoValidationError = MEventoDiagnostic;
|
|
115
|
+
type MEventoValidationResult = {
|
|
116
|
+
ok: boolean;
|
|
117
|
+
errors: MEventoValidationError[];
|
|
118
|
+
};
|
|
119
|
+
type MEventoFunctionSpec = {
|
|
120
|
+
name: string;
|
|
121
|
+
minArgs?: number;
|
|
122
|
+
maxArgs?: number;
|
|
123
|
+
tags?: Iterable<string>;
|
|
124
|
+
args?: MEventoArgSpec[];
|
|
125
|
+
returnType?: string;
|
|
126
|
+
description?: string;
|
|
127
|
+
returnDescription?: string;
|
|
128
|
+
examples?: MEventoFunctionExample[];
|
|
129
|
+
metadata?: {
|
|
130
|
+
[name: string]: unknown;
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
type MEventoFunctionExample = {
|
|
134
|
+
title?: string;
|
|
135
|
+
script: string;
|
|
136
|
+
result?: unknown;
|
|
137
|
+
description?: string;
|
|
138
|
+
};
|
|
139
|
+
type MEventoArgSpec = {
|
|
140
|
+
name: string;
|
|
141
|
+
type?: string;
|
|
142
|
+
required?: boolean;
|
|
143
|
+
description?: string;
|
|
144
|
+
metadata?: {
|
|
145
|
+
[name: string]: unknown;
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
type MEventoOptions = {
|
|
149
|
+
maxSteps?: number;
|
|
150
|
+
trace?: boolean;
|
|
151
|
+
compatV1?: boolean;
|
|
152
|
+
};
|
|
153
|
+
type MEventoValueSpec = {
|
|
154
|
+
name: string;
|
|
155
|
+
type?: string;
|
|
156
|
+
required?: boolean;
|
|
157
|
+
};
|
|
158
|
+
type MEventoScriptManifest = {
|
|
159
|
+
functions?: MEventoFunctionList;
|
|
160
|
+
inputs?: MEventoValueSpec[];
|
|
161
|
+
outputs?: MEventoValueSpec[];
|
|
162
|
+
};
|
|
163
|
+
type MEventoTraceEvent = {
|
|
164
|
+
kind: string;
|
|
165
|
+
line?: number;
|
|
166
|
+
col?: number;
|
|
167
|
+
node?: string;
|
|
168
|
+
name?: string;
|
|
169
|
+
stepCount?: number;
|
|
170
|
+
detail: {
|
|
171
|
+
[name: string]: unknown;
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
type MEventoFunctionList = Set<string> | string[] | MEventoFunctionSpec[] | {
|
|
175
|
+
[name: string]: MEventoFunctionSpec;
|
|
176
|
+
};
|
|
76
177
|
declare class RootAST extends AST {
|
|
77
178
|
body: AST[];
|
|
78
179
|
source: string;
|
|
@@ -220,6 +321,7 @@ declare abstract class ANodeVisitor {
|
|
|
220
321
|
declare abstract class NodeVisitor extends ANodeVisitor {
|
|
221
322
|
constructor();
|
|
222
323
|
visit(node: AST): any;
|
|
324
|
+
protected beforeVisit(_node: AST): void;
|
|
223
325
|
protected assignProperty(owner: any, property: any, value: any): any;
|
|
224
326
|
protected abstract visitRootAST(node: RootAST): any;
|
|
225
327
|
protected abstract visitBlockStatementAST(node: BlockStatementAST): any;
|
|
@@ -261,17 +363,43 @@ declare class MEvento extends NodeVisitor {
|
|
|
261
363
|
protected currentScope?: MEventScope;
|
|
262
364
|
debug: boolean;
|
|
263
365
|
private static _globalFunctionsRegistry;
|
|
366
|
+
private static _globalFunctionSpecs;
|
|
264
367
|
private static _cache;
|
|
265
368
|
protected _functionsRegistry: {
|
|
266
369
|
[k: string]: MEventoFBinding;
|
|
267
370
|
};
|
|
371
|
+
protected _functionSpecs: {
|
|
372
|
+
[k: string]: MEventoFunctionSpec;
|
|
373
|
+
};
|
|
268
374
|
protected _functionResolver?: (name: string) => MEventoFBinding | undefined;
|
|
269
|
-
|
|
375
|
+
protected _options: MEventoOptions;
|
|
376
|
+
private _executionStepCount;
|
|
377
|
+
private _traceEvents;
|
|
378
|
+
constructor(options?: MEventoOptions);
|
|
379
|
+
get options(): MEventoOptions;
|
|
380
|
+
get executionStepCount(): number;
|
|
381
|
+
trace(): MEventoTraceEvent[];
|
|
382
|
+
protected resetExecutionBudget(): void;
|
|
383
|
+
protected beforeVisit(node: AST): void;
|
|
384
|
+
protected clearTrace(): void;
|
|
385
|
+
protected recordTrace(kind: string, node: AST, name?: string, detail?: {
|
|
386
|
+
[name: string]: unknown;
|
|
387
|
+
}): void;
|
|
270
388
|
protected resolve(name: string): any;
|
|
271
389
|
protected changeVariable(name: string, value: any): any;
|
|
272
390
|
protected pushScope(name: string): void;
|
|
273
391
|
protected popScope(): void;
|
|
274
392
|
protected log(message: any): void;
|
|
393
|
+
protected successResult(value: any): {
|
|
394
|
+
ok: boolean;
|
|
395
|
+
value: any;
|
|
396
|
+
error: any;
|
|
397
|
+
};
|
|
398
|
+
protected errorResult(error: MEventoRuntimeError): {
|
|
399
|
+
ok: boolean;
|
|
400
|
+
value: any;
|
|
401
|
+
error: MEventoDiagnostic;
|
|
402
|
+
};
|
|
275
403
|
protected visitRootAST(node: RootAST): any;
|
|
276
404
|
protected visitBlockStatementAST(node: BlockStatementAST): any;
|
|
277
405
|
protected visitIdentifierAST(node: IdentifierAST): any;
|
|
@@ -297,23 +425,54 @@ declare class MEvento extends NodeVisitor {
|
|
|
297
425
|
resolveArguments(args: AST[]): any;
|
|
298
426
|
setFunctionResolver(resolver: (name: string) => MEventoFBinding | undefined): void;
|
|
299
427
|
resolveFunction(name: string): MEventoFBinding | undefined;
|
|
300
|
-
|
|
428
|
+
resolveFunctionSpec(name: string): MEventoFunctionSpec | undefined;
|
|
429
|
+
capabilities(): {
|
|
430
|
+
[name: string]: MEventoFunctionSpec;
|
|
431
|
+
};
|
|
432
|
+
registerFunction(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
|
|
301
433
|
unregisterFunction(id: string): void;
|
|
434
|
+
validate(source: string, functions?: MEventoFunctionList, cache?: boolean): MEventoValidationResult;
|
|
435
|
+
validateManifest(source: string, manifest: MEventoScriptManifest, cache?: boolean): MEventoValidationResult;
|
|
436
|
+
protected validationFunctionSpecs(functions?: MEventoFunctionList): Map<string, MEventoFunctionSpec>;
|
|
437
|
+
protected validateNode(node: AST | null | undefined, knownFunctions: Map<string, MEventoFunctionSpec>, errors: MEventoValidationError[], protectedByTry?: boolean): void;
|
|
438
|
+
protected validateCallExpression(node: CallExpressionAST, knownFunctions: Map<string, MEventoFunctionSpec>, errors: MEventoValidationError[], protectedByTry: boolean): void;
|
|
439
|
+
protected validateStaticArgumentTypes(node: CallExpressionAST, spec: MEventoFunctionSpec, errors: MEventoValidationError[]): void;
|
|
440
|
+
protected staticArgumentType(node: AST): string | undefined;
|
|
441
|
+
protected argumentTypeMatches(spec: MEventoArgSpec, actualType: string): boolean;
|
|
442
|
+
protected validateManifestNode(module: AST, manifest: MEventoScriptManifest, errors: MEventoValidationError[]): void;
|
|
443
|
+
protected analyzeManifestNode(node: AST | null | undefined, analysis: {
|
|
444
|
+
knownInputs: Set<string>;
|
|
445
|
+
assigned: Set<string>;
|
|
446
|
+
assignedTypes: Map<string, string>;
|
|
447
|
+
reportedInputs: Set<string>;
|
|
448
|
+
}, errors: MEventoValidationError[]): void;
|
|
449
|
+
protected markAssignedTarget(node: AST, assignedType: string | undefined, analysis: {
|
|
450
|
+
assigned: Set<string>;
|
|
451
|
+
assignedTypes: Map<string, string>;
|
|
452
|
+
}): void;
|
|
453
|
+
protected valueSpecTypeMatches(spec: MEventoValueSpec, actualType: string): boolean;
|
|
454
|
+
protected validationError(code: string, node: AST, message: string, name?: string, diagnostic?: Pick<MEventoDiagnostic, "argCount" | "minArgs" | "maxArgs" | "argIndex" | "expectedType" | "actualType">): MEventoValidationError;
|
|
455
|
+
protected validateRuntimeArgumentTypes(node: AST, spec: MEventoFunctionSpec, values: unknown[]): void;
|
|
302
456
|
execute(source: string, cache?: boolean, input?: {
|
|
303
457
|
[k: string]: any;
|
|
304
458
|
}): any;
|
|
305
459
|
static compile(source: string, cache?: boolean): AST;
|
|
306
|
-
static register(id: string, fn: MEventoFBinding): void;
|
|
460
|
+
static register(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
|
|
307
461
|
static unregister(id: string): void;
|
|
462
|
+
static capabilities(): {
|
|
463
|
+
[name: string]: MEventoFunctionSpec;
|
|
464
|
+
};
|
|
465
|
+
static validateSource(source: string, functions: MEventoFunctionList, cache?: boolean): MEventoValidationResult;
|
|
466
|
+
static validateManifestSource(source: string, manifest: MEventoScriptManifest, cache?: boolean): MEventoValidationResult;
|
|
308
467
|
static run(source: string, cache?: boolean, input?: {
|
|
309
468
|
[k: string]: any;
|
|
310
|
-
}): any;
|
|
311
|
-
static newInstance(): MEvento;
|
|
469
|
+
}, options?: MEventoOptions): any;
|
|
470
|
+
static newInstance(options?: MEventoOptions): MEvento;
|
|
312
471
|
clone(): MEvento;
|
|
313
472
|
newAsyncInstance(): MEventoAsync;
|
|
314
473
|
}
|
|
315
474
|
declare class MEventoAsync extends MEvento {
|
|
316
|
-
constructor();
|
|
475
|
+
constructor(options?: MEventoOptions);
|
|
317
476
|
protected visitRootAST(node: RootAST): Promise<any>;
|
|
318
477
|
protected visitBlockStatementAST(node: BlockStatementAST): Promise<any>;
|
|
319
478
|
protected visitIdentifierAST(node: AST): Promise<any>;
|
|
@@ -334,16 +493,16 @@ declare class MEventoAsync extends MEvento {
|
|
|
334
493
|
protected visitForOfStatement(node: ForOfStatement): Promise<any[] | ReturnBranch>;
|
|
335
494
|
protected visitReturnAST(node: ReturnAST): Promise<any>;
|
|
336
495
|
resolveArgumentsAsync(args: AST[]): Promise<any[]>;
|
|
337
|
-
registerFunction(id: string, fn: MEventoFBinding): void;
|
|
496
|
+
registerFunction(id: string, fn: MEventoFBinding, spec?: MEventoFunctionSpec): void;
|
|
338
497
|
unregisterFunction(id: string): void;
|
|
339
498
|
execute(source: string, cache?: boolean, input?: {
|
|
340
499
|
[k: string]: any;
|
|
341
500
|
}): Promise<any>;
|
|
342
501
|
static run(source: string, cache?: boolean, input?: {
|
|
343
502
|
[k: string]: any;
|
|
344
|
-
}): Promise<any>;
|
|
345
|
-
static newInstance(): MEventoAsync;
|
|
503
|
+
}, options?: MEventoOptions): Promise<any>;
|
|
504
|
+
static newInstance(options?: MEventoOptions): MEventoAsync;
|
|
346
505
|
clone(): MEventoAsync;
|
|
347
506
|
}
|
|
348
507
|
|
|
349
|
-
export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, MEventoAsync, type MEventoFBinding, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
|
|
508
|
+
export { AST, ArrayExpression, AssignmentExpressionAST, BinaryExpressionAST, BlockStatementAST, BreakAST, BreakBranch, CallExpressionAST, ContinueAST, ContinueBranch, ExpressionStatementAST, ForLoopStatement, ForOfStatement, IdentifierAST, IfStatementAST, IndexAccessorAST, LexerDictionary, LiteralAST, LogicalExpressionAST, LoopControl, MEventScope, MEvento, type MEventoArgSpec, MEventoAsync, type MEventoDiagnostic, type MEventoFBinding, type MEventoFunctionExample, type MEventoFunctionList, type MEventoFunctionSpec, type MEventoOptions, MEventoRuntimeError, type MEventoScriptManifest, type MEventoTraceEvent, type MEventoValidationError, type MEventoValidationResult, type MEventoValueSpec, NodeVisitor, ObjectExpression, ObjectProperty, ReturnAST, ReturnBranch, RootAST, Token, TokenType, TupleExpression, UnaryExpressionAST, WhileLoopStatement };
|