@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.
@@ -43,6 +43,11 @@ export declare class SemanticValidator {
43
43
  * No $system.*, no effects, no $input.*
44
44
  */
45
45
  private validateAvailableExpr;
46
+ /**
47
+ * v0.9.0: Validate dispatchable expression is pure (E047)
48
+ * Allows state/computed/action params, but forbids direct $input.*, $meta.*, and $system.*.
49
+ */
50
+ private validateDispatchableExpr;
46
51
  private validateGuardedStmt;
47
52
  private validateWhen;
48
53
  private validateOnce;
@@ -0,0 +1,12 @@
1
+ var Be={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",dispatchable:"DISPATCHABLE",fail:"FAIL",stop:"STOP",with:"WITH",type:"TYPE",import:"IMPORT",from:"FROM",export:"EXPORT"},tn=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 Xr(t){return t in Be}function ut(t){return tn.has(t)}function mt(t){return Object.hasOwn(Be,t)?Be[t]:void 0}function Ue(t,e,n,r){return{kind:t,lexeme:e,location:n,value:r}}function ht(t,e,n){return{line:t,column:e,offset:n}}function ft(t,e,n){return{start:t,end:e,source:n}}function Zr(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 Ge=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(Ue("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,r=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 o=this.advance();switch(o){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 '\\${o}'`),i+=o}}else i+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${r}`);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),r=parseInt(n,16);this.addToken("NUMBER",r);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(ut(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=mt(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 ft(e,n,this.sourcePath)}positionAt(e){let n=1,r=0;for(let i=0;i<e;i++)this.source[i]===`
7
+ `&&(n++,r=i+1);return ht(n,e-r+1,e)}addToken(e,n){let r=this.source.slice(this.start,this.current);this.tokens.push(Ue(e,r,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let r=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:r,source:this.getSourceLine(r.start.line)})}getSourceLine(e){return this.source.split(`
8
+ `)[e-1]??""}};function ye(t,e){return new Ge(t,e).tokenize()}function ci(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function li(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var yt=(m=>(m[m.NONE=0]="NONE",m[m.TERNARY=1]="TERNARY",m[m.NULLISH=2]="NULLISH",m[m.OR=3]="OR",m[m.AND=4]="AND",m[m.EQUALITY=5]="EQUALITY",m[m.COMPARISON=6]="COMPARISON",m[m.ADDITIVE=7]="ADDITIVE",m[m.MULTIPLICATIVE=8]="MULTIPLICATIVE",m[m.UNARY=9]="UNARY",m[m.CALL=10]="CALL",m[m.ACCESS=11]="ACCESS",m))(yt||{});function qe(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 gt(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 pi(t){return qe(t)!==0}function ui(t){return t==="BANG"||t==="MINUS"}function Et(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var ze=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 r=this.parseDomain();return{kind:"program",imports:n,domain:r,location:h(e,r.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 r=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:r.value,location:h(e,r.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 r=[];for(;this.check("TYPE")&&!this.isAtEnd();)r.push(this.parseTypeDecl());let i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)if(this.check("TYPE"))r.push(this.parseTypeDecl());else{let a=this.parseDomainMember();a&&i.push(a)}let o=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:n,types:r,members:i,location:h(e,o)}}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 r=this.parseTypeExpr();return{kind:"typeDecl",name:n,typeExpr:r,location:h(e,r.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 r=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,r)}}parseStateField(){let e=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let n=this.parseTypeExpr(),r;return this.match("EQ")&&(r=this.parseExpression()),{kind:"stateField",name:e.lexeme,typeExpr:n,initializer:r,location:h(e.location,r?.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 r=this.parseExpression();return{kind:"computed",name:n,expression:r,location:h(e,r.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 r=[];if(!this.check("RPAREN"))do r.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());let o;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),o=this.parseExpression()),this.check("AVAILABLE")){let c=o?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(c)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let a=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let c=this.parseGuardedStmt();c&&a.push(c)}let s=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:n,params:r,available:i,dispatchable:o,body:a,location:h(e,s)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let r=[];if(!this.check("RPAREN"))do r.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 o=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:r,body:i,location:h(e.location,o)}}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 r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseInnerStmt();o&&r.push(o)}let i=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:r,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 r;this.match("WHEN")&&(r=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 o=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:r,body:i,location:h(e,o)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseInnerStmt();o&&r.push(o)}let i=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:r,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 r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));let i=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:r,location:h(e.location,i)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),r,i,o;return this.match("UNSET")?(r="unset",o=this.previous().location):this.match("MERGE")?(r="merge",i=this.parseExpression(),o=i.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),r="set",i=this.parseExpression(),o=i.location),{kind:"patch",path:n,op:r,value:i,location:h(e,o)}}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 r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.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:r,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),r=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:r,isPath:n,location:h(e.location,r.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),r=n.value,i,o=n.location;return this.match("WITH")&&(i=this.parseExpression(),o=i.location),{kind:"fail",code:r,message:i,location:h(e,o)}}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(),r=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,r)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let r=this.parseTypeExpr(),i=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:r,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"),o=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let a=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,typeExpr:a,optional:o,location:h(i.location,a.location)}),this.match("COMMA")}let r=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,r)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let r=qe(this.peek().kind);if(r<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let i=gt(this.peek().kind);if(!i)break;this.advance();let o=Et(this.previous().kind)?r-1:r,a=this.parseExpression(o);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 r=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:r,location:h(e.location,r.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 r=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,r)})}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(),r=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,r)}}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 o=this.parseExpression();n.push({kind:"objectProperty",key:i.lexeme,value:o,location:h(i.location,o.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let r=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,r)}}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 r=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,r)}}parsePath(){let e=[],n=this.peek().location,r=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:r.lexeme,location:r.location});;)if(this.match("DOT")){let o=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:o.lexeme,location:o.location})}else if(this.match("LBRACKET")){let o=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:o,location:h(o.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 ge(t){return new ze(t).parse()}var Ee=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)}},Ve=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 Ee("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let r of e.members)if(r.kind==="state")for(let i of r.fields)this.defineSymbol({name:i.name,kind:"state",location:i.location});else r.kind==="computed"?this.defineSymbol({name:r.name,kind:"computed",location:r.location}):r.kind==="action"?this.defineSymbol({name:r.name,kind:"action",location:r.location}):r.kind;for(let r of e.members)r.kind==="computed"?this.analyzeComputedExpr(r):r.kind==="action"&&this.analyzeAction(r)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new Ee("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let r of e.params)n.define({name:r.name,kind:"param",location:r.location});for(let r of e.body)this.analyzeStmt(r);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 r of e.args)this.analyzeExpr(r,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 r of e.properties)this.analyzeExpr(r.value,n);break;case"arrayLiteral":for(let r of e.elements)this.analyzeExpr(r,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,r){let i=this.currentScope?.lookup(e);if(!i){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}r==="computed"&&i.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,r){let[i,...o]=e;if(i==="system"&&r==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),i==="system"){let a=["uuid","timestamp","time.now","random"],s=o.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=o.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,r){this.diagnostics.push({severity:"error",code:r,message:e,location:n})}};function kt(t){return new Ve().analyze(t)}function ke(t,e,n,r){return{severity:"error",code:t,message:e,location:n,...r}}function Nt(t,e,n,r){return{severity:"warning",code:t,message:e,location:n,...r}}function bi(t,e,n){return{severity:"info",code:t,message:e,location:n}}function nn(t){return t.severity==="error"}function Si(t){return t.some(nn)}function xi(t,e){return t.filter(n=>n.severity===e)}var Tt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),bt=new Set(["add","sub","mul","div","mod","abs","floor","ceil","round","sqrt","pow","len","strlen","indexOf","sum","min","max","toNumber"]),St=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),rn=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),on=new Set(["updateById","removeById"]);function Ne(t){let e=new Map,n=new Map,r=new Map;for(let i of t.types)r.set(i.name,i);for(let i of t.members){if(i.kind==="state"){for(let o of i.fields)e.set(o.name,o.typeExpr);continue}i.kind==="computed"&&n.set(i.name,i)}return{stateTypes:e,computedDecls:n,typeDefs:r,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Te(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 dn(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??an(t.name,n);case"propertyAccess":return K(g(t.object,e,n),t.property,n);case"indexAccess":return ae(g(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let i=g(r.value,e,n);return i?{kind:"typeField",name:r.key,typeExpr:i,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{let r=j(t.elements.map(i=>g(i,e,n)),t.location);return r?{kind:"arrayType",elementType:r,location:t.location}:null}case"unary":return sn(t);case"binary":return cn(t,e,n);case"ternary":return j([g(t.consequent,e,n),g(t.alternate,e,n)],t.location);case"functionCall":return ln(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function F(t,e,n){let r=g(t,e,n);if(r)return xt(r,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?oe([F(t.left,e,n),F(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([F(t.consequent,e,n),F(t.alternate,e,n)]);case"functionCall":return rn.has(t.name)?"nonprimitive":Tt.has(t.name)||bt.has(t.name)||St.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?oe([F(t.args[1],e,n),F(t.args[2],e,n)]):t.name==="coalesce"?oe(t.args.map(i=>F(i,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function xt(t,e){let n=A(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(r=>xt(r,e)))}}function A(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),A(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function K(t,e,n){let r=A(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(o=>o.name===e)?.typeExpr??null;if(r.kind==="unionType"){let i=r.types.filter(o=>!Y(o)).map(o=>K(o,e,n)).filter(o=>o!==null);return j(i,r.location)}return null}function ae(t,e){let n=A(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 r=n.types.filter(i=>!Y(i)).map(i=>ae(i,e)).filter(i=>i!==null);return j(r,n.location)}return null}function O(t,e){let n=A(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(i=>!Y(i)).map(i=>O(i,e)).filter(i=>i!==null);return j(r,n.location)}return null}function be(t,e){let n=A(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(r=>be(r,e));default:return!1}}function Y(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function an(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 r=g(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,r),r}function sn(t){return t.operator==="!"?D("boolean",t.location):D("number",t.location)}function cn(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return D("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return D("number",t.location);case"??":return j([g(t.left,e,n),g(t.right,e,n)],t.location)}}function ln(t,e,n){if(Tt.has(t.name))return D("boolean",t.location);if(bt.has(t.name))return D("number",t.location);if(St.has(t.name))return D("string",t.location);if(t.name==="toBoolean")return D("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let r=O(g(t.args[0],e,n),n);return r?j([r,D("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let r=O(g(t.args[0],e,n),n);return r?j([r,D("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 r=g(t.args[0],e,n),i=O(r,n);if(!i)return null;let o=g(t.args[1],un(e,i),n);return o?{kind:"arrayType",elementType:o,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 ae(g(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let r=pn(t.args[1]);return r?K(g(t.args[0],e,n),r,n):null}return on.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(r=>g(r,e,n)),t.location):t.name==="slice"&&t.args.length>=1?g(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:D("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:D("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(o=>o!==null);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],i=new Set;for(let o of n){let a=JSON.stringify(o);i.has(a)||(i.add(a),r.push(o))}return r.length===1?r[0]:{kind:"unionType",types:r,location:e}}function dn(t,e){return{kind:"literalType",value:t,location:e}}function D(t,e){return{kind:"simpleType",name:t,location:e}}function pn(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function un(t,e){let n=new Map(t);return n.set("$item",e),n}var mn=new Set(["findById","existsById"]),Ke=new Set(["updateById","removeById"]),hn=new Set([...mn,...Ke]);function U(t,e,n,r,i){let o=`${n}:${i.start.offset}:${i.end.offset}:${r}`;e.has(o)||(e.add(o),t.push(ke(n,r,i)))}function vt(t){let e=[],n=new Set,r=Ne(t.domain);En(t.domain,r,e,n);for(let i of t.domain.members)switch(i.kind){case"computed":N(i.expression,"computed",new Map,r,e,n,0);break;case"action":{let o=Te(i.params);fn(i,o,r,e,n);break}case"state":case"flow":break}return e}function fn(t,e,n,r,i){t.available&&N(t.available,"available",e,n,r,i,0),t.dispatchable&&N(t.dispatchable,"dispatchable",e,n,r,i,0);for(let o of t.body)yn(o,e,n,r,i)}function yn(t,e,n,r,i){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"include":break}}function X(t,e,n,r,i){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,i,0);for(let o of t.body)X(o,e,n,r,i);break;case"patch":t.value&&N(t.value,"patch",e,n,r,i,0);break;case"effect":for(let o of t.args)o.isPath||N(o.value,"action",e,n,r,i,0);break;case"fail":t.message&&N(t.message,"action",e,n,r,i,0);break;case"include":case"stop":break}}function N(t,e,n,r,i,o,a){switch(t.kind){case"functionCall":{gn(t,e,n,r,i,o,a);let s=a+(Ke.has(t.name)?1:0);for(let c of t.args)N(c,e,n,r,i,o,s);break}case"binary":N(t.left,e,n,r,i,o,a),N(t.right,e,n,r,i,o,a);break;case"unary":N(t.operand,e,n,r,i,o,a);break;case"ternary":N(t.condition,e,n,r,i,o,a),N(t.consequent,e,n,r,i,o,a),N(t.alternate,e,n,r,i,o,a);break;case"propertyAccess":N(t.object,e,n,r,i,o,a);break;case"indexAccess":N(t.object,e,n,r,i,o,a),N(t.index,e,n,r,i,o,a);break;case"objectLiteral":for(let s of t.properties)N(s.value,e,n,r,i,o,a);break;case"arrayLiteral":for(let s of t.elements)N(s,e,n,r,i,o,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function gn(t,e,n,r,i,o,a){if(!hn.has(t.name)||t.args.length===0)return;Ke.has(t.name)&&(e==="available"?U(i,o,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?U(i,o,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?U(i,o,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&U(i,o,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&U(i,o,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!He(t.args[0],r)&&U(i,o,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=Nn(t.args[0],n,r);if(!s)return;let c=wt(s,r);if(!c){U(i,o,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}be(c,r)||U(i,o,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function En(t,e,n,r){for(let i of t.members)if(i.kind==="state")for(let o of i.fields)kn(o,e,n,r)}function kn(t,e,n,r){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let i=O(t.typeExpr,e);if(!i)return;let o=wt(i,e);if(!o||!be(o,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(p=>p.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)){U(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function Nn(t,e,n){return O(g(t,e,n),n)}function wt(t,e){return K(t,"id",e)}function He(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return He(t.object,e);case"indexAccess":return He(t.object,e);default:return!1}}function At(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Tn=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function E(t,e){return{kind:"simpleType",name:t,location:e}}function G(t,e,n){let r=A(t,n),i=A(e,n);if(!r||!i)return null;if(i.kind==="unionType"){let o=r.kind==="unionType"?r.types:[r],a=!1;for(let s of o){let c=i.types.map(l=>G(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(r.kind==="unionType"){let o=!1;for(let a of r.types){let s=G(a,i,n);if(s===!1)return!1;s===null&&(o=!0)}return o?null:!0}if(i.kind==="simpleType"){if(r.kind==="simpleType")return r.name===i.name;if(r.kind==="literalType")return i.name==="null"?r.value===null:typeof r.value===i.name}if(i.kind==="literalType")return r.kind!=="literalType"?!1:r.value===i.value;if(i.kind==="arrayType")return r.kind!=="arrayType"?!1:G(r.elementType,i.elementType,n);if(i.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let o of i.fields){let a=r.fields.find(c=>c.name===o.name);if(!a){if(o.optional)continue;return!1}let s=G(a.typeExpr,o.typeExpr,n);if(s!==!0)return s}return!0}return i.kind==="recordType"?r.kind!=="recordType"?null:G(r.valueType,i.valueType,n):null}function C(t,e){let n=A(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(r=>`${r.name}${r.optional?"?":""}: ${C(r.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(r=>C(r,e)).join(" | ")}}function We(t,e){let n=A(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 r=new Set;for(let i of n.types){let o=We(i,e);if(o===null)return null;if(o==="nonprimitive")return"nonprimitive";for(let a of o)r.add(a)}return r}}}function Ct(t,e,n){let r=We(t,n),i=We(e,n);if(r===null||i===null)return null;if(r==="nonprimitive"||i==="nonprimitive")return!1;if(!(r instanceof Set)||!(i instanceof Set))return null;let o=[...r].filter(s=>s!=="null"),a=[...i].filter(s=>s!=="null");return o.length===0||a.length===0?!0:o.some(s=>a.includes(s))}function bn(t,e){let n=A(t,e);if(!n||Y(n))return null;if(n.kind!=="unionType")return n;let r=n.types.filter(i=>!Y(i));return r.length===0?null:r.length===1?r[0]:{kind:"unionType",types:r,location:n.location}}function Sn(t,e,n){if(!t||!e)return null;let r=G(t,e,n);if(r===!0)return!0;let i=G(e,t,n);if(i===!0)return!0;let o=Ct(t,e,n);return o!==null?o:r===!1&&i===!1?!1:null}function Pt(t,e){let n=A(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(i=>Pt(i,e));return r.every(i=>i===!0)?!0:r.some(i=>i===!1)?!1:null}return n.kind==="arrayType"}function It(t,e){let n=A(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(i=>It(i,e));return r.every(i=>i===!0)?!0:r.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 xn(t,e){let n=new Map(t);return n.set("$item",e),n}function vn(t,e){let[n,...r]=t.segments;if(!n||n.kind!=="propertySegment")return null;let i=e.stateTypes.get(n.name)??null;for(let o of r){if(!i)return null;i=o.kind==="propertySegment"?K(i,o.name,e):ae(i,e)}return i}function wn(t){let e="";for(let[n,r]of t.segments.entries()){if(r.kind==="propertySegment"){e+=n===0?r.name:`.${r.name}`;continue}r.index.kind==="literal"?e+=`[${JSON.stringify(r.index.value)}]`:e+="[*]"}return e}var Qe=class{ctx=At();symbols=null;validate(e){return this.ctx=At(),this.symbols=Ne(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 r of e.fields){let i=n.get(r.name);i?this.error(`Duplicate state field '${r.name}'. First declared at line ${i.start.line}`,r.location,"E_DUPLICATE_FIELD"):n.set(r.name,r.location),this.validateStateField(r)}}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 r of e.args)this.validateStateInitializer(r);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(Nt("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 r of e.fields)this.checkAnonymousObjectType(r.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 r of e.types)this.checkAnonymousObjectType(r,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Te(e.params),e.available&&this.validateAvailableExpr(e.available),e.dispatchable&&this.validateDispatchableExpr(e.dispatchable);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}}validateDispatchableExpr(e){switch(e.kind){case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",e.location,"E047"),e.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",e.location,"E047"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",e.location,"E047");break;case"functionCall":for(let n of e.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(e.left),this.validateDispatchableExpr(e.right);break;case"unary":this.validateDispatchableExpr(e.operand);break;case"ternary":this.validateDispatchableExpr(e.condition),this.validateDispatchableExpr(e.consequent),this.validateDispatchableExpr(e.alternate);break;case"propertyAccess":this.validateDispatchableExpr(e.object);break;case"indexAccess":this.validateDispatchableExpr(e.object),this.validateDispatchableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateDispatchableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateDispatchableExpr(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,r=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let i=vn(e.path,this.symbols);if(!i||!r)return;G(r,i,this.symbols)===!1&&this.error(`Patch value for '${wn(e.path)}' must be assignable to ${C(i,this.symbols)}, got ${C(r,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"),Tn.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let r=this.ctx.diagnostics.length,i=this.validateExpr(e,"action");r===this.ctx.diagnostics.length&&this.requireAssignable(i,E("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,r=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,r),this.inferType(e,r);case"binary":{let i=this.ctx.diagnostics.length,o=this.validateExpr(e.left,n,r),a=this.validateExpr(e.right,n,r);if(!(i!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,o,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(o,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(o,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(o,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([o,a],e.location);break}return this.inferType(e,r)}case"unary":{let i=this.ctx.diagnostics.length,o=this.validateExpr(e.operand,n,r);return i===this.ctx.diagnostics.length&&this.requireAssignable(o,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,r)}case"ternary":{let i=this.ctx.diagnostics.length,o=this.validateExpr(e.condition,n,r);return this.validateExpr(e.consequent,n,r),this.validateExpr(e.alternate,n,r),i===this.ctx.diagnostics.length&&this.requireAssignable(o,E("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,r)}case"propertyAccess":return this.validateExpr(e.object,n,r),this.inferType(e,r);case"indexAccess":return this.validateExpr(e.object,n,r),this.validateExpr(e.index,n,r),this.inferType(e,r);case"objectLiteral":for(let i of e.properties)this.validateExpr(i.value,n,r);return this.inferType(e,r);case"arrayLiteral":for(let i of e.elements)this.validateExpr(i,n,r);return this.inferType(e,r);case"systemIdent":return this.inferType(e,r);case"literal":case"identifier":case"iterationVar":return this.inferType(e,r)}}validateFunctionCall(e,n,r){let{name:i,args:o,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)&&o.length===1){n==="action"&&this.error(`Primitive aggregation '${i}()' can only be used in computed expressions, not in actions`,a,"E009");let c=o[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":o.length!==1&&this.error(`Function '${i}' expects 1 argument, got ${o.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"gt":case"gte":case"lt":case"lte":o.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${o.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":o.length!==1&&this.error(`Function '${i}' expects 1 argument, got ${o.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":o.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"updateById":o.length!==3&&this.error(`Function '${i}' expects 3 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"removeById":o.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(o.length<2||o.length>3)&&this.error(`Function '${i}' expects 2-3 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"split":o.length!==2&&this.error(`Function '${i}' expects 2 arguments, got ${o.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":o.length<1&&this.error(`Function '${i}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"if":case"cond":o.length!==3&&this.error(`Function '${i}' expects 3 arguments, got ${o.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)&&o.length>0){let c=this.validateExpr(o[0],n,r);s.push(c);let l=r;if(this.symbols){let d=O(c,this.symbols);d&&(l=xn(r,d))}for(let d=1;d<o.length;d+=1)s.push(this.validateExpr(o[d],n,d===1?l:r))}else for(let c of o)s.push(this.validateExpr(c,n,r));if(this.symbols)switch(i){case"eq":case"neq":o.length===2&&this.validatePrimitiveEquality(o[0],o[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"pow":o.length===2&&(this.requireAssignable(s[0],E("number",o[0].location),o[0].location,`Function '${i}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",o[1].location),o[1].location,`Function '${i}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":o.length===2&&(this.requireAssignable(s[0],E("number",o[0].location),o[0].location,`Function '${i}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",o[1].location),o[1].location,`Function '${i}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of o.entries())this.requireAssignable(s[c],E("boolean",l.location),l.location,`Function '${i}' expects boolean arguments`);break;case"not":o.length===1&&this.requireAssignable(s[0],E("boolean",o[0].location),o[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":o.length===1&&this.requireAssignable(s[0],E("number",o[0].location),o[0].location,`Function '${i}' expects a numeric argument`);break;case"trim":case"lower":case"upper":case"strlen":o.length===1&&this.requireAssignable(s[0],E("string",o[0].location),o[0].location,`Function '${i}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":o.length===2&&(this.requireAssignable(s[0],E("string",o[0].location),o[0].location,`Function '${i}' expects a string first argument`),this.requireAssignable(s[1],E("string",o[1].location),o[1].location,`Function '${i}' expects a string second argument`));break;case"replace":o.length>=2&&(this.requireAssignable(s[0],E("string",o[0].location),o[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],E("string",o[1].location),o[1].location,"Function 'replace' expects a string second argument")),o.length===3&&this.requireAssignable(s[2],E("string",o[2].location),o[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":o.length>=2&&(this.requireAssignable(s[0],E("string",o[0].location),o[0].location,`Function '${i}' expects a string first argument`),this.requireAssignable(s[1],E("number",o[1].location),o[1].location,`Function '${i}' expects a numeric second argument`)),o.length===3&&this.requireAssignable(s[2],E("number",o[2].location),o[2].location,`Function '${i}' expects a numeric third argument`);break;case"len":o.length===1&&this.requireLenCompatible(s[0],o[0].location);break;case"filter":case"find":case"every":case"some":o.length===2&&(this.requireArrayCompatible(s[0],o[0].location,i),this.requireAssignable(s[1],E("boolean",o[1].location),o[1].location,`Function '${i}' requires a boolean-valued callback`));break;case"map":o.length===2&&this.requireArrayCompatible(s[0],o[0].location,i);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"if":case"cond":o.length===3&&this.requireAssignable(s[0],E("boolean",o[0].location),o[0].location,`Function '${i}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,r,i,o){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",o,"E_TYPE_MISMATCH");return}Ct(r,i,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${C(r,this.symbols)} and ${C(i,this.symbols)}`,o,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?g(e,n,this.symbols):null}requireAssignable(e,n,r,i){if(!this.symbols||!e)return;G(e,n,this.symbols)===!1&&this.error(`${i}, got ${C(e,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,r){if(!this.symbols||!e)return;Pt(e,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${C(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;It(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 r=e.map(i=>bn(i,this.symbols)).filter(i=>i!==null);for(let i=0;i<r.length;i+=1)for(let o=i+1;o<r.length;o+=1)if(Sn(r[i],r[o],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${C(r[i],this.symbols)} and ${C(r[o],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}error(e,n,r){this.ctx.diagnostics.push({severity:"error",code:r,message:e,location:n})}warn(e,n,r){this.ctx.diagnostics.push({severity:"warning",code:r,message:e,location:n})}};function Mt(t){let n=new Qe().validate(t),r=vt(t),i=[...n.diagnostics,...r];return{valid:!i.some(o=>o.severity==="error"),diagnostics:i}}var Ye={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},Xe={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},Je={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},Ze={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},An={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var L=class extends Error{code;path;details;constructor(e,n,r){super(n),this.name="LoweringError",this.code=e,this.path=r?.path,this.details=r?.details}};function Se(t,e,n){return new L("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function k(t,e){return new L("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function xe(t,e){return new L("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function et(t,e){return new L("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function Cn(t,e){return new L("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function tt(t,e){return new L("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function Pn(t,e){let n=Array.from(t),r=Array.from(e),i=Math.min(n.length,r.length);for(let o=0;o<i;o+=1){let a=n[o].codePointAt(0)??0,s=r[o].codePointAt(0)??0;if(a!==s)return a-s}return n.length-r.length}function Dt(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let r=Pn(e.item.key,n.item.key);return r!==0?r:e.index-n.index}).map(({item:e})=>e)}function u(t,e){switch(t.kind){case"lit":return In(t);case"var":return Mn(t,e);case"sys":return Dn(t,e);case"get":return Rn(t,e);case"field":return Rt(t,e);case"call":return Ln(t,e);case"obj":return Fn(t,e);case"arr":return On(t,e);default:throw tt(t.kind)}}function In(t){return{kind:"lit",value:t.value}}function Mn(t,e){if(!e.allowItem)throw Se("var",e.mode);return{kind:"get",path:"$item"}}function Dn(t,e){if(t.path.length===0)throw xe(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw xe(t.path);return{kind:"get",path:t.path.join(".")}}function Rn(t,e){let n=t.path.map(r=>r.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 Se("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw et(t.base.kind)}function Rt(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(r=>r.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:u(t.object,e),property:t.property}}function Ln(t,e){let{fn:n,args:r}=t;if(jn(n)){if(r.length!==2)throw k(n);let[i,o]=r;return{kind:n,left:u(i,e),right:u(o,e)}}if(n==="isNotNull"){if(r.length!==1)throw k(n);return{kind:"not",arg:{kind:"isNull",arg:u(r[0],e)}}}if(Lt(n)){if(r.length!==1)throw k(n);return{kind:_n(n),arg:u(r[0],e)}}if(n==="trim"){if(r.length!==1)throw k(n);return{kind:"trim",str:u(r[0],e)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw k(n);return{kind:"toLowerCase",str:u(r[0],e)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw k(n);return{kind:"toUpperCase",str:u(r[0],e)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw k(n);return{kind:"strLen",str:u(r[0],e)}}if($n(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(r[0],e)}:{kind:n,args:r.map(i=>u(i,e))};if(n==="sum"){if(r.length!==1)throw k(n);return{kind:"sumArray",array:u(r[0],e)}}if(n==="pow"){if(r.length!==2)throw k(n);return{kind:"pow",base:u(r[0],e),exponent:u(r[1],e)}}if(Bn(n))return{kind:n,args:r.map(i=>u(i,e))};if(n==="if"||n==="cond"){if(r.length!==3)throw k(n);return{kind:"if",cond:u(r[0],e),then:u(r[1],e),else:u(r[2],e)}}if(n==="field"){if(r.length!==2)throw k(n);let i=u(r[0],e),o=r[1];if(o.kind!=="lit"||typeof o.value!="string")throw k(n);return Rt({kind:"field",object:r[0],property:o.value},e)}if(Un(n)){if(r.length!==1)throw k(n);return{kind:n,array:u(r[0],e)}}if(Gn(n)){if(r.length!==1)throw k(n);return{kind:n,obj:u(r[0],e)}}if(n==="at"){if(r.length!==2)throw k(n);return{kind:"at",array:u(r[0],e),index:u(r[1],e)}}if(n==="includes"){if(r.length!==2)throw k(n);return{kind:"includes",array:u(r[0],e),item:u(r[1],e)}}if(qn(n)){if(r.length!==2)throw k(n);let i={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(r[0],e),mapper:u(r[1],i)}:{kind:n,array:u(r[0],e),predicate:u(r[1],i)}}if(n==="slice"){if(r.length<2||r.length>3)throw k(n);let i={kind:"slice",array:u(r[0],e),start:u(r[1],e)};return r.length===3&&(i.end=u(r[2],e)),i}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw k(n);let i={kind:"substring",str:u(r[0],e),start:u(r[1],e)};return r.length===3&&(i.end=u(r[2],e)),i}if(n==="append"){if(r.length<1)throw k(n);return{kind:"append",array:u(r[0],e),items:r.slice(1).map(i=>u(i,e))}}if(n==="merge")return{kind:"merge",objects:r.map(i=>u(i,e))};throw k(n)}function Fn(t,e){let n={};for(let r of Dt(t.fields))n[r.key]=u(r.value,e);return{kind:"object",fields:n}}function On(t,e){if(t.elements.every(i=>i.kind==="lit"))return{kind:"lit",value:t.elements.map(o=>o.value)};let r=t.elements.map(i=>u(i,e));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function jn(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function Lt(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function _n(t){if(t==="isNotNull")throw k(t);if(!Lt(t))throw k(t);return t}function $n(t){return t==="min"||t==="max"}function Bn(t){return["and","or","concat","coalesce"].includes(t)}function Un(t){return["first","last"].includes(t)}function Gn(t){return["keys","values","entries"].includes(t)}function qn(t){return["filter","find","every","some","map"].includes(t)}function zn(t,e){return t.map(n=>Vn(n,e))}function Vn(t,e){let n=t.condition?u(t.condition,ve(e,"action")):void 0,r=Hn(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:r,confidence:t.confidence}}function Hn(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:J(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:J(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:J(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:u(t.rule,ve(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,ve(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,ve(e,"schema"))}}}function J(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:J(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:J(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(J)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function ve(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function Kn(t,e){return t.map(n=>we(n,e))}function we(t,e){let n=t.condition?u(t.condition,e):void 0,r=t.value?u(t.value,e):void 0;return{condition:n,op:t.op,path:Wn(t.path,e),value:r}}function Wn(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function v(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:Xn(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??_(t.name);case"systemIdent":return Qn(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return Yn(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[v(t.object,e),v(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>v(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[v(t.operand,e)]};case"binary":return{kind:"call",fn:Jn(t.operator),args:[v(t.left,e),v(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[v(t.condition,e),v(t.consequent,e),v(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:v(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>v(n,e))}}}function _(...t){return{kind:"get",path:Ft(...t)}}function nt(t,...e){return{kind:"get",base:t,path:Ft(...e)}}function se(...t){return{kind:"sys",path:t}}function Ae(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function Ft(...t){return t.map(e=>({kind:"prop",name:e}))}function Qn(t,e){return e.resolveSystemIdent?.(t.path)??se(...t.path)}function Yn(t,e,n){let r=v(t,n);return r.kind==="get"?{kind:"get",...r.base?{base:r.base}:void 0,path:[...r.path,{kind:"prop",name:e}]}:r.kind==="var"&&r.name==="item"?nt(r,e):{kind:"field",object:r,property:e}}function Xn(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 Jn(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 ir,semanticPathToPatchPath as or,sha256Sync as ar}from"@manifesto-ai/core";var Zn=new Set(["findById","existsById","updateById","removeById"]);function Ot(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,er(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,tr(n)]))}}function er(t){return{...t,expr:jt(t.expr)}}function tr(t){return{...t,flow:Ce(t.flow),available:t.available?jt(t.available):void 0,dispatchable:t.dispatchable?nr(t.dispatchable):void 0}}function Ce(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>Ce(e))};case"if":return{kind:"if",cond:rt(t.cond),then:Ce(t.then),else:t.else?Ce(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?rt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,rr(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?rt(t.message):void 0};case"call":case"halt":return t}}function jt(t){return u(P(t),Ye)}function rt(t){return u(P(t),Xe)}function nr(t){return u(P(t),Je)}function rr(t){return u(P(t),Ze)}function P(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?_("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:P(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:P(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:P(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>P(e))};case"call":return Zn.has(t.fn)?P(_t(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>P(e))}}}function _t(t,e){let[n,r,i]=e,o=P(n),a=r?P(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=nt(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[o,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[_t("findById",e)]}]};case"updateById":{let l=i?P(i):Ae({});return{kind:"call",fn:"map",args:[o,{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:[o,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>P(l))}}}function sr(t){return{domainName:t,stateFields:new Set,computedFields:new Set,actionParams:new Map,onceIntentCounters:new Map,currentAction:null,diagnostics:[],typeDefs:new Map,typeDefinitions:new Map,stateFieldSpecs:new Map,stateFieldTypes:new Map}}function cr(t){let e=sr(t.domain.name);lr(t.domain,e);let n=dr(t.domain,e),r=pr(t.domain,e),i=mr(t.domain,e),o=Er(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:r,computed:i,actions:o,meta:{name:t.domain.name}},s=Ir(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function $t(t){let e=cr(t);return e.schema?{schema:Ot(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function lr(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 r of n.fields)e.stateFields.add(r.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function dr(t,e){let n={};for(let r of t.types){let i=q(r.typeExpr);e.typeDefinitions.set(r.name,i),n[r.name]={name:r.name,definition:i}}return n}function q(t){switch(t.kind){case"simpleType":return["string","number","boolean","null","object","array"].includes(t.name)?{kind:"primitive",type:t.name}:{kind:"ref",name:t.name};case"arrayType":return{kind:"array",element:q(t.elementType)};case"recordType":return{kind:"record",key:q(t.keyType),value:q(t.valueType)};case"objectType":let e={};for(let r of t.fields)e[r.name]={type:q(r.typeExpr),optional:r.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(q)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function pr(t,e){let n={},r={};for(let i of t.members)if(i.kind==="state")for(let o of i.fields){let a=q(o.typeExpr);r[o.name]=a,e.stateFieldTypes.set(o.name,a);let s=Q(o.typeExpr,e);s&&e.stateFieldSpecs.set(o.name,s);let c=ur(o,e);c&&(n[o.name]=c)}return{fields:n,fieldTypes:r}}function ur(t,e){let n=Q(t.typeExpr,e);if(!n)return null;let r=t.initializer?Ie(t.initializer,e):void 0;return r!==void 0&&le(r,q(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:r}}function Q(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 r=e.typeDefs.get(t.name);return r?n.includes(t.name)?(it(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):Q(r.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let r=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),i=r.length!==t.types.length,o=[],a=!i;for(let s of r){if(s.kind!=="literalType"){a=!1;break}o.push(s.value)}return a&&o.length>0?{type:{enum:o},required:!0}:i&&r.length===1?Q(r[0],e,n):(it(e,"E043",`Union type '${Z(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let r=Q(t.elementType,e,n);return r?{type:"array",required:!0,items:r}:null}case"recordType":return{type:"object",required:!0};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 r={};for(let i of t.fields){let o=Q(i.typeExpr,e,n);if(!o)return null;r[i.name]={...o,required:!i.optional}}return{type:"object",required:!0,fields:r}}}}function it(t,e,n,r){t.diagnostics.push({severity:"error",code:e,message:n,location:r})}function Z(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>Z(e)).join(" | ");case"arrayType":return`Array<${Z(t.elementType)}>`;case"recordType":return`Record<${Z(t.keyType)}, ${Z(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${Z(e.typeExpr)}`).join("; ")} }`}}function de(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let r=e.typeDefinitions.get(t.name);return r?de(r,e,[...n,t.name]):null}function z(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${z(t.element)}>`;case"record":return`Record<${z(t.key)}, ${z(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${z(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>z(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function ce(t,e,n){let r=de(e,n);if(!r)return!1;switch(r.kind){case"primitive":switch(r.type){case"null":return t===null;case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"object":return t!==null&&!Array.isArray(t)&&typeof t=="object";case"array":return Array.isArray(t);default:return!1}case"literal":return Object.is(t,r.value);case"array":return Array.isArray(t)&&t.every(i=>ce(i,r.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(i=>ce(i,r.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let i of Object.keys(t))if(!(i in r.fields))return!1;for(let[i,o]of Object.entries(r.fields)){if(!(i in t)){if(!o.optional)return!1;continue}if(!ce(t[i],o.type,n))return!1}return!0;case"union":return r.types.some(i=>ce(t,i,n));case"ref":return!1}}function le(t,e,n,r,i){if(t===void 0)return;let o=de(e,i);if(!o){i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${z(e)}, got ${JSON.stringify(t)}`,location:r});return}if(o.kind==="union"){if(ce(t,o,i))return;i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${z(o)}, got ${JSON.stringify(t)}`,location:r});return}switch(o.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(o.type){case"null":t!==null&&W(i,n,"null",a,r);return;case"string":case"number":case"boolean":typeof t!==o.type&&W(i,n,o.type,a,r);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&W(i,n,"object",a,r);return;case"array":Array.isArray(t)||W(i,n,"array",a,r);return}return}case"literal":Object.is(t,o.value)||i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(o.value)}, got ${JSON.stringify(t)}`,location:r});return;case"array":if(!Array.isArray(t)){W(i,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,r);return}for(let a=0;a<t.length;a+=1)le(t[a],o.element,`${n}[${a}]`,r,i);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;W(i,n,"object",a,r);return}for(let[a,s]of Object.entries(t))le(s,o.value,`${n}.${a}`,r,i);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;W(i,n,"object",a,r);return}for(let a of Object.keys(t))a in o.fields||i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${z(o)}`,location:r});for(let[a,s]of Object.entries(o.fields)){if(!(a in t)){s.optional||i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:r});continue}le(t[a],s.type,`${n}.${a}`,r,i)}return;case"ref":i.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${z(e)}, got ${JSON.stringify(t)}`,location:r});return}}function W(t,e,n,r,i){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${r}`,location:i})}function Ie(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>Ie(n,e));case"objectLiteral":{let n={};for(let r of t.properties)n[r.key]=Ie(r.value,e);return n}default:return}}function mr(t,e){let n=[],r=0;for(let o of t.members)if(o.kind==="computed"){let a=$(o.expression,e),s=gr(a);n.push({name:o.name,deps:s,expr:a,location:o.location,order:r}),r+=1}let i={};for(let o of hr(n,e))i[o.name]={deps:o.deps,expr:o.expr};return{fields:i}}function hr(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),r=new Map,i=new Map,o=new Map;for(let c of t)i.set(c.name,[]),o.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));r.set(c.name,l),o.set(c.name,l.length);for(let d of l)i.get(d).push(c.name)}let a=t.filter(c=>(o.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=(o.get(l)??0)-1;o.set(l,d),d===0&&fr(a,l,n)}}if(s.length!==t.length){let c=new Set(s.map(m=>m.name)),l=t.filter(m=>!c.has(m.name)),d=yr(l[0].name,r),p=d?d.join(" -> "):l.map(m=>m.name).join(", ");return it(e,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function fr(t,e,n){let r=n.get(e)?.order??Number.MAX_SAFE_INTEGER,i=t.length;for(let o=0;o<t.length;o+=1){let a=n.get(t[o])?.order??Number.MAX_SAFE_INTEGER;if(r<a){i=o;break}}t.splice(i,0,e)}function yr(t,e){let n=new Set,r=[],i=new Set;function o(a){n.add(a),r.push(a),i.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(i.has(s)){let c=r.indexOf(s);return[...r.slice(c),s]}}else{let c=o(s);if(c)return c}return r.pop(),i.delete(a),null}return o(t)}function gr(t){let e=new Set;function n(r){switch(r.kind){case"lit":case"sys":case"var":return;case"get":r.base===void 0?e.add(r.path.map(i=>i.name).join(".")):n(r.base);return;case"field":n(r.object);return;case"call":for(let i of r.args)n(i);return;case"obj":for(let i of r.fields)n(i.value);return;case"arr":for(let i of r.elements)n(i);return}}return n(t),Array.from(e)}function Er(t,e){let n={};for(let r of t.members)if(r.kind==="action"){e.currentAction=r.name,e.onceIntentCounters.set(r.name,0);let i=new Set;for(let p of r.params)i.add(p.name);e.actionParams.set(r.name,i);let o=r.params.map(p=>p.name),a=Bt(r.body,e),s,c;if(r.params.length>0){let p={},m={};for(let T of r.params){let b=Q(T.typeExpr,e);b&&(p[T.name]=structuredClone(b),m[T.name]={type:q(T.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:m}}let l;r.available&&(l=$(r.available,e));let d;r.dispatchable&&(d=$(r.dispatchable,e,{preferActionParams:!0})),n[r.name]={flow:a,input:s,inputType:c,params:o,available:l,dispatchable:d},e.currentAction=null}return n}function Bt(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Me(t[0],e):{kind:"seq",steps:t.map(n=>Me(n,e))}}function Me(t,e){switch(t.kind){case"when":return kr(t,e);case"once":return Nr(t,e);case"onceIntent":return Tr(t,e);case"patch":return br(t,e);case"effect":return Sr(t,e);case"fail":return vr(t,e);case"stop":return wr(t,e);case"include":return{kind:"seq",steps:[]}}}function kr(t,e){let n=$(t.condition,e),r=Bt(t.body,e);return{kind:"if",cond:n,then:r}}function Nr(t,e){let n=ot(t.marker,e),r=se("meta","intentId"),i=De("neq",[_(...Ut(n)),r]);if(t.condition){let s=$(t.condition,e);i=De("and",[i,s])}let o={kind:"patch",op:"set",path:at(n),value:r},a=t.body.map(s=>Me(s,e));return{kind:"if",cond:i,then:{kind:"seq",steps:[o,...a]}}}function Tr(t,e){let n=e.currentAction??"unknown",r=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,r+1);let i=ar(`${n}:${r}:intent`),o=`$mel.guards.intent.${i}`,a=se("meta","intentId"),s=De("neq",[_(...Ut(o)),a]);if(t.condition){let d=$(t.condition,e);s=De("and",[s,d])}let c={kind:"patch",op:"merge",path:at("$mel.guards.intent"),value:Ae({[i]:a})},l=t.body.map(d=>Me(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function br(t,e){let n=ot(t.path,e),r={kind:"patch",op:t.op,path:at(n)};if(t.value){let i=$(t.value,e);if(r.value=i,t.op==="set"){let o=t.path.segments[0];if(o.kind==="propertySegment"){let a=e.stateFieldTypes.get(o.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?de(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let m=p.types.filter(T=>{let b=de(T,e);return!(b?.kind==="primitive"&&b.type==="null")&&!(b?.kind==="literal"&&b.value===null)});if(m.length!==1){s=null;break}s=m[0],l-=1;continue}if(d.kind==="propertySegment"&&p.kind==="object"&&p.fields[d.name])s=p.fields[d.name].type;else if(d.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(d.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let l=xr(t.value,e);if(l!==void 0){let d=t.path.segments.map(p=>p.kind==="propertySegment"?p.name:"[*]").join(".");le(l,s,d,t.location,e)}}}}}}return r}function Sr(t,e){let n={};for(let r of t.args)r.isPath?n[r.name]={kind:"lit",value:ot(r.value,e)}:n[r.name]=$(r.value,e);return{kind:"effect",type:t.effectType,params:n}}function xr(t,e){return Ie(t,e)}function vr(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=$(t.message,e)),n}function wr(t,e){return{kind:"halt",reason:t.reason}}function Ar(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Pe(...t){return t.map(Ar).join(".")}function ot(t,e){let n=[];for(let i of t.segments)if(i.kind==="propertySegment")n.push(i.name);else{let o=$(i.index,e);o.kind==="lit"?n.push(String(o.value)):n.push("*")}let r=n[0];return e.stateFields.has(r)?Pe(...n):e.computedFields.has(r)?Pe(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(r)?`input.${Pe(...n)}`:Pe(...n)}function at(t){return or(t)}function De(t,e){return{kind:"call",fn:t,args:e}}function Ut(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function $(t,e,n={}){return v(t,{resolveIdentifier:r=>Cr(r,e,n),resolveSystemIdent:r=>Pr(r,e)})}function Cr(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?_("input",t):e.stateFields.has(t)||e.computedFields.has(t)?_(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?_("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}}}),_(t))}function Pr(t,e){let[n,...r]=t;switch(n){case"system":case"meta":case"input":return se(n,...r);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 Ir(t){return ir(t)}var st=16;function y(t){return structuredClone(t)}function x(t,e,n,r,i){let o=`${n}:${i.start.offset}:${i.end.offset}:${r}`;e.has(o)||(e.add(o),t.push(ke(n,r,i)))}function Mr(t){let e=new Map,n=new Set,r=new Map,i=new Set,o=new Map;for(let a of t.types)r.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":o.has(a.name)||o.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:r,actionNames:i,flows:o}}function Dr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Rr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Lr(t,e,n,r){let i=new Map;for(let o of e.flows.values()){i.set(o.name,[]),e.actionNames.has(o.name)&&x(n,r,"E022",`Flow '${o.name}' conflicts with action '${o.name}'.`,o.location);for(let s of o.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&x(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Dr(o);for(let s of o.body)Or(s,o.name,a,e,n,r,i.get(o.name))}for(let o of t.members)if(o.kind==="action"){let a=Rr(o);for(let s of o.body)Fr(s,a,e,n,r)}return i}function Fr(t,e,n,r,i){switch(t.kind){case"include":Le(t,e,n,r,i);break;case"when":for(let o of t.body)te(o,e,n,r,i);break;case"once":for(let o of t.body)te(o,e,n,r,i);break;case"onceIntent":for(let o of t.body)te(o,e,n,r,i);break;case"fail":case"stop":break}}function te(t,e,n,r,i){switch(t.kind){case"include":x(r,i,"E016","include is only allowed at action or flow body top-level.",t.location),Le(t,e,n,r,i);break;case"when":for(let o of t.body)te(o,e,n,r,i);break;case"once":for(let o of t.body)te(o,e,n,r,i);break;case"onceIntent":for(let o of t.body)te(o,e,n,r,i);break;case"patch":case"effect":case"fail":case"stop":break}}function Or(t,e,n,r,i,o,a){switch(t.kind){case"include":Le(t,n,r,i,o)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Re(s,e,n,r,i,o);break;case"once":x(i,o,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":x(i,o,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":x(i,o,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":x(i,o,"E020","effect is not allowed in flow bodies.",t.location);break}}function Re(t,e,n,r,i,o){switch(t.kind){case"include":x(i,o,"E016","include is only allowed at action or flow body top-level.",t.location),Le(t,n,r,i,o);break;case"when":for(let a of t.body)Re(a,e,n,r,i,o);break;case"once":x(i,o,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Re(a,e,n,r,i,o);break;case"onceIntent":x(i,o,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Re(a,e,n,r,i,o);break;case"patch":x(i,o,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":x(i,o,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function Le(t,e,n,r,i){let o=n.flows.get(t.flowName);if(!o)return x(r,i,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==o.params.length)return x(r,i,"E023",`include '${t.flowName}' expected ${o.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=o.params[a],l=pe(s,e,n);if(!l)continue;ee(l,c.typeExpr,n)===!1&&x(r,i,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function jr(t,e,n,r){function i(o,a,s){s.add(o);for(let c of t.get(o)??[]){if(a+1>st){x(n,r,"E014",`Include expansion depth exceeds limit (${st}).`,c.location);continue}if(s.has(c.target)){x(n,r,"E013","Circular include detected.",c.location);continue}i(c.target,a+1,new Set(s))}}for(let o of e.flows.keys())i(o,1,new Set)}function w(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=>w(n,e))};case"binary":return{...y(t),left:w(t.left,e),right:w(t.right,e)};case"unary":return{...y(t),operand:w(t.operand,e)};case"ternary":return{...y(t),condition:w(t.condition,e),consequent:w(t.consequent,e),alternate:w(t.alternate,e)};case"propertyAccess":return{...y(t),object:w(t.object,e)};case"indexAccess":return{...y(t),object:w(t.object,e),index:w(t.index,e)};case"objectLiteral":return{...y(t),properties:t.properties.map(n=>({...y(n),value:w(n.value,e)}))};case"arrayLiteral":return{...y(t),elements:t.elements.map(n=>w(n,e))}}}function _r(t,e){switch(t.kind){case"when":return[Gt(t,e)];case"fail":return[{...y(t),message:t.message?w(t.message,e):void 0}];case"stop":return[y(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function Gt(t,e){return{...y(t),condition:w(t.condition,e),body:t.body.flatMap(n=>_r(n,e))}}function $r(t,e,n){let r=new Map;for(let i=0;i<t.params.length;i+=1)r.set(t.params[i].name,w(e.args[i],n));return r}function Br(t,e,n,r,i){switch(t.kind){case"when":return[Gt(t,n)];case"include":return qt(t,e,n,r,i);case"once":case"onceIntent":case"patch":case"effect":return[]}}function qt(t,e,n,r,i){let o=e.flows.get(t.flowName);if(!o||t.args.length!==o.params.length||r>st||i.includes(t.flowName))return[];let a=$r(o,t,n),s=[...i,t.flowName];return o.body.flatMap(c=>Br(c,e,a,r+1,s))}function ne(t){switch(t.kind){case"when":return[{...y(t),body:t.body.flatMap(e=>ne(e))}];case"once":return[{...y(t),body:t.body.flatMap(e=>ne(e))}];case"onceIntent":return[{...y(t),body:t.body.flatMap(e=>ne(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[y(t)]}}function Ur(t,e,n){switch(t.kind){case"include":return qt(t,e,new Map,n,[]);case"when":return[{...y(t),body:t.body.flatMap(r=>ne(r))}];case"once":return[{...y(t),body:t.body.flatMap(r=>ne(r))}];case"onceIntent":return[{...y(t),body:t.body.flatMap(r=>ne(r))}];case"fail":case"stop":return[y(t)]}}function Gr(t,e){let n=[];for(let r of t.domain.members)switch(r.kind){case"state":case"computed":n.push(y(r));break;case"action":n.push({...y(r),body:r.body.flatMap(i=>Ur(i,e,1))});break;case"flow":break}return{...y(t),domain:{...y(t.domain),types:t.domain.types.map(r=>y(r)),members:n}}}function pe(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 r=pe(t.object,e,n);return zt(r,t.property,n)}case"indexAccess":{let r=pe(t.object,e,n);return Vt(r,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let i=pe(r.value,e,n);return i?{kind:"typeField",name:r.key,typeExpr:i,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let r=pe(t.elements[0],e,n);return r?{kind:"arrayType",elementType:r,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function ue(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),ue(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function zt(t,e,n){let r=ue(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(o=>o.name===e)?.typeExpr??null;if(r.kind==="unionType")for(let i of r.types){if(i.kind==="simpleType"&&i.name==="null")continue;let o=zt(i,e,n);if(o)return o}return null}function Vt(t,e){let n=ue(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 r of n.types){if(r.kind==="simpleType"&&r.name==="null")continue;let i=Vt(r,e);if(i)return i}return null}function ee(t,e,n){let r=ue(t,n),i=ue(e,n);if(!r||!i)return null;if(i.kind==="unionType"){let o=i.types.map(a=>ee(r,a,n));return o.includes(!0)?!0:o.every(a=>a===!1)?!1:null}if(r.kind==="unionType"){let o=r.types.map(a=>ee(a,i,n));return o.every(a=>a===!0)?!0:o.some(a=>a===!1)?!1:null}if(i.kind==="simpleType"){if(r.kind==="simpleType")return r.name===i.name;if(r.kind==="literalType")return i.name==="null"?r.value===null:typeof r.value===i.name}if(i.kind==="literalType")return r.kind!=="literalType"?!1:r.value===i.value;if(i.kind==="arrayType")return r.kind!=="arrayType"?!1:ee(r.elementType,i.elementType,n);if(i.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let o of i.fields){let a=r.fields.find(c=>c.name===o.name);if(!a){if(o.optional)continue;return!1}let s=ee(a.typeExpr,o.typeExpr,n);if(s!==!0)return s}return!0}return i.kind==="recordType"?r.kind!=="recordType"?null:ee(r.valueType,i.valueType,n):null}function Ht(t){let e=Mr(t.domain),n=[],r=new Set,i=Lr(t.domain,e,n,r);return jr(i,e,n,r),{program:Gr(t,e),diagnostics:n}}import{sha256Sync as Fe}from"@manifesto-ai/core";function Kt(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function re(t){return v(t)}var Oe=class{constructor(e){this.deps=e;this.exprValidator=new lt(e.mapLocation)}conditionComposer=new ct;exprValidator;collect(e,n,r,i){return this.collectPatchStatements(e,n,r,i)}collectPatchStatements(e,n,r,i){let o=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),o.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(m){n.push({severity:"error",code:"E_LOWER",message:m.message,location:this.deps.mapLocation(a.condition.location)})}let c=Fe(`${r.actionName}:${r.whenCounter}:when`);r.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=me(l),p=this.collectPatchStatements(a.body,n,r,void 0).map(m=>({patch:m.patch,condition:this.conditionComposer.and(d,m.condition)}));o.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{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=me(a.marker),l=a.marker,d=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch(V){n.push({severity:"error",code:"E_LOWER",message:V.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(i,p);let m=Fe(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let T={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:m,location:d}],location:d},b=me(T),I=this.collectPatchStatements(a.body,n,r,b);o.push({patch:{kind:"patch",op:"set",path:T,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:b},...I,{patch:{kind:"patch",op:"unset",path:T,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Fe(`${r.actionName}:${r.onceCounter}:onceIntent`);r.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=me(c),d=Fe(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let p=a.location,T={kind:"call",fn:"neq",args:[me({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:d,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{T=this.conditionComposer.and(T,this.deps.toMelExpr(a.condition))??T}catch(B){n.push({severity:"error",code:"E_LOWER",message:B.message,location:this.deps.mapLocation(a.condition.location)})}}let b=this.conditionComposer.and(i,T),I={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},V=this.collectPatchStatements(a.body,n,r,l);o.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:b},{patch:{kind:"patch",op:"merge",path:I,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},...V,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:b});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 o}};function Wt(t){return{op:t.patch.op,path:qr(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:re(t.patch.value)}:void 0}}function me(t){let e=t.segments,n;for(let r of e){if(r.kind==="propertySegment"){let i={kind:"prop",name:r.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:r.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,re(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function qr(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:re(e.index)})}var ct=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},lt=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 r of e.segments)r.kind==="indexSegment"&&this.validateExpr(r.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 r of e.args)this.validateExpr(r,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 r of e.properties)this.validateExpr(r.value,n);return;case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,r,i){let o=F(e,new Map,this.symbols),a=F(n,new Map,this.symbols);o!=="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(r)})}};function Yt(t){let e=[],n=0;for(let r of t)e.push(n),n+=r.length+1;return e}function Xt(t,e){return n=>Jt(n,t,e)}function dt(t,e,n){return t.map(r=>zr(r,e,n))}function zr(t,e,n){return{...t,location:Jt(t.location,e,n)}}function Jt(t,e,n){return{...t,start:Qt(t.start,e,n),end:Qt(t.end,e,n)}}function Qt(t,e,n){let r=t.line-3,i=e.length,o=Math.min(Math.max(r,1),i),a=n[o-1]??0,s=e[o-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:o,column:l,offset:Math.max(a+l-1,0)}}var he="__compileMelPatch",Hr="__patchDomain",Kr=" ";function Zt(t,e){let n=[],r=[],i=[],o=t.split(`
9
+ `),a=Yt(o),s=Xt(o,a),c=Wr(t,he),l=performance.now(),d;try{let S=ye(c);d=S.tokens;let M=dt(S.diagnostics.filter(fe=>fe.severity==="error"),o,a);if(M.length>0)return i.push(...M),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:i}}catch(S){return i.push({severity:"error",code:"E_LEX",message:S.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:r,errors:i}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),m;try{let S=ge(d),M=dt(S.diagnostics,o,a),fe=M.filter($e=>$e.severity==="error"),_e=M.filter($e=>$e.severity!=="error");if(fe.length>0)return i.push(...fe),r.push(..._e),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:i};if(!S.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}}}),r.push(..._e),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:i};m=S.program,r.push(..._e)}catch(S){return i.push({severity:"error",code:"E_PARSE",message:S.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:i}}n.push({phase:"parse",durationMs:performance.now()-p});let T=performance.now(),b={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},I=m.domain.members.find(S=>S.kind==="action"&&S.name===he);if(!I)return i.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${he}' 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()-T}),{ops:[],trace:n,warnings:r,errors:i};let V=o.length+3+2;if(I.location.end.line!==V)return i.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${he}'.`,location:s(I.location)}),n.push({phase:"analyze",durationMs:performance.now()-T}),{ops:[],trace:n,warnings:r,errors:i};let[B]=I.body;if(!B||B.kind!=="when"||!Kt(B.condition)||I.body.length!==1)return i.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${he}'.`,location:s(I.location)}),n.push({phase:"analyze",durationMs:performance.now()-T}),{ops:[],trace:n,warnings:r,errors:i};let f=new Oe({mapLocation:s,toMelExpr:re}).collect(B.body,i,b,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(B.location)}),n.push({phase:"analyze",durationMs:performance.now()-T,details:{count:f.length}}),i.length>0)return{ops:[],trace:n,warnings:r,errors:i};let R=performance.now(),ie={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},H=[];for(let S of f)try{let M=Wt(S);H.push(we(M,ie))}catch(M){M instanceof L?i.push({severity:"error",code:M.code,message:M.message,location:s(S.patch.location)}):M instanceof Error?i.push({severity:"error",code:"E_LOWER",message:M.message,location:s(S.patch.location)}):i.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(S.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-R,details:{count:H.length}}),i.length>0?{ops:[],trace:n,warnings:r,errors:i}:{ops:H,trace:n,warnings:r,errors:i}}function Wr(t,e){let n=t.split(`
10
+ `).map(r=>`${Kr}${r}`).join(`
11
+ `);return[`domain ${Hr} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
+ `)}function Qr(t,e){let n=[],r=[],i=[],o=performance.now(),a;try{let f=ye(t);a=f.tokens;let R=f.diagnostics.filter(H=>H.severity==="error");if(R.length>0)return i.push(...R),n.push({phase:"lex",durationMs:performance.now()-o,details:{tokenCount:a.length}}),{schema:null,trace:n,warnings:r,errors:i};let ie=f.diagnostics.filter(H=>H.severity==="warning");r.push(...ie)}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()-o}),{schema:null,trace:n,warnings:r,errors:i}}n.push({phase:"lex",durationMs:performance.now()-o,details:{tokenCount:a.length}});let s=performance.now(),c;try{let f=ge(a),R=f.diagnostics.filter(ie=>ie.severity==="error");if(R.length>0)return i.push(...R),n.push({phase:"parse",durationMs:performance.now()-s}),{schema:null,trace:n,warnings:r,errors:en(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:r,errors:i}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Ht(c),p=d.diagnostics.filter(f=>f.severity==="error"),m=d.diagnostics.filter(f=>f.severity==="warning"),T=kt(d.program),b=Mt(d.program),I=[...p,...T.diagnostics.filter(f=>f.severity==="error"),...b.diagnostics.filter(f=>f.severity==="error")],V=[...m,...T.diagnostics.filter(f=>f.severity==="warning"),...b.diagnostics.filter(f=>f.severity==="warning")];if(r.push(...V),n.push({phase:"analyze",durationMs:performance.now()-l}),I.length>0)return i.push(...I),{schema:null,trace:n,warnings:r,errors:i};let B=performance.now(),je=$t(d.program);n.push({phase:"generate",durationMs:performance.now()-B});for(let f of je.diagnostics)f.severity==="warning"?r.push(f):i.push(f);return{schema:je.schema,trace:n,warnings:r,errors:en(i)}}var pt=10;function en(t){if(t.length<=pt)return t;let e=t.slice(0,pt);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-pt} 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 Yr(t,e){return Zt(t,e)}export{Be as a,tn as b,Xr as c,ut as d,mt as e,Ue as f,ht as g,ft as h,Zr as i,h as j,Ge as k,ye as l,ci as m,li as n,yt as o,qe as p,gt as q,pi as r,ui as s,Et as t,ze as u,ge as v,Ee as w,Ve as x,kt as y,ke as z,Nt as A,bi as B,nn as C,Si as D,xi as E,Qe as F,Mt as G,Ye as H,Xe as I,Je as J,Ze as K,An as L,L as M,Se as N,k as O,xe as P,et as Q,Cn as R,tt as S,Pn as T,u as U,zn as V,Kn as W,we as X,cr as Y,$t as Z,Ht as _,Qr as $,Yr as aa};
@@ -1,5 +1,4 @@
1
- import{_ as n}from"./chunk-Z6PR4OWA.js";function s(o){let r=o.location;if(!r)return`[${o.code}] ${o.message}`;let{line:e,column:t}=r.start;return`[${o.code}] ${o.message} (${e}:${t})`}function c(o,r){let e=n(o,{mode:"domain"});if(e.errors.length>0){let i=e.errors.map(s).join(`
1
+ import{$ as n}from"./chunk-BJMGKJRO.js";function s(o){let r=o.location;if(!r)return`[${o.code}] ${o.message}`;let{line:e,column:t}=r.start;return`[${o.code}] ${o.message} (${e}:${t})`}function c(o,r){let e=n(o,{mode:"domain"});if(e.errors.length>0){let i=e.errors.map(s).join(`
2
2
  `);throw new Error(`MEL compilation failed for ${r}
3
3
  ${i}`)}if(!e.schema)throw new Error(`MEL compilation produced no schema for ${r}`);return`export default ${JSON.stringify(e.schema,null,2)};
4
4
  `}export{s as a,c as b};
5
- //# sourceMappingURL=chunk-VJFQRHAM.js.map
@@ -1,5 +1,4 @@
1
- import{a as d}from"./chunk-VJFQRHAM.js";import{_ as f}from"./chunk-Z6PR4OWA.js";import{createHash as u}from"crypto";import*as i from"path";import{createUnplugin as p}from"unplugin";var h=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function y(e,t){return e.lastIndex=0,e.test(t)}function b(e){let t=l(e).replace(/\\/g,"/");if(!t)return"domain.mel";if(!i.isAbsolute(e))return t.replace(/^\.\//,"");let n=i.relative(process.cwd(),e);return!n||n.startsWith("..")||i.isAbsolute(n)?M(t):n.split(i.sep).join("/")}function M(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=u("sha256").update(e).digest("hex").slice(0,12);return`external/${x(o)}--${r}${n}`}function x(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"domain"}function w(e){if(!e)return null;if(typeof e=="function")return{emit:e,timing:"transform"};if(typeof e=="object"&&typeof e.emit=="function"){let t=e.timing??"transform";if(!h.has(t))throw new TypeError(`manifesto:mel codegen timing must be one of "transform", "build", or "both" (received ${JSON.stringify(t)})`);return{emit:e.emit,timing:t}}throw new TypeError("manifesto:mel codegen must be a function or an object with a callable emit field")}var I=p((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=w(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return y(t,l(r))},async transform(r,s){let m=l(s),a=f(r,{mode:"domain"});if(a.errors.length>0){let g=a.errors.map(d).join(`
1
+ import{a as d}from"./chunk-JM4I5DPC.js";import{$ as f}from"./chunk-BJMGKJRO.js";import{createHash as u}from"crypto";import*as i from"path";import{createUnplugin as p}from"unplugin";var h=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function y(e,t){return e.lastIndex=0,e.test(t)}function b(e){let t=l(e).replace(/\\/g,"/");if(!t)return"domain.mel";if(!i.isAbsolute(e))return t.replace(/^\.\//,"");let n=i.relative(process.cwd(),e);return!n||n.startsWith("..")||i.isAbsolute(n)?M(t):n.split(i.sep).join("/")}function M(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=u("sha256").update(e).digest("hex").slice(0,12);return`external/${x(o)}--${r}${n}`}function x(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"domain"}function w(e){if(!e)return null;if(typeof e=="function")return{emit:e,timing:"transform"};if(typeof e=="object"&&typeof e.emit=="function"){let t=e.timing??"transform";if(!h.has(t))throw new TypeError(`manifesto:mel codegen timing must be one of "transform", "build", or "both" (received ${JSON.stringify(t)})`);return{emit:e.emit,timing:t}}throw new TypeError("manifesto:mel codegen must be a function or an object with a callable emit field")}var I=p((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=w(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return y(t,l(r))},async transform(r,s){let m=l(s),a=f(r,{mode:"domain"});if(a.errors.length>0){let g=a.errors.map(d).join(`
2
2
  `);throw new Error(`MEL compilation failed for ${m}
3
3
  ${g}`)}if(!a.schema)throw new Error(`MEL compilation produced no schema for ${m}`);let c=b(m);return o&&((o.timing==="transform"||o.timing==="both")&&await o.emit({schema:a.schema,sourceId:c}),(o.timing==="build"||o.timing==="both")&&n.set(c,a.schema)),`export default ${JSON.stringify(a.schema,null,2)};
4
4
  `},async buildEnd(){if(!(!o||n.size===0))for(let[r,s]of n)await o.emit({schema:s,sourceId:r})}}});export{I as a};
5
- //# sourceMappingURL=chunk-7V3B4M34.js.map
package/dist/esbuild.js CHANGED
@@ -1,2 +1 @@
1
- import{a as e}from"./chunk-7V3B4M34.js";import"./chunk-VJFQRHAM.js";import"./chunk-Z6PR4OWA.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
2
- //# sourceMappingURL=esbuild.js.map
1
+ import{a as e}from"./chunk-QXTUKGFJ.js";import"./chunk-JM4I5DPC.js";import"./chunk-BJMGKJRO.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
@@ -65,6 +65,7 @@ export interface FieldSpec {
65
65
  */
66
66
  export interface StateSpec {
67
67
  fields: Record<string, FieldSpec>;
68
+ fieldTypes?: Record<string, TypeDefinition>;
68
69
  }
69
70
  /**
70
71
  * Computed field specification
@@ -91,13 +92,19 @@ export interface ComputedSpec {
91
92
  export interface ActionSpec {
92
93
  flow: CoreFlowNode;
93
94
  input?: FieldSpec;
95
+ inputType?: TypeDefinition;
96
+ params?: readonly string[];
94
97
  available?: CoreExprNode;
98
+ dispatchable?: CoreExprNode;
95
99
  description?: string;
96
100
  }
97
101
  export interface CompilerActionSpec {
98
102
  flow: CompilerFlowNode;
99
103
  input?: FieldSpec;
104
+ inputType?: TypeDefinition;
105
+ params?: readonly string[];
100
106
  available?: CompilerExprNode;
107
+ dispatchable?: CompilerExprNode;
101
108
  description?: string;
102
109
  }
103
110
  /**