@manifesto-ai/compiler 3.2.0 → 3.3.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.
@@ -1,13 +0,0 @@
1
- var _e={domain:"DOMAIN",state:"STATE",computed:"COMPUTED",action:"ACTION",effect:"EFFECT",when:"WHEN",once:"ONCE",patch:"PATCH",unset:"UNSET",merge:"MERGE",true:"TRUE",false:"FALSE",null:"NULL",as:"AS",available:"AVAILABLE",fail:"FAIL",stop:"STOP",with:"WITH",type:"TYPE",import:"IMPORT",from:"FROM",export:"EXPORT"},Xt=new Set(["function","var","let","const","if","else","for","while","do","switch","case","break","continue","return","throw","try","catch","finally","new","delete","instanceof","void","debugger","this","super","arguments","eval","async","await","yield","class","extends","interface","enum","namespace","module"]);function Ho(t){return t in _e}function ct(t){return Xt.has(t)}function lt(t){return Object.hasOwn(_e,t)?_e[t]:void 0}function $e(t,e,n,o){return{kind:t,lexeme:e,location:n,value:o}}function dt(t,e,n){return{line:t,column:e,offset:n}}function pt(t,e,n){return{start:t,end:e,source:n}}function Qo(t,e){return{start:t,end:t,source:e}}function h(t,e){return{start:t.start.offset<e.start.offset?t.start:e.start,end:t.end.offset>e.end.offset?t.end:e.end,source:t.source??e.source}}var Be=class{source;sourcePath;tokens=[];diagnostics=[];start=0;current=0;line=1;column=1;lineStart=0;constructor(e,n){this.source=e,this.sourcePath=n}tokenize(){for(;!this.isAtEnd();)this.start=this.current,this.scanToken();return this.tokens.push($e("EOF","",this.currentLocation())),{tokens:this.tokens,diagnostics:this.diagnostics}}scanToken(){let e=this.advance();switch(e){case"(":this.addToken("LPAREN");break;case")":this.addToken("RPAREN");break;case"{":this.addToken("LBRACE");break;case"}":this.addToken("RBRACE");break;case"[":this.addToken("LBRACKET");break;case"]":this.addToken("RBRACKET");break;case",":this.addToken("COMMA");break;case";":this.addToken("SEMICOLON");break;case".":this.addToken("DOT");break;case"+":this.addToken("PLUS");break;case"-":this.addToken("MINUS");break;case"*":this.addToken("STAR");break;case"%":this.addToken("PERCENT");break;case":":this.addToken("COLON");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
2
- `:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(e)?this.number():this.isAlpha(e)?this.identifier():this.error(`Unexpected character '${e}'`)}}lineComment(){for(;this.peek()!==`
3
- `&&!this.isAtEnd();)this.advance()}blockComment(){let e=this.line,n=this.column-2;for(;!this.isAtEnd();){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance();return}this.peek()===`
4
- `&&this.newline(),this.advance()}this.error(`Unterminated block comment starting at line ${e}:${n}`)}string(e){let n=this.line,o=this.column-1,i="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
5
- `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let r=this.advance();switch(r){case"n":i+=`
6
- `;break;case"r":i+="\r";break;case"t":i+=" ";break;case"\\":i+="\\";break;case"'":i+="'";break;case'"':i+='"';break;case"0":i+="\0";break;default:this.error(`Invalid escape sequence '\\${r}'`),i+=r}}else i+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${o}`);return}this.advance(),this.addToken("STRING",i)}number(){if(this.source[this.start]==="0"&&(this.peek()==="x"||this.peek()==="X")){for(this.advance();this.isHexDigit(this.peek());)this.advance();let n=this.source.slice(this.start+2,this.current),o=parseInt(n,16);this.addToken("NUMBER",o);return}for(;this.isDigit(this.peek());)this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(this.advance();this.isDigit(this.peek());)this.advance();if(this.peek()==="e"||this.peek()==="E"){if(this.advance(),(this.peek()==="+"||this.peek()==="-")&&this.advance(),!this.isDigit(this.peek())){this.error("Invalid number: expected digits after exponent");return}for(;this.isDigit(this.peek());)this.advance()}let e=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",e)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let e=this.source.slice(this.start,this.current);if(e.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(ct(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=lt(e);n?this.addToken(n):this.addToken("IDENTIFIER")}systemIdentifier(){if(!this.isAlpha(this.peek())){this.error("Expected identifier after '$'"),this.addToken("ERROR");return}for(;this.isAlphaNumeric(this.peek());)this.advance();let e=this.source.slice(this.start,this.current);if(e==="$item"){this.addToken("ITEM");return}if(e==="$system"||e==="$meta"||e==="$input"){for(;this.peek()==="."&&this.isAlpha(this.peekNext());)for(this.advance();this.isAlphaNumeric(this.peek());)this.advance();this.addToken("SYSTEM_IDENT");return}this.error(`Invalid system identifier '${e}'. Expected $system.*, $meta.*, $input.*, or $item`),this.addToken("ERROR")}isAtEnd(){return this.current>=this.source.length}advance(){let e=this.source[this.current];return this.current++,this.column++,e}peek(){return this.isAtEnd()?"\0":this.source[this.current]}peekNext(){return this.current+1>=this.source.length?"\0":this.source[this.current+1]}match(e){return this.isAtEnd()||this.source[this.current]!==e?!1:(this.current++,this.column++,!0)}newline(){this.line++,this.column=1,this.lineStart=this.current}isDigit(e){return e>="0"&&e<="9"}isHexDigit(e){return this.isDigit(e)||e>="a"&&e<="f"||e>="A"&&e<="F"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}currentLocation(){let e=this.positionAt(this.start),n=this.positionAt(this.current);return pt(e,n,this.sourcePath)}positionAt(e){let n=1,o=0;for(let i=0;i<e;i++)this.source[i]===`
7
- `&&(n++,o=i+1);return dt(n,e-o+1,e)}addToken(e,n){let o=this.source.slice(this.start,this.current);this.tokens.push($e(e,o,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let o=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:o,source:this.getSourceLine(o.start.line)})}getSourceLine(e){return this.source.split(`
8
- `)[e-1]??""}};function me(t,e){return new Be(t,e).tokenize()}function ii(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function ri(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var ut=(u=>(u[u.NONE=0]="NONE",u[u.TERNARY=1]="TERNARY",u[u.NULLISH=2]="NULLISH",u[u.OR=3]="OR",u[u.AND=4]="AND",u[u.EQUALITY=5]="EQUALITY",u[u.COMPARISON=6]="COMPARISON",u[u.ADDITIVE=7]="ADDITIVE",u[u.MULTIPLICATIVE=8]="MULTIPLICATIVE",u[u.UNARY=9]="UNARY",u[u.CALL=10]="CALL",u[u.ACCESS=11]="ACCESS",u))(ut||{});function Ue(t){switch(t){case"QUESTION":return 1;case"QUESTION_QUESTION":return 2;case"PIPE_PIPE":return 3;case"AMP_AMP":return 4;case"EQ_EQ":case"BANG_EQ":return 5;case"LT":case"LT_EQ":case"GT":case"GT_EQ":return 6;case"PLUS":case"MINUS":return 7;case"STAR":case"SLASH":case"PERCENT":return 8;default:return 0}}function mt(t){switch(t){case"PLUS":return"+";case"MINUS":return"-";case"STAR":return"*";case"SLASH":return"/";case"PERCENT":return"%";case"EQ_EQ":return"==";case"BANG_EQ":return"!=";case"LT":return"<";case"LT_EQ":return"<=";case"GT":return">";case"GT_EQ":return">=";case"AMP_AMP":return"&&";case"PIPE_PIPE":return"||";case"QUESTION_QUESTION":return"??";default:return null}}function si(t){return Ue(t)!==0}function ci(t){return t==="BANG"||t==="MINUS"}function ht(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var Ge=class{tokens;current=0;diagnostics=[];constructor(e){this.tokens=e}parse(){try{return{program:this.parseProgram(),diagnostics:this.diagnostics}}catch{return{program:null,diagnostics:this.diagnostics}}}parseProgram(){let e=this.peek().location,n=[];for(;this.check("IMPORT");)n.push(this.parseImport());let o=this.parseDomain();return{kind:"program",imports:n,domain:o,location:h(e,o.location)}}parseImport(){let e=this.consume("IMPORT","Expected 'import'").location;this.consume("LBRACE","Expected '{' after 'import'");let n=[];do n.push(this.consume("IDENTIFIER","Expected identifier").lexeme);while(this.match("COMMA"));this.consume("RBRACE","Expected '}' after import names"),this.consume("FROM","Expected 'from' after import names");let o=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:o.value,location:h(e,o.location)}}parseDomain(){let e=this.consume("DOMAIN","Expected 'domain'").location,n=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let o=[];for(;this.check("TYPE")&&!this.isAtEnd();)o.push(this.parseTypeDecl());let i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)if(this.check("TYPE"))o.push(this.parseTypeDecl());else{let a=this.parseDomainMember();a&&i.push(a)}let r=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:n,types:o,members:i,location:h(e,r)}}parseTypeDecl(){let e=this.consume("TYPE","Expected 'type'").location,n=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let o=this.parseTypeExpr();return{kind:"typeDecl",name:n,typeExpr:o,location:h(e,o.location)}}parseDomainMember(){return this.check("STATE")?this.parseState():this.check("COMPUTED")?this.parseComputed():this.check("ACTION")?this.parseAction():this.isFlowDeclContext()?this.parseFlowDecl():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let e=this.consume("STATE","Expected 'state'").location;this.consume("LBRACE","Expected '{' after 'state'");let n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)n.push(this.parseStateField());let o=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,o)}}parseStateField(){let e=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let n=this.parseTypeExpr(),o;return this.match("EQ")&&(o=this.parseExpression()),{kind:"stateField",name:e.lexeme,typeExpr:n,initializer:o,location:h(e.location,o?.location??n.location)}}parseComputed(){let e=this.consume("COMPUTED","Expected 'computed'").location,n=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let o=this.parseExpression();return{kind:"computed",name:n,expression:o,location:h(e,o.location)}}parseAction(){let e=this.consume("ACTION","Expected 'action'").location,n=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseParam());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let i;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),i=this.parseExpression()),this.consume("LBRACE","Expected '{' to start action body");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseGuardedStmt();s&&r.push(s)}let a=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:n,params:o,available:i,body:r,location:h(e,a)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseParam());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&i.push(a)}let r=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:o,body:i,location:h(e.location,r)}}parseParam(){let e=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let n=this.parseTypeExpr();return{kind:"param",name:e.lexeme,typeExpr:n,location:h(e.location,n.location)}}parseGuardedStmt(){if(this.check("WHEN"))return this.parseWhenStmt();if(this.check("ONCE"))return this.parseOnceStmt();if(this.isOnceIntentContext())return this.parseOnceIntentStmt();if(this.isIncludeContext())return this.parseIncludeStmt();if(this.check("FAIL"))return this.parseFailStmt();if(this.check("STOP"))return this.parseStopStmt();let e=this.peek();return e.kind==="PATCH"||e.lexeme==="patch"||e.kind==="EFFECT"||e.lexeme==="effect"?(this.error(`'${e.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${e.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${e.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){return this.check("WHEN")?this.parseWhenStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'when', 'include', 'once', 'onceIntent', 'patch', or 'effect'.`),this.advance(),null)}skipToRecoveryPoint(){let e=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){e++,this.advance();continue}if(n.kind==="RBRACE"){if(e===0)return;e--,this.advance();continue}if(e===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let e=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseInnerStmt();r&&o.push(r)}let i=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:o,location:h(e,i)}}parseOnceStmt(){let e=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let o;this.match("WHEN")&&(o=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&i.push(a)}let r=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:o,body:i,location:h(e,r)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.parseInnerStmt();r&&o.push(r)}let i=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:o,location:h(e.location,i)}}parseInnerStmt(){return this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():this.check("WHEN")?this.parseWhenStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("FAIL")?this.parseFailStmt():this.check("STOP")?this.parseStopStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'patch', 'effect', 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseIncludeStmt(){let e=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseExpression());while(this.match("COMMA"));let i=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:o,location:h(e.location,i)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),o,i,r;return this.match("UNSET")?(o="unset",r=this.previous().location):this.match("MERGE")?(o="merge",i=this.parseExpression(),r=i.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),o="set",i=this.parseExpression(),r=i.location),{kind:"patch",path:n,op:o,value:i,location:h(e,r)}}parseEffectStmt(){let e=this.consume("EFFECT","Expected 'effect'").location,n=this.consume("IDENTIFIER","Expected effect type").lexeme;for(;this.match("DOT");)n+="."+this.consume("IDENTIFIER","Expected identifier after '.'").lexeme;this.consume("LPAREN","Expected '(' after effect type"),this.consume("LBRACE","Expected '{' for effect arguments");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)o.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let i=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:o,location:h(e,i)}}parseEffectArg(){let e=this.match("IDENTIFIER","FAIL")?this.previous():this.consume("IDENTIFIER","Expected argument name");this.consume("COLON","Expected ':' after argument name");let n=["into","pass","fail"].includes(e.lexeme),o=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:o,isPath:n,location:h(e.location,o.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),o=n.value,i,r=n.location;return this.match("WITH")&&(i=this.parseExpression(),r=i.location),{kind:"fail",code:o,message:i,location:h(e,r)}}parseStopStmt(){let e=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:h(e,n.location)}}parseTypeExpr(){let e=this.parseBaseType();if(this.check("PIPE")){let n=[e];for(;this.match("PIPE");)n.push(this.parseBaseType());e={kind:"unionType",types:n,location:h(n[0].location,n[n.length-1].location)}}return e}parseBaseType(){if(this.check("LBRACE"))return this.parseObjectType();if(this.check("STRING")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("NUMBER")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("TRUE")||this.check("FALSE")){let n=this.advance();return{kind:"literalType",value:n.kind==="TRUE",location:n.location}}if(this.check("NULL"))return{kind:"literalType",value:null,location:this.advance().location};let e=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(e.lexeme==="Array"){let n=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,o)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let o=this.parseTypeExpr(),i=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:o,location:h(e.location,i)}}else{for(this.error(`Unknown generic type '${e.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:e.lexeme,location:e.location}}parseObjectType(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.consume("IDENTIFIER","Expected field name"),r=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let a=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,typeExpr:a,optional:r,location:h(i.location,a.location)}),this.match("COMMA")}let o=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,o)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let o=Ue(this.peek().kind);if(o<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let i=mt(this.peek().kind);if(!i)break;this.advance();let r=ht(this.previous().kind)?o-1:o,a=this.parseExpression(r);n={kind:"binary",operator:i,left:n,right:a,location:h(n.location,a.location)}}return n}parseTernary(e){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let o=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:o,location:h(e.location,o.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let e=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:e.kind==="BANG"?"!":"-",operand:n,location:h(e.location,n.location)}}if(this.match("LPAREN")){let e=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),e}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"number",location:e.location}}if(this.check("STRING")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"string",location:e.location}}if(this.check("TRUE")||this.check("FALSE")){let e=this.advance();return{kind:"literal",value:e.kind==="TRUE",literalType:"boolean",location:e.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let e=this.advance(),n=e.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:e.location})}if(this.check("ITEM")){let e=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:e.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let e=this.advance();return this.parseFunctionCall(e)}if(this.check("IDENTIFIER")){let e=this.advance();return this.check("LPAREN")?this.parseFunctionCall(e):this.parsePostfix({kind:"identifier",name:e.lexeme,location:e.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(e){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,o)})}parsePostfix(e){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"propertyAccess",object:e,property:n.lexeme,location:h(e.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),o=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,o)}}else break;return e}parseObjectLiteral(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let r=this.parseExpression();n.push({kind:"objectProperty",key:i.lexeme,value:r,location:h(i.location,r.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let o=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,o)}}parseArrayLiteral(){let e=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();)n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements");let o=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,o)}}parsePath(){let e=[],n=this.peek().location,o=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:o.lexeme,location:o.location});;)if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:r.lexeme,location:r.location})}else if(this.match("LBRACKET")){let r=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:r,location:h(r.location,a)})}else break;let i=e[e.length-1];return{kind:"path",segments:e,location:h(n,i.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","EQ_EQ","BANG_EQ","LT","LT_EQ","GT","GT_EQ","AMP_AMP","PIPE_PIPE","BANG","QUESTION","QUESTION_QUESTION"].includes(e.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(e){return this.current+e>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+e]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.isAtEnd()?!1:this.peek().kind===e}isOnceIntentContext(){if(!this.check("IDENTIFIER")||this.peek().lexeme!=="onceIntent")return!1;let n=this.peekNext();return n.kind==="LBRACE"||n.kind==="WHEN"}isFlowDeclContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="flow"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}isIncludeContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="include"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}match(...e){for(let n of e)if(this.check(n))return this.advance(),!0;return!1}consume(e,n){if(this.check(e))return this.advance();throw this.errorAtCurrent(n)}error(e){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.previous().location})}errorAtCurrent(e){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.peek().location}),new Error(e)}};function he(t){return new Ge(t).parse()}var fe=class{parent;symbols=new Map;kind;constructor(e,n=null){this.kind=e,this.parent=n}define(e){this.symbols.set(e.name,e)}lookup(e){let n=this.symbols.get(e);return n||this.parent?.lookup(e)}isDefined(e){return this.symbols.has(e)}},qe=class{diagnostics=[];scopes=new Map;currentScope=null;domainScope=null;analyze(e){return this.diagnostics=[],this.scopes=new Map,this.currentScope=null,this.domainScope=null,this.analyzeDomain(e.domain),{scopes:this.scopes,diagnostics:this.diagnostics}}analyzeDomain(e){let n=new fe("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let o of e.members)if(o.kind==="state")for(let i of o.fields)this.defineSymbol({name:i.name,kind:"state",location:i.location});else o.kind==="computed"?this.defineSymbol({name:o.name,kind:"computed",location:o.location}):o.kind==="action"?this.defineSymbol({name:o.name,kind:"action",location:o.location}):o.kind;for(let o of e.members)o.kind==="computed"?this.analyzeComputedExpr(o):o.kind==="action"&&this.analyzeAction(o)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new fe("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let o of e.params)n.define({name:o.name,kind:"param",location:o.location});for(let o of e.body)this.analyzeStmt(o);this.currentScope=this.domainScope}analyzeStmt(e){switch(e.kind){case"when":this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"onceIntent":e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"once":this.validatePath(e.marker),e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"patch":this.validatePath(e.path),e.value&&this.analyzeExpr(e.value,"action");break;case"effect":for(let n of e.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(e,n){switch(e.kind){case"identifier":this.checkIdentifier(e.name,e.location,n);break;case"systemIdent":this.checkSystemIdent(e.path,e.location,n);break;case"propertyAccess":this.analyzeExpr(e.object,n);break;case"indexAccess":this.analyzeExpr(e.object,n),this.analyzeExpr(e.index,n);break;case"functionCall":for(let o of e.args)this.analyzeExpr(o,n);break;case"binary":this.analyzeExpr(e.left,n),this.analyzeExpr(e.right,n);break;case"unary":this.analyzeExpr(e.operand,n);break;case"ternary":this.analyzeExpr(e.condition,n),this.analyzeExpr(e.consequent,n),this.analyzeExpr(e.alternate,n);break;case"objectLiteral":for(let o of e.properties)this.analyzeExpr(o.value,n);break;case"arrayLiteral":for(let o of e.elements)this.analyzeExpr(o,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,o){let i=this.currentScope?.lookup(e);if(!i){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}o==="computed"&&i.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,o){let[i,...r]=e;if(i==="system"&&o==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),i==="system"){let a=["uuid","timestamp","time.now","random"],s=r.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(i==="meta"){let a=["intentId","actionName","timestamp"],s=r.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(e){if(!e||!e.segments)return;let n=e.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,e.location,"E_UNDEFINED"))}defineSymbol(e){if(this.currentScope){if(this.currentScope.isDefined(e.name)){this.error(`Duplicate identifier '${e.name}'`,e.location,"E_DUPLICATE");return}this.currentScope.define(e)}}error(e,n,o){this.diagnostics.push({severity:"error",code:o,message:e,location:n})}};function ft(t){return new qe().analyze(t)}function ye(t,e,n,o){return{severity:"error",code:t,message:e,location:n,...o}}function yt(t,e,n,o){return{severity:"warning",code:t,message:e,location:n,...o}}function Ei(t,e,n){return{severity:"info",code:t,message:e,location:n}}function Jt(t){return t.severity==="error"}function Ni(t){return t.some(Jt)}function ki(t,e){return t.filter(n=>n.severity===e)}var gt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),Et=new Set(["add","sub","mul","div","mod","abs","floor","ceil","round","sqrt","pow","len","strlen","indexOf","sum","min","max","toNumber"]),Nt=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),Zt=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),en=new Set(["updateById","removeById"]);function ge(t){let e=new Map,n=new Map,o=new Map;for(let i of t.types)o.set(i.name,i);for(let i of t.members){if(i.kind==="state"){for(let r of i.fields)e.set(r.name,r.typeExpr);continue}i.kind==="computed"&&n.set(i.name,i)}return{stateTypes:e,computedDecls:n,typeDefs:o,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ee(t){let e=new Map;for(let n of t)e.set(n.name,n.typeExpr);return e}function g(t,e,n){switch(t.kind){case"literal":return an(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??tn(t.name,n);case"propertyAccess":return K(g(t.object,e,n),t.property,n);case"indexAccess":return ie(g(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let i=g(o.value,e,n);return i?{kind:"typeField",name:o.key,typeExpr:i,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{let o=j(t.elements.map(i=>g(i,e,n)),t.location);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"unary":return nn(t);case"binary":return on(t,e,n);case"ternary":return j([g(t.consequent,e,n),g(t.alternate,e,n)],t.location);case"functionCall":return rn(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function L(t,e,n){let o=g(t,e,n);if(o)return kt(o,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?oe([L(t.left,e,n),L(t.right,e,n)]):t.operator==="=="||t.operator==="!="||t.operator==="+"||t.operator==="-"||t.operator==="*"||t.operator==="/"||t.operator==="%"||t.operator==="<"||t.operator==="<="||t.operator===">"||t.operator===">="||t.operator==="&&"||t.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return oe([L(t.consequent,e,n),L(t.alternate,e,n)]);case"functionCall":return Zt.has(t.name)?"nonprimitive":gt.has(t.name)||Et.has(t.name)||Nt.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?oe([L(t.args[1],e,n),L(t.args[2],e,n)]):t.name==="coalesce"?oe(t.args.map(i=>L(i,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function kt(t,e){let n=w(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name==="object"?"nonprimitive":n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?"primitive":"unknown";case"literalType":return"primitive";case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":return oe(n.types.map(o=>kt(o,e)))}}function w(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),w(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function K(t,e,n){let o=w(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(r=>r.name===e)?.typeExpr??null;if(o.kind==="unionType"){let i=o.types.filter(r=>!H(r)).map(r=>K(r,e,n)).filter(r=>r!==null);return j(i,o.location)}return null}function ie(t,e){let n=w(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let o=n.types.filter(i=>!H(i)).map(i=>ie(i,e)).filter(i=>i!==null);return j(o,n.location)}return null}function O(t,e){let n=w(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let o=n.types.filter(i=>!H(i)).map(i=>O(i,e)).filter(i=>i!==null);return j(o,n.location)}return null}function Ne(t,e){let n=w(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number";case"literalType":return typeof n.value=="string"||typeof n.value=="number";case"unionType":return n.types.length>0&&n.types.every(o=>Ne(o,e));default:return!1}}function H(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function tn(t,e){if(e.computedTypeCache.has(t))return e.computedTypeCache.get(t)??null;let n=e.computedDecls.get(t);if(!n||e.computedTypeInFlight.has(t))return null;e.computedTypeInFlight.add(t);let o=g(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,o),o}function nn(t){return t.operator==="!"?M("boolean",t.location):M("number",t.location)}function on(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return M("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return M("number",t.location);case"??":return j([g(t.left,e,n),g(t.right,e,n)],t.location)}}function rn(t,e,n){if(gt.has(t.name))return M("boolean",t.location);if(Et.has(t.name))return M("number",t.location);if(Nt.has(t.name))return M("string",t.location);if(t.name==="toBoolean")return M("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let o=O(g(t.args[0],e,n),n);return o?j([o,M("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let o=O(g(t.args[0],e,n),n);return o?j([o,M("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return g(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let o=g(t.args[0],e,n),i=O(o,n);if(!i)return null;let r=g(t.args[1],cn(e,i),n);return r?{kind:"arrayType",elementType:r,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return O(g(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return ie(g(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let o=sn(t.args[1]);return o?K(g(t.args[0],e,n),o,n):null}return en.has(t.name)&&t.args.length>=1?g(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?j([g(t.args[1],e,n),g(t.args[2],e,n)],t.location):t.name==="coalesce"?j(t.args.map(o=>g(o,e,n)),t.location):t.name==="slice"&&t.args.length>=1?g(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:M("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:M("string",t.location),location:t.location}:null}function oe(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function j(t,e){let n=t.filter(r=>r!==null);if(n.length===0)return null;if(n.length===1)return n[0];let o=[],i=new Set;for(let r of n){let a=JSON.stringify(r);i.has(a)||(i.add(a),o.push(r))}return o.length===1?o[0]:{kind:"unionType",types:o,location:e}}function an(t,e){return{kind:"literalType",value:t,location:e}}function M(t,e){return{kind:"simpleType",name:t,location:e}}function sn(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function cn(t,e){let n=new Map(t);return n.set("$item",e),n}var ln=new Set(["findById","existsById"]),Ve=new Set(["updateById","removeById"]),dn=new Set([...ln,...Ve]);function G(t,e,n,o,i){let r=`${n}:${i.start.offset}:${i.end.offset}:${o}`;e.has(r)||(e.add(r),t.push(ye(n,o,i)))}function Tt(t){let e=[],n=new Set,o=ge(t.domain);hn(t.domain,o,e,n);for(let i of t.domain.members)switch(i.kind){case"computed":k(i.expression,"computed",new Map,o,e,n,0);break;case"action":{let r=Ee(i.params);pn(i,r,o,e,n);break}case"state":case"flow":break}return e}function pn(t,e,n,o,i){t.available&&k(t.available,"available",e,n,o,i,0);for(let r of t.body)un(r,e,n,o,i)}function un(t,e,n,o,i){switch(t.kind){case"when":k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"once":t.condition&&k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"onceIntent":t.condition&&k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"include":break}}function W(t,e,n,o,i){switch(t.kind){case"when":k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"once":t.condition&&k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"onceIntent":t.condition&&k(t.condition,"guard",e,n,o,i,0);for(let r of t.body)W(r,e,n,o,i);break;case"patch":t.value&&k(t.value,"patch",e,n,o,i,0);break;case"effect":for(let r of t.args)r.isPath||k(r.value,"action",e,n,o,i,0);break;case"fail":t.message&&k(t.message,"action",e,n,o,i,0);break;case"include":case"stop":break}}function k(t,e,n,o,i,r,a){switch(t.kind){case"functionCall":{mn(t,e,n,o,i,r,a);let s=a+(Ve.has(t.name)?1:0);for(let c of t.args)k(c,e,n,o,i,r,s);break}case"binary":k(t.left,e,n,o,i,r,a),k(t.right,e,n,o,i,r,a);break;case"unary":k(t.operand,e,n,o,i,r,a);break;case"ternary":k(t.condition,e,n,o,i,r,a),k(t.consequent,e,n,o,i,r,a),k(t.alternate,e,n,o,i,r,a);break;case"propertyAccess":k(t.object,e,n,o,i,r,a);break;case"indexAccess":k(t.object,e,n,o,i,r,a),k(t.index,e,n,o,i,r,a);break;case"objectLiteral":for(let s of t.properties)k(s.value,e,n,o,i,r,a);break;case"arrayLiteral":for(let s of t.elements)k(s,e,n,o,i,r,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function mn(t,e,n,o,i,r,a){if(!dn.has(t.name)||t.args.length===0)return;Ve.has(t.name)&&(e==="available"?G(i,r,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="guard"?G(i,r,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&G(i,r,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&G(i,r,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!ze(t.args[0],o)&&G(i,r,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=yn(t.args[0],n,o);if(!s)return;let c=St(s,o);if(!c){G(i,r,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}Ne(c,o)||G(i,r,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function hn(t,e,n,o){for(let i of t.members)if(i.kind==="state")for(let r of i.fields)fn(r,e,n,o)}function fn(t,e,n,o){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let i=O(t.typeExpr,e);if(!i)return;let r=St(i,e);if(!r||!Ne(r,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(m=>m.key==="id");if(!c||c.value.kind!=="literal"||typeof c.value.value!="string"&&typeof c.value.value!="number")continue;let l=`${typeof c.value.value}:${String(c.value.value)}`;if(a.get(l)){G(n,o,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function yn(t,e,n){return O(g(t,e,n),n)}function St(t,e){return K(t,"id",e)}function ze(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return ze(t.object,e);case"indexAccess":return ze(t.object,e);default:return!1}}function xt(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var gn=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function E(t,e){return{kind:"simpleType",name:t,location:e}}function $(t,e,n){let o=w(t,n),i=w(e,n);if(!o||!i)return null;if(i.kind==="unionType"){let r=o.kind==="unionType"?o.types:[o],a=!1;for(let s of r){let c=i.types.map(l=>$(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(o.kind==="unionType"){let r=!1;for(let a of o.types){let s=$(a,i,n);if(s===!1)return!1;s===null&&(r=!0)}return r?null:!0}if(i.kind==="simpleType"){if(o.kind==="simpleType")return o.name===i.name;if(o.kind==="literalType")return i.name==="null"?o.value===null:typeof o.value===i.name}if(i.kind==="literalType")return o.kind!=="literalType"?!1:o.value===i.value;if(i.kind==="arrayType")return o.kind!=="arrayType"?!1:$(o.elementType,i.elementType,n);if(i.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let r of i.fields){let a=o.fields.find(c=>c.name===r.name);if(!a){if(r.optional)continue;return!1}let s=$(a.typeExpr,r.typeExpr,n);if(s!==!0)return s}return!0}return i.kind==="recordType"?o.kind!=="recordType"?null:$(o.valueType,i.valueType,n):null}function C(t,e){let n=w(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name;case"literalType":return JSON.stringify(n.value);case"arrayType":return`Array<${C(n.elementType,e)}>`;case"recordType":return`Record<${C(n.keyType,e)}, ${C(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(o=>`${o.name}${o.optional?"?":""}: ${C(o.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(o=>C(o,e)).join(" | ")}}function Ke(t,e){let n=w(t,e);if(!n)return null;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?new Set([n.name]):n.name==="object"?"nonprimitive":null;case"literalType":return new Set([n.value===null?"null":typeof n.value]);case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":{let o=new Set;for(let i of n.types){let r=Ke(i,e);if(r===null)return null;if(r==="nonprimitive")return"nonprimitive";for(let a of r)o.add(a)}return o}}}function bt(t,e,n){let o=Ke(t,n),i=Ke(e,n);if(o===null||i===null)return null;if(o==="nonprimitive"||i==="nonprimitive")return!1;if(!(o instanceof Set)||!(i instanceof Set))return null;let r=[...o].filter(s=>s!=="null"),a=[...i].filter(s=>s!=="null");return r.length===0||a.length===0?!0:r.some(s=>a.includes(s))}function En(t,e){let n=w(t,e);if(!n||H(n))return null;if(n.kind!=="unionType")return n;let o=n.types.filter(i=>!H(i));return o.length===0?null:o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function Nn(t,e,n){if(!t||!e)return null;let o=$(t,e,n);if(o===!0)return!0;let i=$(e,t,n);if(i===!0)return!0;let r=bt(t,e,n);return r!==null?r:o===!1&&i===!1?!1:null}function vt(t,e){let n=w(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(i=>vt(i,e));return o.every(i=>i===!0)?!0:o.some(i=>i===!1)?!1:null}return n.kind==="arrayType"}function wt(t,e){let n=w(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(i=>wt(i,e));return o.every(i=>i===!0)?!0:o.some(i=>i===!1)?!1:null}return n.kind==="arrayType"||n.kind==="recordType"||n.kind==="objectType"?!0:n.kind==="literalType"?typeof n.value=="string":n.kind==="simpleType"?n.name==="string"||n.name==="object":!1}function kn(t,e){let n=new Map(t);return n.set("$item",e),n}function Tn(t,e){let[n,...o]=t.segments;if(!n||n.kind!=="propertySegment")return null;let i=e.stateTypes.get(n.name)??null;for(let r of o){if(!i)return null;i=r.kind==="propertySegment"?K(i,r.name,e):ie(i,e)}return i}function Sn(t){let e="";for(let[n,o]of t.segments.entries()){if(o.kind==="propertySegment"){e+=n===0?o.name:`.${o.name}`;continue}o.index.kind==="literal"?e+=`[${JSON.stringify(o.index.value)}]`:e+="[*]"}return e}var He=class{ctx=xt();symbols=null;validate(e){return this.ctx=xt(),this.symbols=ge(e.domain),this.validateDomain(e.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(e){e.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",e.location,"E_RESERVED_NAME");for(let n of e.members)switch(n.kind){case"state":this.validateState(n);break;case"computed":this.validateExpr(n.expression,"computed");break;case"action":this.validateAction(n);break;case"flow":break}}validateState(e){let n=new Map;for(let o of e.fields){let i=n.get(o.name);i?this.error(`Duplicate state field '${o.name}'. First declared at line ${i.start.line}`,o.location,"E_DUPLICATE_FIELD"):n.set(o.name,o.location),this.validateStateField(o)}}validateStateField(e){this.checkAnonymousObjectType(e.typeExpr,e.location),e.initializer&&this.validateStateInitializer(e.initializer)}validateStateInitializer(e){switch(e.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",e.location,"E042");return;case"systemIdent":e.path[0]==="system"?this.error("$system.* cannot be used in state initializers",e.location,"E002"):this.error("State initializers must be compile-time constants",e.location,"E042");return;case"objectLiteral":for(let n of e.properties)this.validateStateInitializer(n.value);return;case"arrayLiteral":for(let n of e.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let o of e.args)this.validateStateInitializer(o);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.left),this.validateStateInitializer(e.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.condition),this.validateStateInitializer(e.consequent),this.validateStateInitializer(e.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.validateStateInitializer(e.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}}}checkAnonymousObjectType(e,n){switch(e.kind){case"objectType":this.ctx.diagnostics.push(yt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",e.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let o of e.fields)this.checkAnonymousObjectType(o.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(e.elementType,n);break;case"recordType":this.checkAnonymousObjectType(e.keyType,n),this.checkAnonymousObjectType(e.valueType,n);break;case"unionType":for(let o of e.types)this.checkAnonymousObjectType(o,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ee(e.params),e.available&&this.validateAvailableExpr(e.available);for(let n of e.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(e){switch(e.kind){case"identifier":this.ctx.currentActionParamTypes.has(e.name)&&this.error("Action parameters cannot be used in available condition",e.location,"E005");break;case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",e.location,"E005"),e.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",e.location,"E005"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",e.location,"E005");break;case"functionCall":for(let n of e.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(e.left),this.validateAvailableExpr(e.right);break;case"unary":this.validateAvailableExpr(e.operand);break;case"ternary":this.validateAvailableExpr(e.condition),this.validateAvailableExpr(e.consequent),this.validateAvailableExpr(e.alternate);break;case"propertyAccess":this.validateAvailableExpr(e.object);break;case"indexAccess":this.validateAvailableExpr(e.object),this.validateAvailableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateAvailableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateAvailableExpr(n);break}}validateGuardedStmt(e){switch(e.kind){case"when":this.validateWhen(e);break;case"once":this.validateOnce(e);break;case"onceIntent":this.validateOnceIntent(e);break;case"patch":this.validatePatch(e);break;case"effect":this.validateEffect(e);break;case"include":break;case"fail":this.validateFail(e);break;case"stop":this.validateStop(e);break}}validateWhen(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(e.condition,"when");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,e.condition&&this.validateCondition(e.condition,"once");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,e.condition&&this.validateCondition(e.condition,"onceIntent");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(e){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_PATCH"),e.value){let n=this.ctx.diagnostics.length,o=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let i=Tn(e.path,this.symbols);if(!i||!o)return;$(o,i,this.symbols)===!1&&this.error(`Patch value for '${Sn(e.path)}' must be assignable to ${C(i,this.symbols)}, got ${C(o,this.symbols)}`,e.value.location,"E_TYPE_MISMATCH")}}validateEffect(e){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_EFFECT");for(let n of e.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(e){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",e.location,"E006"),e.message&&this.validateExpr(e.message,"action")}validateStop(e){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",e.location,"E007"),gn.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let o=this.ctx.diagnostics.length,i=this.validateExpr(e,"action");o===this.ctx.diagnostics.length&&this.requireAssignable(i,E("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,o=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,o),this.inferType(e,o);case"binary":{let i=this.ctx.diagnostics.length,r=this.validateExpr(e.left,n,o),a=this.validateExpr(e.right,n,o);if(!(i!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,r,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(r,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(r,E("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,E("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(r,E("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,E("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([r,a],e.location);break}return this.inferType(e,o)}case"unary":{let i=this.ctx.diagnostics.length,r=this.validateExpr(e.operand,n,o);return i===this.ctx.diagnostics.length&&this.requireAssignable(r,E(e.operator==="!"?"boolean":"number",e.operand.location),e.operand.location,e.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(e,o)}case"ternary":{let i=this.ctx.diagnostics.length,r=this.validateExpr(e.condition,n,o);return this.validateExpr(e.consequent,n,o),this.validateExpr(e.alternate,n,o),i===this.ctx.diagnostics.length&&this.requireAssignable(r,E("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,o)}case"propertyAccess":return this.validateExpr(e.object,n,o),this.inferType(e,o);case"indexAccess":return this.validateExpr(e.object,n,o),this.validateExpr(e.index,n,o),this.inferType(e,o);case"objectLiteral":for(let i of e.properties)this.validateExpr(i.value,n,o);return this.inferType(e,o);case"arrayLiteral":for(let i of e.elements)this.validateExpr(i,n,o);return this.inferType(e,o);case"systemIdent":return this.inferType(e,o);case"literal":case"identifier":case"iterationVar":return this.inferType(e,o)}}validateFunctionCall(e,n,o){let{name:i,args:r,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(i)&&this.error(`Function '${i}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(i)&&r.length===1){n==="action"&&this.error(`Primitive aggregation '${i}()' can only be used in computed expressions, not in actions`,a,"E009");let c=r[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${i}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(i){case"eq":case"neq":break;case"len":case"sum":r.length!==1&&this.error(`Function '${i}' expects 1 argument, got ${r.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"gt":case"gte":case"lt":case"lte":r.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"not":case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":case"isNull":case"isNotNull":case"trim":case"lower":case"upper":case"strlen":case"keys":case"values":case"entries":case"first":case"last":case"typeof":case"toString":case"toNumber":case"toBoolean":case"reverse":case"unique":case"flat":case"fromEntries":r.length!==1&&this.error(`Function '${i}' expects 1 argument, got ${r.length}`,a,"E_ARG_COUNT");break;case"pow":case"findById":case"existsById":case"filter":case"map":case"find":case"every":case"some":case"at":case"includes":case"field":case"hasKey":case"pick":case"omit":case"startsWith":case"endsWith":case"strIncludes":case"indexOf":r.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"updateById":r.length!==3&&this.error(`Function '${i}' expects 3 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"removeById":r.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(r.length<2||r.length>3)&&this.error(`Function '${i}' expects 2-3 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"split":r.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":r.length<1&&this.error(`Function '${i}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"if":case"cond":r.length!==3&&this.error(`Function '${i}' expects 3 arguments, got ${r.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${i}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(i)&&r.length>0){let c=this.validateExpr(r[0],n,o);s.push(c);let l=o;if(this.symbols){let d=O(c,this.symbols);d&&(l=kn(o,d))}for(let d=1;d<r.length;d+=1)s.push(this.validateExpr(r[d],n,d===1?l:o))}else for(let c of r)s.push(this.validateExpr(c,n,o));if(this.symbols)switch(i){case"eq":case"neq":r.length===2&&this.validatePrimitiveEquality(r[0],r[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"pow":r.length===2&&(this.requireAssignable(s[0],E("number",r[0].location),r[0].location,`Function '${i}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",r[1].location),r[1].location,`Function '${i}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":r.length===2&&(this.requireAssignable(s[0],E("number",r[0].location),r[0].location,`Function '${i}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",r[1].location),r[1].location,`Function '${i}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of r.entries())this.requireAssignable(s[c],E("boolean",l.location),l.location,`Function '${i}' expects boolean arguments`);break;case"not":r.length===1&&this.requireAssignable(s[0],E("boolean",r[0].location),r[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":r.length===1&&this.requireAssignable(s[0],E("number",r[0].location),r[0].location,`Function '${i}' expects a numeric argument`);break;case"trim":case"lower":case"upper":case"strlen":r.length===1&&this.requireAssignable(s[0],E("string",r[0].location),r[0].location,`Function '${i}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":r.length===2&&(this.requireAssignable(s[0],E("string",r[0].location),r[0].location,`Function '${i}' expects a string first argument`),this.requireAssignable(s[1],E("string",r[1].location),r[1].location,`Function '${i}' expects a string second argument`));break;case"replace":r.length>=2&&(this.requireAssignable(s[0],E("string",r[0].location),r[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],E("string",r[1].location),r[1].location,"Function 'replace' expects a string second argument")),r.length===3&&this.requireAssignable(s[2],E("string",r[2].location),r[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":r.length>=2&&(this.requireAssignable(s[0],E("string",r[0].location),r[0].location,`Function '${i}' expects a string first argument`),this.requireAssignable(s[1],E("number",r[1].location),r[1].location,`Function '${i}' expects a numeric second argument`)),r.length===3&&this.requireAssignable(s[2],E("number",r[2].location),r[2].location,`Function '${i}' expects a numeric third argument`);break;case"len":r.length===1&&this.requireLenCompatible(s[0],r[0].location);break;case"filter":case"find":case"every":case"some":r.length===2&&(this.requireArrayCompatible(s[0],r[0].location,i),this.requireAssignable(s[1],E("boolean",r[1].location),r[1].location,`Function '${i}' requires a boolean-valued callback`));break;case"map":r.length===2&&this.requireArrayCompatible(s[0],r[0].location,i);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"if":case"cond":r.length===3&&this.requireAssignable(s[0],E("boolean",r[0].location),r[0].location,`Function '${i}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,o,i,r){if(!this.symbols)return;if(e.kind==="objectLiteral"||e.kind==="arrayLiteral"||n.kind==="objectLiteral"||n.kind==="arrayLiteral"){this.error("eq/neq operands must be compatible primitive types, not object or array literals",r,"E_TYPE_MISMATCH");return}bt(o,i,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${C(o,this.symbols)} and ${C(i,this.symbols)}`,r,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?g(e,n,this.symbols):null}requireAssignable(e,n,o,i){if(!this.symbols||!e)return;$(e,n,this.symbols)===!1&&this.error(`${i}, got ${C(e,this.symbols)}`,o,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,o){if(!this.symbols||!e)return;vt(e,this.symbols)===!1&&this.error(`Function '${o}' expects an array first argument, got ${C(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;wt(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${C(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let o=e.map(i=>En(i,this.symbols)).filter(i=>i!==null);for(let i=0;i<o.length;i+=1)for(let r=i+1;r<o.length;r+=1)if(Nn(o[i],o[r],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${C(o[i],this.symbols)} and ${C(o[r],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}error(e,n,o){this.ctx.diagnostics.push({severity:"error",code:o,message:e,location:n})}warn(e,n,o){this.ctx.diagnostics.push({severity:"warning",code:o,message:e,location:n})}};function Ct(t){let n=new He().validate(t),o=Tt(t),i=[...n.diagnostics,...o];return{valid:!i.some(r=>r.severity==="error"),diagnostics:i}}var We={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},Qe={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},Ye={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},xn={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var D=class extends Error{code;path;details;constructor(e,n,o){super(n),this.name="LoweringError",this.code=e,this.path=o?.path,this.details=o?.details}};function ke(t,e,n){return new D("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function N(t,e){return new D("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function Te(t,e){return new D("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function Xe(t,e){return new D("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function bn(t,e){return new D("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function Je(t,e){return new D("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function vn(t,e){let n=Array.from(t),o=Array.from(e),i=Math.min(n.length,o.length);for(let r=0;r<i;r+=1){let a=n[r].codePointAt(0)??0,s=o[r].codePointAt(0)??0;if(a!==s)return a-s}return n.length-o.length}function At(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let o=vn(e.item.key,n.item.key);return o!==0?o:e.index-n.index}).map(({item:e})=>e)}function p(t,e){switch(t.kind){case"lit":return wn(t);case"var":return Cn(t,e);case"sys":return An(t,e);case"get":return Pn(t,e);case"field":return Pt(t,e);case"call":return In(t,e);case"obj":return Mn(t,e);case"arr":return Rn(t,e);default:throw Je(t.kind)}}function wn(t){return{kind:"lit",value:t.value}}function Cn(t,e){if(!e.allowItem)throw ke("var",e.mode);return{kind:"get",path:"$item"}}function An(t,e){if(t.path.length===0)throw Te(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw Te(t.path);return{kind:"get",path:t.path.join(".")}}function Pn(t,e){let n=t.path.map(o=>o.name).join(".");if(t.base===void 0)return{kind:"get",path:n};if(t.base.kind==="var"&&t.base.name==="item"){if(!e.allowItem)throw ke("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw Xe(t.base.kind)}function Pt(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(o=>o.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:p(t.object,e),property:t.property}}function In(t,e){let{fn:n,args:o}=t;if(Dn(n)){if(o.length!==2)throw N(n);let[i,r]=o;return{kind:n,left:p(i,e),right:p(r,e)}}if(n==="isNotNull"){if(o.length!==1)throw N(n);return{kind:"not",arg:{kind:"isNull",arg:p(o[0],e)}}}if(It(n)){if(o.length!==1)throw N(n);return{kind:Fn(n),arg:p(o[0],e)}}if(n==="trim"){if(o.length!==1)throw N(n);return{kind:"trim",str:p(o[0],e)}}if(n==="lower"||n==="toLowerCase"){if(o.length!==1)throw N(n);return{kind:"toLowerCase",str:p(o[0],e)}}if(n==="upper"||n==="toUpperCase"){if(o.length!==1)throw N(n);return{kind:"toUpperCase",str:p(o[0],e)}}if(n==="strlen"||n==="strLen"){if(o.length!==1)throw N(n);return{kind:"strLen",str:p(o[0],e)}}if(Ln(n))return o.length===1?{kind:n==="min"?"minArray":"maxArray",array:p(o[0],e)}:{kind:n,args:o.map(i=>p(i,e))};if(n==="sum"){if(o.length!==1)throw N(n);return{kind:"sumArray",array:p(o[0],e)}}if(n==="pow"){if(o.length!==2)throw N(n);return{kind:"pow",base:p(o[0],e),exponent:p(o[1],e)}}if(On(n))return{kind:n,args:o.map(i=>p(i,e))};if(n==="if"||n==="cond"){if(o.length!==3)throw N(n);return{kind:"if",cond:p(o[0],e),then:p(o[1],e),else:p(o[2],e)}}if(n==="field"){if(o.length!==2)throw N(n);let i=p(o[0],e),r=o[1];if(r.kind!=="lit"||typeof r.value!="string")throw N(n);return Pt({kind:"field",object:o[0],property:r.value},e)}if(jn(n)){if(o.length!==1)throw N(n);return{kind:n,array:p(o[0],e)}}if(_n(n)){if(o.length!==1)throw N(n);return{kind:n,obj:p(o[0],e)}}if(n==="at"){if(o.length!==2)throw N(n);return{kind:"at",array:p(o[0],e),index:p(o[1],e)}}if(n==="includes"){if(o.length!==2)throw N(n);return{kind:"includes",array:p(o[0],e),item:p(o[1],e)}}if($n(n)){if(o.length!==2)throw N(n);let i={...e,allowItem:!0};return n==="map"?{kind:"map",array:p(o[0],e),mapper:p(o[1],i)}:{kind:n,array:p(o[0],e),predicate:p(o[1],i)}}if(n==="slice"){if(o.length<2||o.length>3)throw N(n);let i={kind:"slice",array:p(o[0],e),start:p(o[1],e)};return o.length===3&&(i.end=p(o[2],e)),i}if(n==="substring"||n==="substr"){if(o.length<2||o.length>3)throw N(n);let i={kind:"substring",str:p(o[0],e),start:p(o[1],e)};return o.length===3&&(i.end=p(o[2],e)),i}if(n==="append"){if(o.length<1)throw N(n);return{kind:"append",array:p(o[0],e),items:o.slice(1).map(i=>p(i,e))}}if(n==="merge")return{kind:"merge",objects:o.map(i=>p(i,e))};throw N(n)}function Mn(t,e){let n={};for(let o of At(t.fields))n[o.key]=p(o.value,e);return{kind:"object",fields:n}}function Rn(t,e){if(t.elements.every(i=>i.kind==="lit"))return{kind:"lit",value:t.elements.map(r=>r.value)};let o=t.elements.map(i=>p(i,e));return o.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:o}}function Dn(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function It(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function Fn(t){if(t==="isNotNull")throw N(t);if(!It(t))throw N(t);return t}function Ln(t){return t==="min"||t==="max"}function On(t){return["and","or","concat","coalesce"].includes(t)}function jn(t){return["first","last"].includes(t)}function _n(t){return["keys","values","entries"].includes(t)}function $n(t){return["filter","find","every","some","map"].includes(t)}function Bn(t,e){return t.map(n=>Un(n,e))}function Un(t,e){let n=t.condition?p(t.condition,Se(e,"action")):void 0,o=Gn(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:o,confidence:t.confidence}}function Gn(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:Q(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:Q(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:Q(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:p(t.rule,Se(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:p(t.expr,Se(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:p(t.expr,Se(e,"schema"))}}}function Q(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:Q(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:Q(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(Q)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function Se(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function qn(t,e){return t.map(n=>xe(n,e))}function xe(t,e){let n=t.condition?p(t.condition,e):void 0,o=t.value?p(t.value,e):void 0;return{condition:n,op:t.op,path:zn(t.path,e),value:o}}function zn(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:p(n.expr,e)})}function b(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:Hn(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??B(t.name);case"systemIdent":return Vn(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return Kn(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[b(t.object,e),b(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>b(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[b(t.operand,e)]};case"binary":return{kind:"call",fn:Wn(t.operator),args:[b(t.left,e),b(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[b(t.condition,e),b(t.consequent,e),b(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:b(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>b(n,e))}}}function B(...t){return{kind:"get",path:Mt(...t)}}function Ze(t,...e){return{kind:"get",base:t,path:Mt(...e)}}function re(...t){return{kind:"sys",path:t}}function be(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function Mt(...t){return t.map(e=>({kind:"prop",name:e}))}function Vn(t,e){return e.resolveSystemIdent?.(t.path)??re(...t.path)}function Kn(t,e,n){let o=b(t,n);return o.kind==="get"?{kind:"get",...o.base?{base:o.base}:void 0,path:[...o.path,{kind:"prop",name:e}]}:o.kind==="var"&&o.name==="item"?Ze(o,e):{kind:"field",object:o,property:e}}function Hn(t,e){if(e==="null")return null;if(e==="number"){if(typeof t=="number")return t;if(typeof t=="bigint")return Number(t);if(typeof t=="string"&&t.length>0){let n=Number(t);if(!Number.isNaN(n))return n}throw new Error("Invalid number literal")}if(e==="string"){if(typeof t=="string")return t;throw new Error("Invalid string literal")}if(e==="boolean"){if(typeof t=="boolean")return t;throw new Error("Invalid boolean literal")}throw new Error("Unsupported literal type")}function Wn(t){switch(t){case"+":return"add";case"-":return"sub";case"*":return"mul";case"/":return"div";case"%":return"mod";case"==":return"eq";case"!=":return"neq";case"<":return"lt";case"<=":return"lte";case">":return"gt";case">=":return"gte";case"&&":return"and";case"||":return"or";case"??":return"coalesce"}}import{hashSchemaSync as Zn,semanticPathToPatchPath as eo,sha256Sync as to}from"@manifesto-ai/core";var Qn=new Set(["findById","existsById","updateById","removeById"]);function Rt(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,Yn(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,Xn(n)]))}}function Yn(t){return{...t,expr:Dt(t.expr)}}function Xn(t){return{...t,flow:ve(t.flow),available:t.available?Dt(t.available):void 0}}function ve(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>ve(e))};case"if":return{kind:"if",cond:et(t.cond),then:ve(t.then),else:t.else?ve(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?et(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,Jn(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?et(t.message):void 0};case"call":case"halt":return t}}function Dt(t){return p(I(t),We)}function et(t){return p(I(t),Qe)}function Jn(t){return p(I(t),Ye)}function I(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?B("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:I(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:I(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:I(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>I(e))};case"call":return Qn.has(t.fn)?I(Ft(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>I(e))}}}function Ft(t,e){let[n,o,i]=e,r=I(n),a=o?I(o):{kind:"lit",value:null},s={kind:"var",name:"item"},c=Ze(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[r,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[Ft("findById",e)]}]};case"updateById":{let l=i?I(i):be({});return{kind:"call",fn:"map",args:[r,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,l]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[r,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>I(l))}}}function no(t){return{domainName:t,stateFields:new Set,computedFields:new Set,actionParams:new Map,onceIntentCounters:new Map,currentAction:null,diagnostics:[],typeDefs:new Map,stateFieldSpecs:new Map}}function oo(t){let e=no(t.domain.name);io(t.domain,e);let n=ro(t.domain,e),o=ao(t.domain,e),i=co(t.domain,e),r=ho(t.domain,e);if(e.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:e.diagnostics};let a={id:`mel:${t.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:o,computed:i,actions:r,meta:{name:t.domain.name}},s=wo(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function Lt(t){let e=oo(t);return e.schema?{schema:Rt(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function io(t,e){for(let n of t.types)e.typeDefs.set(n.name,n);for(let n of t.members)if(n.kind==="state")for(let o of n.fields)e.stateFields.add(o.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function ro(t,e){let n={};for(let o of t.types)n[o.name]={name:o.name,definition:Y(o.typeExpr)};return n}function Y(t){switch(t.kind){case"simpleType":return["string","number","boolean","null"].includes(t.name)?{kind:"primitive",type:t.name}:{kind:"ref",name:t.name};case"arrayType":return{kind:"array",element:Y(t.elementType)};case"recordType":return{kind:"record",key:Y(t.keyType),value:Y(t.valueType)};case"objectType":let e={};for(let o of t.fields)e[o.name]={type:Y(o.typeExpr),optional:o.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(Y)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function ao(t,e){let n={};for(let o of t.members)if(o.kind==="state")for(let i of o.fields){let r=X(i.typeExpr,e);r&&e.stateFieldSpecs.set(i.name,r);let a=so(i,e);a&&(n[i.name]=a)}return{fields:n}}function so(t,e){let n=X(t.typeExpr,e);if(!n)return null;let o=t.initializer?Ae(t.initializer,e):void 0;return o!==void 0&&Ce(o,n,t.name,t.location,e),{...n,required:!0,default:o}}function X(t,e,n=[]){switch(t.kind){case"simpleType":switch(t.name){case"string":return{type:"string",required:!0};case"number":return{type:"number",required:!0};case"boolean":return{type:"boolean",required:!0};case"null":return{type:"null",required:!0};default:{let o=e.typeDefs.get(t.name);return o?n.includes(t.name)?(se(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):X(o.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let o=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),i=o.length!==t.types.length,r=[],a=!i;for(let s of o){if(s.kind!=="literalType"){a=!1;break}r.push(s.value)}return a&&r.length>0?{type:{enum:r},required:!0}:i&&o.length===1?(se(e,"E045",`Nullable type '${q(t)}' cannot be lowered to FieldSpec`,t.location),null):(se(e,"E043",`Union type '${q(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let o=X(t.elementType,e,n);return o?{type:"array",required:!0,items:o}:null}case"recordType":return se(e,"E046",`Record type '${q(t)}' cannot be lowered to FieldSpec`,t.location),null;case"literalType":return typeof t.value=="string"?{type:"string",required:!0}:typeof t.value=="number"?{type:"number",required:!0}:typeof t.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let o={};for(let i of t.fields){let r=X(i.typeExpr,e,n);if(!r)return null;o[i.name]={...r,required:!i.optional}}return{type:"object",required:!0,fields:o}}}}function se(t,e,n,o){t.diagnostics.push({severity:"error",code:e,message:n,location:o})}function q(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>q(e)).join(" | ");case"arrayType":return`Array<${q(t.elementType)}>`;case"recordType":return`Record<${q(t.keyType)}, ${q(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${q(e.typeExpr)}`).join("; ")} }`}}function Ce(t,e,n,o,i){if(t===void 0)return;if(t===null){e.required!==!1&&!(typeof e.type=="object"&&"enum"in e.type&&e.type.enum.includes(null))&&i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' is not nullable, but initializer is null`,location:o});return}let r=e.type;if(typeof r=="object"&&"enum"in r){r.enum.some(s=>Object.is(s,t))||i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects one of [${r.enum.join(", ")}], got ${JSON.stringify(t)}`,location:o});return}let a=Array.isArray(t)?"array":typeof t=="object"?"object":typeof t;if(r==="string"&&typeof t!="string"?ae(i,n,"string",a,o):r==="number"&&typeof t!="number"?ae(i,n,"number",a,o):r==="boolean"&&typeof t!="boolean"?ae(i,n,"boolean",a,o):r==="array"&&!Array.isArray(t)?ae(i,n,"array",a,o):r==="object"&&(typeof t!="object"||Array.isArray(t))&&ae(i,n,"object",a,o),r==="object"&&e.fields&&typeof t=="object"&&!Array.isArray(t)){let s=t;for(let[c,l]of Object.entries(e.fields))c in s&&Ce(s[c],l,`${n}.${c}`,o,i)}if(r==="array"&&e.items&&Array.isArray(t))for(let s=0;s<t.length;s++)Ce(t[s],e.items,`${n}[${s}]`,o,i)}function ae(t,e,n,o,i){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${o}`,location:i})}function Ae(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>Ae(n,e));case"objectLiteral":{let n={};for(let o of t.properties)n[o.key]=Ae(o.value,e);return n}default:return}}function co(t,e){let n=[],o=0;for(let r of t.members)if(r.kind==="computed"){let a=U(r.expression,e),s=mo(a);n.push({name:r.name,deps:s,expr:a,location:r.location,order:o}),o+=1}let i={};for(let r of lo(n,e))i[r.name]={deps:r.deps,expr:r.expr};return{fields:i}}function lo(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),o=new Map,i=new Map,r=new Map;for(let c of t)i.set(c.name,[]),r.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));o.set(c.name,l),r.set(c.name,l.length);for(let d of l)i.get(d).push(c.name)}let a=t.filter(c=>(r.get(c.name)??0)===0).map(c=>c.name),s=[];for(;a.length>0;){let c=a.shift();s.push(n.get(c));for(let l of i.get(c)??[]){let d=(r.get(l)??0)-1;r.set(l,d),d===0&&po(a,l,n)}}if(s.length!==t.length){let c=new Set(s.map(u=>u.name)),l=t.filter(u=>!c.has(u.name)),d=uo(l[0].name,o),m=d?d.join(" -> "):l.map(u=>u.name).join(", ");return se(e,"E040",`Circular computed dependency: ${m}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function po(t,e,n){let o=n.get(e)?.order??Number.MAX_SAFE_INTEGER,i=t.length;for(let r=0;r<t.length;r+=1){let a=n.get(t[r])?.order??Number.MAX_SAFE_INTEGER;if(o<a){i=r;break}}t.splice(i,0,e)}function uo(t,e){let n=new Set,o=[],i=new Set;function r(a){n.add(a),o.push(a),i.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(i.has(s)){let c=o.indexOf(s);return[...o.slice(c),s]}}else{let c=r(s);if(c)return c}return o.pop(),i.delete(a),null}return r(t)}function mo(t){let e=new Set;function n(o){switch(o.kind){case"lit":case"sys":case"var":return;case"get":o.base===void 0?e.add(o.path.map(i=>i.name).join(".")):n(o.base);return;case"field":n(o.object);return;case"call":for(let i of o.args)n(i);return;case"obj":for(let i of o.fields)n(i.value);return;case"arr":for(let i of o.elements)n(i);return}}return n(t),Array.from(e)}function ho(t,e){let n={};for(let o of t.members)if(o.kind==="action"){e.currentAction=o.name,e.onceIntentCounters.set(o.name,0);let i=new Set;for(let c of o.params)i.add(c.name);e.actionParams.set(o.name,i);let r=Ot(o.body,e),a;if(o.params.length>0){let c={};for(let l of o.params){let d=X(l.typeExpr,e);d&&(c[l.name]=structuredClone(d))}a={type:"object",required:!0,fields:c}}let s;o.available&&(s=U(o.available,e)),n[o.name]={flow:r,input:a,available:s},e.currentAction=null}return n}function Ot(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Pe(t[0],e):{kind:"seq",steps:t.map(n=>Pe(n,e))}}function Pe(t,e){switch(t.kind){case"when":return fo(t,e);case"once":return yo(t,e);case"onceIntent":return go(t,e);case"patch":return Eo(t,e);case"effect":return No(t,e);case"fail":return To(t,e);case"stop":return So(t,e);case"include":return{kind:"seq",steps:[]}}}function fo(t,e){let n=U(t.condition,e),o=Ot(t.body,e);return{kind:"if",cond:n,then:o}}function yo(t,e){let n=tt(t.marker,e),o=re("meta","intentId"),i=Ie("neq",[B(...jt(n)),o]);if(t.condition){let s=U(t.condition,e);i=Ie("and",[i,s])}let r={kind:"patch",op:"set",path:nt(n),value:o},a=t.body.map(s=>Pe(s,e));return{kind:"if",cond:i,then:{kind:"seq",steps:[r,...a]}}}function go(t,e){let n=e.currentAction??"unknown",o=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,o+1);let i=to(`${n}:${o}:intent`),r=`$mel.guards.intent.${i}`,a=re("meta","intentId"),s=Ie("neq",[B(...jt(r)),a]);if(t.condition){let d=U(t.condition,e);s=Ie("and",[s,d])}let c={kind:"patch",op:"merge",path:nt("$mel.guards.intent"),value:be({[i]:a})},l=t.body.map(d=>Pe(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function Eo(t,e){let n=tt(t.path,e),o={kind:"patch",op:t.op,path:nt(n)};if(t.value){let i=U(t.value,e);if(o.value=i,t.op==="set"){let r=t.path.segments[0];if(r.kind==="propertySegment"){let a=e.stateFieldSpecs.get(r.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l];if(d.kind==="propertySegment"&&s.fields?.[d.name])s=s.fields[d.name];else if(d.kind==="indexSegment"&&s.items)s=s.items;else{s=void 0;break}}if(s){let l=ko(t.value,e);if(l!==void 0){let d=t.path.segments.map(m=>m.kind==="propertySegment"?m.name:"[*]").join(".");Ce(l,s,d,t.location,e)}}}}}}return o}function No(t,e){let n={};for(let o of t.args)o.isPath?n[o.name]={kind:"lit",value:tt(o.value,e)}:n[o.name]=U(o.value,e);return{kind:"effect",type:t.effectType,params:n}}function ko(t,e){return Ae(t,e)}function To(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=U(t.message,e)),n}function So(t,e){return{kind:"halt",reason:t.reason}}function xo(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function we(...t){return t.map(xo).join(".")}function tt(t,e){let n=[];for(let i of t.segments)if(i.kind==="propertySegment")n.push(i.name);else{let r=U(i.index,e);r.kind==="lit"?n.push(String(r.value)):n.push("*")}let o=n[0];return e.stateFields.has(o)?we(...n):e.computedFields.has(o)?we(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(o)?`input.${we(...n)}`:we(...n)}function nt(t){return eo(t)}function Ie(t,e){return{kind:"call",fn:t,args:e}}function jt(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function U(t,e){return b(t,{resolveIdentifier:n=>bo(n,e),resolveSystemIdent:n=>vo(n,e)})}function bo(t,e){return e.stateFields.has(t)||e.computedFields.has(t)?B(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?B("input",t):(e.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${t}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),B(t))}function vo(t,e){let[n,...o]=t;switch(n){case"system":case"meta":case"input":return re(n,...o);default:return e.diagnostics.push({severity:"error",code:"E_INVALID_SYSTEM",message:`Invalid system identifier namespace '$${n}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),{kind:"lit",value:null}}}function wo(t){return Zn(t)}var ot=16;function y(t){return structuredClone(t)}function S(t,e,n,o,i){let r=`${n}:${i.start.offset}:${i.end.offset}:${o}`;e.has(r)||(e.add(r),t.push(ye(n,o,i)))}function Co(t){let e=new Map,n=new Set,o=new Map,i=new Set,r=new Map;for(let a of t.types)o.set(a.name,a);for(let a of t.members)switch(a.kind){case"state":for(let s of a.fields)e.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":i.add(a.name);break;case"flow":r.has(a.name)||r.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:o,actionNames:i,flows:r}}function Ao(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Po(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Io(t,e,n,o){let i=new Map;for(let r of e.flows.values()){i.set(r.name,[]),e.actionNames.has(r.name)&&S(n,o,"E022",`Flow '${r.name}' conflicts with action '${r.name}'.`,r.location);for(let s of r.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&S(n,o,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Ao(r);for(let s of r.body)Ro(s,r.name,a,e,n,o,i.get(r.name))}for(let r of t.members)if(r.kind==="action"){let a=Po(r);for(let s of r.body)Mo(s,a,e,n,o)}return i}function Mo(t,e,n,o,i){switch(t.kind){case"include":Re(t,e,n,o,i);break;case"when":for(let r of t.body)Z(r,e,n,o,i);break;case"once":for(let r of t.body)Z(r,e,n,o,i);break;case"onceIntent":for(let r of t.body)Z(r,e,n,o,i);break;case"fail":case"stop":break}}function Z(t,e,n,o,i){switch(t.kind){case"include":S(o,i,"E016","include is only allowed at action or flow body top-level.",t.location),Re(t,e,n,o,i);break;case"when":for(let r of t.body)Z(r,e,n,o,i);break;case"once":for(let r of t.body)Z(r,e,n,o,i);break;case"onceIntent":for(let r of t.body)Z(r,e,n,o,i);break;case"patch":case"effect":case"fail":case"stop":break}}function Ro(t,e,n,o,i,r,a){switch(t.kind){case"include":Re(t,n,o,i,r)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Me(s,e,n,o,i,r);break;case"once":S(i,r,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":S(i,r,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":S(i,r,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":S(i,r,"E020","effect is not allowed in flow bodies.",t.location);break}}function Me(t,e,n,o,i,r){switch(t.kind){case"include":S(i,r,"E016","include is only allowed at action or flow body top-level.",t.location),Re(t,n,o,i,r);break;case"when":for(let a of t.body)Me(a,e,n,o,i,r);break;case"once":S(i,r,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Me(a,e,n,o,i,r);break;case"onceIntent":S(i,r,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Me(a,e,n,o,i,r);break;case"patch":S(i,r,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":S(i,r,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function Re(t,e,n,o,i){let r=n.flows.get(t.flowName);if(!r)return S(o,i,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==r.params.length)return S(o,i,"E023",`include '${t.flowName}' expected ${r.params.length} argument(s), got ${t.args.length}.`,t.location),!0;for(let a=0;a<t.args.length;a+=1){let s=t.args[a],c=r.params[a],l=ce(s,e,n);if(!l)continue;J(l,c.typeExpr,n)===!1&&S(o,i,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function Do(t,e,n,o){function i(r,a,s){s.add(r);for(let c of t.get(r)??[]){if(a+1>ot){S(n,o,"E014",`Include expansion depth exceeds limit (${ot}).`,c.location);continue}if(s.has(c.target)){S(n,o,"E013","Circular include detected.",c.location);continue}i(c.target,a+1,new Set(s))}}for(let r of e.flows.keys())i(r,1,new Set)}function v(t,e){switch(t.kind){case"identifier":return e.has(t.name)?y(e.get(t.name)):y(t);case"systemIdent":case"literal":case"iterationVar":return y(t);case"functionCall":return{...y(t),args:t.args.map(n=>v(n,e))};case"binary":return{...y(t),left:v(t.left,e),right:v(t.right,e)};case"unary":return{...y(t),operand:v(t.operand,e)};case"ternary":return{...y(t),condition:v(t.condition,e),consequent:v(t.consequent,e),alternate:v(t.alternate,e)};case"propertyAccess":return{...y(t),object:v(t.object,e)};case"indexAccess":return{...y(t),object:v(t.object,e),index:v(t.index,e)};case"objectLiteral":return{...y(t),properties:t.properties.map(n=>({...y(n),value:v(n.value,e)}))};case"arrayLiteral":return{...y(t),elements:t.elements.map(n=>v(n,e))}}}function Fo(t,e){switch(t.kind){case"when":return[_t(t,e)];case"fail":return[{...y(t),message:t.message?v(t.message,e):void 0}];case"stop":return[y(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function _t(t,e){return{...y(t),condition:v(t.condition,e),body:t.body.flatMap(n=>Fo(n,e))}}function Lo(t,e,n){let o=new Map;for(let i=0;i<t.params.length;i+=1)o.set(t.params[i].name,v(e.args[i],n));return o}function Oo(t,e,n,o,i){switch(t.kind){case"when":return[_t(t,n)];case"include":return $t(t,e,n,o,i);case"once":case"onceIntent":case"patch":case"effect":return[]}}function $t(t,e,n,o,i){let r=e.flows.get(t.flowName);if(!r||t.args.length!==r.params.length||o>ot||i.includes(t.flowName))return[];let a=Lo(r,t,n),s=[...i,t.flowName];return r.body.flatMap(c=>Oo(c,e,a,o+1,s))}function ee(t){switch(t.kind){case"when":return[{...y(t),body:t.body.flatMap(e=>ee(e))}];case"once":return[{...y(t),body:t.body.flatMap(e=>ee(e))}];case"onceIntent":return[{...y(t),body:t.body.flatMap(e=>ee(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[y(t)]}}function jo(t,e,n){switch(t.kind){case"include":return $t(t,e,new Map,n,[]);case"when":return[{...y(t),body:t.body.flatMap(o=>ee(o))}];case"once":return[{...y(t),body:t.body.flatMap(o=>ee(o))}];case"onceIntent":return[{...y(t),body:t.body.flatMap(o=>ee(o))}];case"fail":case"stop":return[y(t)]}}function _o(t,e){let n=[];for(let o of t.domain.members)switch(o.kind){case"state":case"computed":n.push(y(o));break;case"action":n.push({...y(o),body:o.body.flatMap(i=>jo(i,e,1))});break;case"flow":break}return{...y(t),domain:{...y(t.domain),types:t.domain.types.map(o=>y(o)),members:n}}}function ce(t,e,n){switch(t.kind){case"literal":return{kind:"literalType",value:t.value,location:t.location};case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??null;case"propertyAccess":{let o=ce(t.object,e,n);return Bt(o,t.property,n)}case"indexAccess":{let o=ce(t.object,e,n);return Ut(o,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let i=ce(o.value,e,n);return i?{kind:"typeField",name:o.key,typeExpr:i,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let o=ce(t.elements[0],e,n);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function le(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),le(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Bt(t,e,n){let o=le(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(r=>r.name===e)?.typeExpr??null;if(o.kind==="unionType")for(let i of o.types){if(i.kind==="simpleType"&&i.name==="null")continue;let r=Bt(i,e,n);if(r)return r}return null}function Ut(t,e){let n=le(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType")for(let o of n.types){if(o.kind==="simpleType"&&o.name==="null")continue;let i=Ut(o,e);if(i)return i}return null}function J(t,e,n){let o=le(t,n),i=le(e,n);if(!o||!i)return null;if(i.kind==="unionType"){let r=i.types.map(a=>J(o,a,n));return r.includes(!0)?!0:r.every(a=>a===!1)?!1:null}if(o.kind==="unionType"){let r=o.types.map(a=>J(a,i,n));return r.every(a=>a===!0)?!0:r.some(a=>a===!1)?!1:null}if(i.kind==="simpleType"){if(o.kind==="simpleType")return o.name===i.name;if(o.kind==="literalType")return i.name==="null"?o.value===null:typeof o.value===i.name}if(i.kind==="literalType")return o.kind!=="literalType"?!1:o.value===i.value;if(i.kind==="arrayType")return o.kind!=="arrayType"?!1:J(o.elementType,i.elementType,n);if(i.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let r of i.fields){let a=o.fields.find(c=>c.name===r.name);if(!a){if(r.optional)continue;return!1}let s=J(a.typeExpr,r.typeExpr,n);if(s!==!0)return s}return!0}return i.kind==="recordType"?o.kind!=="recordType"?null:J(o.valueType,i.valueType,n):null}function Gt(t){let e=Co(t.domain),n=[],o=new Set,i=Io(t.domain,e,n,o);return Do(i,e,n,o),{program:_o(t,e),diagnostics:n}}import{sha256Sync as De}from"@manifesto-ai/core";function qt(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function te(t){return b(t)}var Fe=class{constructor(e){this.deps=e;this.exprValidator=new rt(e.mapLocation)}conditionComposer=new it;exprValidator;collect(e,n,o,i){return this.collectPatchStatements(e,n,o,i)}collectPatchStatements(e,n,o,i){let r=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),r.push({patch:a,condition:i});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=i;try{s=this.conditionComposer.and(i,this.deps.toMelExpr(a.condition))}catch(u){n.push({severity:"error",code:"E_LOWER",message:u.message,location:this.deps.mapLocation(a.condition.location)})}let c=De(`${o.actionName}:${o.whenCounter}:when`);o.whenCounter+=1;let l={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__whenGuards",location:a.location},{kind:"propertySegment",name:c,location:a.location}],location:a.location},d=de(l),m=this.collectPatchStatements(a.body,n,o,void 0).map(u=>({patch:u.patch,condition:this.conditionComposer.and(d,u.condition)}));r.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...m,{patch:{kind:"patch",op:"unset",path:l,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=i,c=de(a.marker),l=a.marker,d=a.location,m={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{m=this.conditionComposer.and(m,this.deps.toMelExpr(a.condition))??m}catch(z){n.push({severity:"error",code:"E_LOWER",message:z.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(i,m);let u=De(`${o.actionName}:${o.onceCounter}:once`);o.onceCounter+=1;let x={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:u,location:d}],location:d},F=de(x),A=this.collectPatchStatements(a.body,n,o,F);r.push({patch:{kind:"patch",op:"set",path:x,value:{kind:"literal",literalType:"boolean",value:!0,location:d},location:d},condition:s},{patch:{kind:"patch",op:"set",path:l,value:{kind:"systemIdent",path:["meta","intentId"],location:d},location:d},condition:F},...A,{patch:{kind:"patch",op:"unset",path:x,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=De(`${o.actionName}:${o.onceCounter}:onceIntent`);o.onceCounter+=1;let c={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__onceScopeGuards",location:a.location},{kind:"propertySegment",name:s,location:a.location}],location:a.location},l=de(c),d=De(`${o.actionName}:${o.onceIntentCounter}:intent`);o.onceIntentCounter+=1;let m=a.location,x={kind:"call",fn:"neq",args:[de({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:m},{kind:"propertySegment",name:"guards",location:m},{kind:"propertySegment",name:"intent",location:m},{kind:"propertySegment",name:d,location:m}],location:m}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{x=this.conditionComposer.and(x,this.deps.toMelExpr(a.condition))??x}catch(_){n.push({severity:"error",code:"E_LOWER",message:_.message,location:this.deps.mapLocation(a.condition.location)})}}let F=this.conditionComposer.and(i,x),A={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:m},{kind:"propertySegment",name:"guards",location:m},{kind:"propertySegment",name:"intent",location:m}],location:m},z=this.collectPatchStatements(a.body,n,o,l);r.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:m},location:m},condition:F},{patch:{kind:"patch",op:"merge",path:A,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:m},location:m}],location:m},location:m},condition:l},...z,{patch:{kind:"patch",op:"unset",path:c,location:m},condition:F});continue}n.push({severity:"error",code:"E_UNSUPPORTED_STMT",message:`Unsupported statement '${a.kind}' in patch text. Only patch statements are allowed.`,location:this.deps.mapLocation(a.location)})}return r}};function zt(t){return{op:t.patch.op,path:$o(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:te(t.patch.value)}:void 0}}function de(t){let e=t.segments,n;for(let o of e){if(o.kind==="propertySegment"){let i={kind:"prop",name:o.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:o.name}]}:n={kind:"get",path:[i]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,te(o.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function $o(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:te(e.index)})}var it=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},rt=class{constructor(e){this.mapLocation=e}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(e,n){for(let o of e.segments)o.kind==="indexSegment"&&this.validateExpr(o.index,n)}validateExpr(e,n){switch(e.kind){case"functionCall":(e.name==="eq"||e.name==="neq")&&e.args.length>=2&&this.validatePrimitiveEquality(e.args[0],e.args[1],e.location,n);for(let o of e.args)this.validateExpr(o,n);return;case"binary":(e.operator==="=="||e.operator==="!=")&&this.validatePrimitiveEquality(e.left,e.right,e.location,n),this.validateExpr(e.left,n),this.validateExpr(e.right,n);return;case"unary":this.validateExpr(e.operand,n);return;case"ternary":this.validateExpr(e.condition,n),this.validateExpr(e.consequent,n),this.validateExpr(e.alternate,n);return;case"propertyAccess":this.validateExpr(e.object,n);return;case"indexAccess":this.validateExpr(e.object,n),this.validateExpr(e.index,n);return;case"objectLiteral":for(let o of e.properties)this.validateExpr(o.value,n);return;case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,o,i){let r=L(e,new Map,this.symbols),a=L(n,new Map,this.symbols);r!=="nonprimitive"&&a!=="nonprimitive"||i.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(o)})}};function Kt(t){let e=[],n=0;for(let o of t)e.push(n),n+=o.length+1;return e}function Ht(t,e){return n=>Wt(n,t,e)}function at(t,e,n){return t.map(o=>Bo(o,e,n))}function Bo(t,e,n){return{...t,location:Wt(t.location,e,n)}}function Wt(t,e,n){return{...t,start:Vt(t.start,e,n),end:Vt(t.end,e,n)}}function Vt(t,e,n){let o=t.line-3,i=e.length,r=Math.min(Math.max(o,1),i),a=n[r-1]??0,s=e[r-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:r,column:l,offset:Math.max(a+l-1,0)}}var pe="__compileMelPatch",Go="__patchDomain",qo=" ";function Qt(t,e){let n=[],o=[],i=[],r=t.split(`
9
- `),a=Kt(r),s=Ht(r,a),c=zo(t,pe),l=performance.now(),d;try{let T=me(c);d=T.tokens;let P=at(T.diagnostics.filter(ue=>ue.severity==="error"),r,a);if(P.length>0)return i.push(...P),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:o,errors:i}}catch(T){return i.push({severity:"error",code:"E_LEX",message:T.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-l}),{ops:[],trace:n,warnings:o,errors:i}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let m=performance.now(),u;try{let T=he(d),P=at(T.diagnostics,r,a),ue=P.filter(je=>je.severity==="error"),Oe=P.filter(je=>je.severity!=="error");if(ue.length>0)return i.push(...ue),o.push(...Oe),n.push({phase:"parse",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:o,errors:i};if(!T.program)return i.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),o.push(...Oe),n.push({phase:"parse",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:o,errors:i};u=T.program,o.push(...Oe)}catch(T){return i.push({severity:"error",code:"E_PARSE",message:T.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:o,errors:i}}n.push({phase:"parse",durationMs:performance.now()-m});let x=performance.now(),F={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},A=u.domain.members.find(T=>T.kind==="action"&&T.name===pe);if(!A)return i.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${pe}' not found during parsing`,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"analyze",durationMs:performance.now()-x}),{ops:[],trace:n,warnings:o,errors:i};let z=r.length+3+2;if(A.location.end.line!==z)return i.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${pe}'.`,location:s(A.location)}),n.push({phase:"analyze",durationMs:performance.now()-x}),{ops:[],trace:n,warnings:o,errors:i};let[_]=A.body;if(!_||_.kind!=="when"||!qt(_.condition)||A.body.length!==1)return i.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${pe}'.`,location:s(A.location)}),n.push({phase:"analyze",durationMs:performance.now()-x}),{ops:[],trace:n,warnings:o,errors:i};let f=new Fe({mapLocation:s,toMelExpr:te}).collect(_.body,i,F,void 0);if(i.length===0&&t.trim()!==""&&f.length===0&&i.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(_.location)}),n.push({phase:"analyze",durationMs:performance.now()-x,details:{count:f.length}}),i.length>0)return{ops:[],trace:n,warnings:o,errors:i};let R=performance.now(),ne={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},V=[];for(let T of f)try{let P=zt(T);V.push(xe(P,ne))}catch(P){P instanceof D?i.push({severity:"error",code:P.code,message:P.message,location:s(T.patch.location)}):P instanceof Error?i.push({severity:"error",code:"E_LOWER",message:P.message,location:s(T.patch.location)}):i.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(T.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-R,details:{count:V.length}}),i.length>0?{ops:[],trace:n,warnings:o,errors:i}:{ops:V,trace:n,warnings:o,errors:i}}function zo(t,e){let n=t.split(`
10
- `).map(o=>`${qo}${o}`).join(`
11
- `);return[`domain ${Go} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
- `)}function Vo(t,e){let n=[],o=[],i=[],r=performance.now(),a;try{let f=me(t);a=f.tokens;let R=f.diagnostics.filter(V=>V.severity==="error");if(R.length>0)return i.push(...R),n.push({phase:"lex",durationMs:performance.now()-r,details:{tokenCount:a.length}}),{schema:null,trace:n,warnings:o,errors:i};let ne=f.diagnostics.filter(V=>V.severity==="warning");o.push(...ne)}catch(f){let R=f;return i.push({severity:"error",code:"E_LEX",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-r}),{schema:null,trace:n,warnings:o,errors:i}}n.push({phase:"lex",durationMs:performance.now()-r,details:{tokenCount:a.length}});let s=performance.now(),c;try{let f=he(a),R=f.diagnostics.filter(ne=>ne.severity==="error");if(R.length>0)return i.push(...R),n.push({phase:"parse",durationMs:performance.now()-s}),{schema:null,trace:n,warnings:o,errors:Yt(i)};c=f.program}catch(f){let R=f;return i.push({severity:"error",code:"E_PARSE",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{schema:null,trace:n,warnings:o,errors:i}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Gt(c),m=d.diagnostics.filter(f=>f.severity==="error"),u=d.diagnostics.filter(f=>f.severity==="warning"),x=ft(d.program),F=Ct(d.program),A=[...m,...x.diagnostics.filter(f=>f.severity==="error"),...F.diagnostics.filter(f=>f.severity==="error")],z=[...u,...x.diagnostics.filter(f=>f.severity==="warning"),...F.diagnostics.filter(f=>f.severity==="warning")];if(o.push(...z),n.push({phase:"analyze",durationMs:performance.now()-l}),A.length>0)return i.push(...A),{schema:null,trace:n,warnings:o,errors:i};let _=performance.now(),Le=Lt(d.program);n.push({phase:"generate",durationMs:performance.now()-_});for(let f of Le.diagnostics)f.severity==="warning"?o.push(f):i.push(f);return{schema:Le.schema,trace:n,warnings:o,errors:Yt(i)}}var st=10;function Yt(t){if(t.length<=st)return t;let e=t.slice(0,st);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-st} more error(s). Fix the errors above first.`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),e}function Ko(t,e){return Qt(t,e)}export{_e as a,Xt as b,Ho as c,ct as d,lt as e,$e as f,dt as g,pt as h,Qo as i,h as j,Be as k,me as l,ii as m,ri as n,ut as o,Ue as p,mt as q,si as r,ci as s,ht as t,Ge as u,he as v,fe as w,qe as x,ft as y,ye as z,yt as A,Ei as B,Jt as C,Ni as D,ki as E,He as F,Ct as G,We as H,Qe as I,Ye as J,xn as K,D as L,ke as M,N,Te as O,Xe as P,bn as Q,Je as R,vn as S,p as T,Bn as U,qn as V,xe as W,oo as X,Lt as Y,Gt as Z,Vo as _,Ko as $};
13
- //# sourceMappingURL=chunk-Z6PR4OWA.js.map