@manifesto-ai/compiler 3.7.0 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{da as t}from"./chunk-YIGJ5PGV.js";function i(o){let e=o.location;if(!e)return`[${o.code}] ${o.message}`;let{line:r,column:n}=e.start;return`[${o.code}] ${o.message} (${r}:${n})`}function s(o){return`export default ${JSON.stringify(o,null,2)};
1
+ import{da as t}from"./chunk-O654OLQV.js";function i(o){let e=o.location;if(!e)return`[${o.code}] ${o.message}`;let{line:r,column:n}=e.start;return`[${o.code}] ${o.message} (${r}:${n})`}function s(o){return`export default ${JSON.stringify(o,null,2)};
2
2
  `}function a(o,e){let r=t(o,{mode:"domain"});if(r.errors.length>0){let n=r.errors.map(i).join(`
3
3
  `);throw new Error(`MEL compilation failed for ${e}
4
4
  ${n}`)}if(!r.schema)throw new Error(`MEL compilation produced no schema for ${e}`);return s(r.schema)}export{i as a,s as b,a as c};
@@ -0,0 +1,12 @@
1
+ var Je={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"},er=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 $i(t){return t in Je}function Lt(t){return er.has(t)}function Ft(t){return Object.hasOwn(Je,t)?Je[t]:void 0}function Ze(t,e,n,r){return{kind:t,lexeme:e,location:n,value:r}}function jt(t,e,n){return{line:t,column:e,offset:n}}function _t(t,e,n){return{start:t,end:e,source:n}}function Bi(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 et=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(Ze("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("AT");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,o="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
5
+ `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":o+=`
6
+ `;break;case"r":o+="\r";break;case"t":o+=" ";break;case"\\":o+="\\";break;case"'":o+="'";break;case'"':o+='"';break;case"0":o+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),o+=i}}else o+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${r}`);return}this.advance(),this.addToken("STRING",o)}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(Lt(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ft(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 _t(e,n,this.sourcePath)}positionAt(e){let n=1,r=0;for(let o=0;o<e;o++)this.source[o]===`
7
+ `&&(n++,r=o+1);return jt(n,e-r+1,e)}addToken(e,n){let r=this.source.slice(this.start,this.current);this.tokens.push(Ze(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 Pe(t,e){return new et(t,e).tokenize()}function Qi(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function Xi(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var $t=(f=>(f[f.NONE=0]="NONE",f[f.TERNARY=1]="TERNARY",f[f.NULLISH=2]="NULLISH",f[f.OR=3]="OR",f[f.AND=4]="AND",f[f.EQUALITY=5]="EQUALITY",f[f.COMPARISON=6]="COMPARISON",f[f.ADDITIVE=7]="ADDITIVE",f[f.MULTIPLICATIVE=8]="MULTIPLICATIVE",f[f.UNARY=9]="UNARY",f[f.CALL=10]="CALL",f[f.ACCESS=11]="ACCESS",f))($t||{});function tt(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 Zi(t){return tt(t)!==0}function ea(t){return t==="BANG"||t==="MINUS"}function Bt(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var nt=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.parseAnnotationList();r.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(r);let o=this.parseDomain(r);return{kind:"program",imports:n,domain:o,location:h(e,o.location)}}parseImport(){let e=this.consume("IMPORT","Expected 'import'").location;this.consume("LBRACE","Expected '{' after 'import'");let n=[];do n.push(this.consume("IDENTIFIER","Expected identifier").lexeme);while(this.match("COMMA"));this.consume("RBRACE","Expected '}' after import names"),this.consume("FROM","Expected 'from' after import names");let r=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:r.value,location:h(e,r.location)}}parseDomain(e=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,r=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let o=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))o.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:r,annotations:e.length>0?e:void 0,types:o,members:i,location:h(n,a)}}parseTypeDecl(e=[]){let n=this.consume("TYPE","Expected 'type'").location,r=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let o=this.parseTypeExpr();return{kind:"typeDecl",name:r,annotations:e.length>0?e:void 0,typeExpr:o,location:h(n,o.location)}}parseDomainMember(e=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(e),this.parseState()):this.check("COMPUTED")?this.parseComputed(e):this.check("ACTION")?this.parseAction(e):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(e),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(e),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();){let o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}n.push(this.parseStateField(o))}let r=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,r)}}parseStateField(e=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let r=this.parseTypeExpr(),o;return this.match("EQ")&&(o=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:r,initializer:o,location:h(n.location,o?.location??r.location)}}parseComputed(e=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,r=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let o=this.parseExpression();return{kind:"computed",name:r,annotations:e.length>0?e:void 0,expression:o,location:h(n,o.location)}}parseAction(e=[]){let n=this.consume("ACTION","Expected 'action'").location,r=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let o=[];if(!this.check("RPAREN"))do{let l=this.parseAnnotationList();if(l.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(l);break}o.push(this.parseParam(l))}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 a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let l=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(l)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let l=this.parseGuardedStmt();l&&s.push(l)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:r,annotations:e.length>0?e:void 0,params:o,available:i,dispatchable:a,body:s,location:h(n,c)}}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{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;r.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:r,body:o,location:h(e.location,i)}}parseParam(e=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let r=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:r,location:h(n.location,r.location)}}parseGuardedStmt(){let e=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(e),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 n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),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 i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:r,location:h(e,o)}}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 o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:r,body:o,location:h(e,i)}}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 i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:r,location:h(e.location,o)}}parseInnerStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),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 o=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:r,location:h(e.location,o)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),r,o,i;return this.match("UNSET")?(r="unset",i=this.previous().location):this.match("MERGE")?(r="merge",o=this.parseExpression(),i=o.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),r="set",o=this.parseExpression(),i=o.location),{kind:"patch",path:n,op:r,value:o,location:h(e,i)}}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 o=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:r,location:h(e,o)}}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,o,i=n.location;return this.match("WITH")&&(o=this.parseExpression(),i=o.location),{kind:"fail",code:r,message:o,location:h(e,i)}}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(),o=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:r,location:h(e.location,o)}}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 o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:o.length>0?o:void 0,typeExpr:s,optional:a,location:h(i.location,s.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=tt(this.peek().kind);if(r<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let o=Gt(this.peek().kind);if(!o)break;this.advance();let i=Bt(this.previous().kind)?r-1:r,a=this.parseExpression(i);n={kind:"binary",operator:o,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 o=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:o.lexeme,value:i,location:h(o.location,i.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 i=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:i,location:h(i.location,a)})}else break;let o=e[e.length-1];return{kind:"path",segments:e,location:h(n,o.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","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)}parseAnnotationList(){let e=[];for(;this.check("AT");)e.push(this.parseAnnotation());return e}parseAnnotation(){let e=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let r=this.consume("STRING","Expected string tag as first @meta argument"),o;this.match("COMMA")&&(o=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:r.value,payload:o,location:h(e,i)}}reportUnsupportedAnnotations(e){for(let n of e)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}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)}errorAtToken(e,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:e.location}),new Error(n)}};function Ie(t){return new nt(t).parse()}var Me=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)}},rt=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 Me("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let r of e.members)if(r.kind==="state")for(let o of r.fields)this.defineSymbol({name:o.name,kind:"state",location:o.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 Me("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 o=this.currentScope?.lookup(e);if(!o){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}r==="computed"&&o.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,r){let[o,...i]=e;if(o==="system"&&r==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),o==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(o==="meta"){let a=["intentId","actionName","timestamp"],s=i.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 Ut(t){return new rt().analyze(t)}function D(t,e,n,r){return{severity:"error",code:t,message:e,location:n,...r}}function qt(t,e,n,r){return{severity:"warning",code:t,message:e,location:n,...r}}function da(t,e,n){return{severity:"info",code:t,message:e,location:n}}function tr(t){return t.severity==="error"}function pa(t){return t.some(tr)}function ua(t,e){return t.filter(n=>n.severity===e)}var Vt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),Ht=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),Kt=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),nr=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),rr=new Set(["updateById","removeById"]);function De(t){let e=new Map,n=new Map,r=new Map;for(let o of t.types)r.set(o.name,o);for(let o of t.members){if(o.kind==="state"){for(let i of o.fields)e.set(i.name,i.typeExpr);continue}o.kind==="computed"&&n.set(o.name,o)}return{stateTypes:e,computedDecls:n,typeDefs:r,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Oe(t){let e=new Map;for(let n of t)e.set(n.name,n.typeExpr);return e}function y(t,e,n){switch(t.kind){case"literal":return Er(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??or(t.name,n);case"propertyAccess":return Z(y(t.object,e,n),t.property,n);case"indexAccess":return Ne(y(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let o=y(r.value,e,n);return o?{kind:"typeField",name:r.key,typeExpr:o,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{let r=w(t.elements.map(o=>y(o,e,n)),t.location);return r?{kind:"arrayType",elementType:r,location:t.location}:null}case"unary":return ir(t);case"binary":return ar(t,e,n);case"ternary":return w([y(t.consequent,e,n),y(t.alternate,e,n)],t.location);case"functionCall":return sr(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function G(t,e,n){let r=y(t,e,n);if(r)return Wt(r,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?Te([G(t.left,e,n),G(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 Te([G(t.consequent,e,n),G(t.alternate,e,n)]);case"functionCall":return nr.has(t.name)?"nonprimitive":Vt.has(t.name)||Ht.has(t.name)||Kt.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?Te([G(t.args[1],e,n),G(t.args[2],e,n)]):t.name==="coalesce"?Te(t.args.map(o=>G(o,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function Wt(t,e){let n=S(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 Te(n.types.map(r=>Wt(r,e)))}}function S(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),S(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Z(t,e,n){let r=S(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(i=>i.name===e)?.typeExpr??null;if(r.kind==="unionType"){let o=r.types.filter(i=>!U(i)).map(i=>Z(i,e,n)).filter(i=>i!==null);return w(o,r.location)}return null}function Ne(t,e){let n=S(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(o=>!U(o)).map(o=>Ne(o,e)).filter(o=>o!==null);return w(r,n.location)}return null}function B(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(o=>!U(o)).map(o=>B(o,e)).filter(o=>o!==null);return w(r,n.location)}return null}function Re(t,e){let n=S(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=>Re(r,e));default:return!1}}function U(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function or(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=y(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,r),r}function ir(t){return t.operator==="!"?P("boolean",t.location):P("number",t.location)}function ar(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return P("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return P("number",t.location);case"??":return w([y(t.left,e,n),y(t.right,e,n)],t.location)}}function sr(t,e,n){if(Vt.has(t.name))return P("boolean",t.location);if(Ht.has(t.name))return P("number",t.location);if(t.name==="idiv")return w([P("number",t.location),P("null",t.location)],t.location);if(Kt.has(t.name))return P("string",t.location);if(t.name==="toBoolean")return P("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let r=B(y(t.args[0],e,n),n);return r?w([r,P("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let r=B(y(t.args[0],e,n),n);return r?w([r,P("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return y(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let r=y(t.args[0],e,n),o=B(r,n);if(!o)return null;let i=y(t.args[1],kr(e,o),n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return B(y(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return Ne(y(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let r=Tr(t.args[1]);return r?Z(y(t.args[0],e,n),r,n):null}return rr.has(t.name)&&t.args.length>=1?y(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?w([y(t.args[1],e,n),y(t.args[2],e,n)],t.location):t.name==="coalesce"?yr(t,e,n):t.name==="match"?cr(t,e,n):t.name==="argmax"||t.name==="argmin"?lr(t,e,n):t.name==="slice"&&t.args.length>=1?y(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:P("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:P("string",t.location),location:t.location}:t.name==="values"&&t.args.length>=1?gr(t,e,n):null}function Te(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function w(t,e){let n=t.filter(i=>i!==null);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],o=new Set;for(let i of n){let a=JSON.stringify(i);o.has(a)||(o.add(a),r.push(i))}return r.length===1?r[0]:{kind:"unionType",types:r,location:e}}function cr(t,e,n){if(t.args.length<3)return null;let r=[];for(let o=1;o<t.args.length-1;o+=1){let i=t.args[o];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;r.push(y(i.elements[1],e,n))}return r.push(y(t.args[t.args.length-1],e,n)),w(r,t.location)}function lr(t,e,n){if(t.args.length<2)return null;let r=[];for(let i=0;i<t.args.length-1;i+=1){let a=t.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;r.push(y(a.elements[0],e,n))}let o=w(r,t.location);return o?ur(t,e,n)?o:w([o,P("null",t.location)],t.location):null}var dr=Symbol("arg-selection:other-string"),pr=Symbol("arg-selection:other-number");function ur(t,e,n){let r=[];for(let c=0;c<t.args.length-1;c+=1){let l=t.args[c];if(l.kind!=="arrayLiteral"||l.elements.length!==3)return!1;r.push(l.elements[1])}let o=new Map;for(let c of r)if(!ie(c,e,n,o))return!1;let i=[...o.values()].map(c=>({key:c.key,values:mr(c,n)}));if(i.some(c=>c.values===null||c.values.length===0))return!1;let a=1;for(let c of i)if(a*=c.values.length,a>256)return!1;let s=new Map;return Yt(i,0,s,()=>r.some(c=>F(c,s)===!0))}function Yt(t,e,n,r){if(e>=t.length)return r();let o=t[e];for(let i of o.values)if(n.set(o.key,i),!Yt(t,e+1,n,r))return n.delete(o.key),!1;return n.delete(o.key),!0}function ie(t,e,n,r){switch(t.kind){case"literal":return t.literalType==="boolean";case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":return fr(t,e,n,r);case"unary":return t.operator==="!"&&ie(t.operand,e,n,r);case"binary":return t.operator==="&&"||t.operator==="||"?ie(t.left,e,n,r)&&ie(t.right,e,n,r):t.operator==="=="||t.operator==="!="?zt(t.left,t.right,e,n,r):!1;case"functionCall":switch(t.name){case"and":case"or":return t.args.every(o=>ie(o,e,n,r));case"not":return t.args.length===1&&ie(t.args[0],e,n,r);case"eq":case"neq":return t.args.length===2&&zt(t.args[0],t.args[1],e,n,r);case"isNull":case"isNotNull":return t.args.length===1&&ot(t.args[0],e,n,r,null);default:return!1}default:return!1}}function fr(t,e,n,r){let o=ke(t),i=y(t,e,n);return!o||!i||!Xt(i,n)||at(t,e,n)?!1:(r.get(o)||r.set(o,{key:o,typeExpr:i,comparedLiterals:[]}),!0)}function zt(t,e,n,r,o){let i=it(t),a=it(e);return i!==void 0&&a!==void 0?!0:a!==void 0?ot(t,n,r,o,a):i!==void 0?ot(e,n,r,o,i):!1}function ot(t,e,n,r,o){let i=ke(t),a=y(t,e,n);if(!i||!a||!Jt(a,n)||at(t,e,n))return!1;let s=r.get(i);return s?(s.comparedLiterals.some(c=>Object.is(c,o))||s.comparedLiterals.push(o),!0):(r.set(i,{key:i,typeExpr:a,comparedLiterals:[o]}),!0)}function mr(t,e){let n=[],r=!1,o=a=>{n.some(s=>Object.is(s,a))||n.push(a)},i=a=>{let s=S(a,e);if(!s||r){r=!0;return}switch(s.kind){case"literalType":o(s.value);return;case"simpleType":switch(s.name){case"boolean":o(!0),o(!1);return;case"string":for(let c of t.comparedLiterals)typeof c=="string"&&o(c);o(dr);return;case"number":for(let c of t.comparedLiterals)typeof c=="number"&&o(c);o(pr);return;case"null":o(null);return;default:r=!0;return}case"unionType":for(let c of s.types)i(c);return;default:r=!0}};return i(t.typeExpr),r||n.length===0?null:n}function F(t,e){switch(t.kind){case"literal":return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0;case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":{let n=ke(t);return n?e.get(n):void 0}case"unary":{let n=F(t.operand,e);return t.operator==="!"&&typeof n=="boolean"?!n:void 0}case"binary":{let n=F(t.left,e),r=F(t.right,e);switch(t.operator){case"&&":return typeof n=="boolean"&&typeof r=="boolean"?n&&r:void 0;case"||":return typeof n=="boolean"&&typeof r=="boolean"?n||r:void 0;case"==":return n!==void 0&&r!==void 0?Object.is(n,r):void 0;case"!=":return n!==void 0&&r!==void 0?!Object.is(n,r):void 0;default:return}}case"functionCall":switch(t.name){case"and":{let n=t.args.map(r=>F(r,e));return n.every(r=>typeof r=="boolean")?n.every(Boolean):void 0}case"or":{let n=t.args.map(r=>F(r,e));return n.every(r=>typeof r=="boolean")?n.some(Boolean):void 0}case"not":{let n=t.args.length===1?F(t.args[0],e):void 0;return typeof n=="boolean"?!n:void 0}case"eq":case"neq":{if(t.args.length!==2)return;let n=F(t.args[0],e),r=F(t.args[1],e);return n===void 0||r===void 0?void 0:t.name==="eq"?Object.is(n,r):!Object.is(n,r)}case"isNull":{if(t.args.length!==1)return;let n=F(t.args[0],e);return n===void 0?void 0:n===null}case"isNotNull":{if(t.args.length!==1)return;let n=F(t.args[0],e);return n===void 0?void 0:n!==null}case"cond":case"if":{if(t.args.length!==3)return;let n=F(t.args[0],e);return typeof n!="boolean"?void 0:F(n?t.args[1]:t.args[2],e)}default:return}default:return}}function ke(t){switch(t.kind){case"identifier":return`id:${t.name}`;case"iterationVar":return"$item";case"propertyAccess":{let e=ke(t.object);return e?`${e}.${t.property}`:null}case"indexAccess":{let e=ke(t.object),n=it(t.index);return e&&n!==void 0?`${e}[${JSON.stringify(n)}]`:null}default:return null}}function at(t,e,n){switch(t.kind){case"propertyAccess":return st(y(t.object,e,n),n)||hr(t.object,t.property,e,n)||at(t.object,e,n);case"indexAccess":return!0;default:return!1}}function hr(t,e,n,r){return Qt(y(t,n,r),e,r)}function Qt(t,e,n){let r=S(t,n);if(!r)return!0;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===e);return!o||o.optional}if(r.kind==="unionType"){let o=r.types.filter(i=>!U(i));return o.length===0||o.some(i=>Qt(i,e,n))}return!0}function Xt(t,e){let n=S(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="boolean";case"literalType":return typeof n.value=="boolean";case"unionType":return n.types.length>0&&n.types.every(r=>Xt(r,e));default:return!1}}function Jt(t,e){let n=S(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null";case"literalType":return typeof n.value=="string"||typeof n.value=="number"||typeof n.value=="boolean"||n.value===null;case"unionType":return n.types.length>0&&n.types.every(r=>Jt(r,e));default:return!1}}function it(t){if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function yr(t,e,n){let r=t.args.map(a=>y(a,e,n));if(r.some(a=>a===null))return w(r,t.location);let o=r.map(a=>en(a,n)).filter(a=>a!==null);if(o.length===0)return w(r,t.location);let i=[...o];return r.every(a=>a!==null&&st(a,n))&&i.push(P("null",t.location)),w(i,t.location)}function gr(t,e,n){if(t.args.length<1)return null;let r=Zt(y(t.args[0],e,n),n);return r?{kind:"arrayType",elementType:r,location:t.location}:null}function Zt(t,e){let n=S(t,e);return n?n.kind==="recordType"?n.valueType:n.kind==="objectType"?w(n.fields.map(r=>r.typeExpr),n.location):n.kind==="unionType"?w(n.types.filter(r=>!U(r)).map(r=>Zt(r,e)),n.location):null:null}function en(t,e){let n=S(t,e);if(!n||U(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(o=>en(o,e)).filter(o=>o!==null);return r.length===0?null:w(r,n.location)}function st(t,e){let n=S(t,e);return!n||U(n)?!0:n.kind!=="unionType"?!1:n.types.some(r=>st(r,e))}function Er(t,e){return{kind:"literalType",value:t,location:e}}function P(t,e){return{kind:"simpleType",name:t,location:e}}function Tr(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function kr(t,e){let n=new Map(t);return n.set("$item",e),n}var Nr=new Set(["findById","existsById"]),lt=new Set(["updateById","removeById"]),br=new Set([...Nr,...lt]);function W(t,e,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;e.has(i)||(e.add(i),t.push(D(n,r,o)))}function tn(t){let e=[],n=new Set,r=De(t.domain);Ar(t.domain,r,e,n);for(let o of t.domain.members)switch(o.kind){case"computed":N(o.expression,"computed",new Map,r,e,n,0);break;case"action":{let i=Oe(o.params);Sr(o,i,r,e,n);break}case"state":case"flow":break}return e}function Sr(t,e,n,r,o){t.available&&N(t.available,"available",e,n,r,o,0),t.dispatchable&&N(t.dispatchable,"dispatchable",e,n,r,o,0);for(let i of t.body)xr(i,e,n,r,o)}function xr(t,e,n,r,o){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"include":break}}function ae(t,e,n,r,o){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"patch":t.value&&N(t.value,"patch",e,n,r,o,0);break;case"effect":for(let i of t.args)i.isPath||N(i.value,"action",e,n,r,o,0);break;case"fail":t.message&&N(t.message,"action",e,n,r,o,0);break;case"include":case"stop":break}}function N(t,e,n,r,o,i,a){switch(t.kind){case"functionCall":{vr(t,e,n,r,o,i,a);let s=a+(lt.has(t.name)?1:0);for(let c of t.args)N(c,e,n,r,o,i,s);break}case"binary":N(t.left,e,n,r,o,i,a),N(t.right,e,n,r,o,i,a);break;case"unary":N(t.operand,e,n,r,o,i,a);break;case"ternary":N(t.condition,e,n,r,o,i,a),N(t.consequent,e,n,r,o,i,a),N(t.alternate,e,n,r,o,i,a);break;case"propertyAccess":N(t.object,e,n,r,o,i,a);break;case"indexAccess":N(t.object,e,n,r,o,i,a),N(t.index,e,n,r,o,i,a);break;case"objectLiteral":for(let s of t.properties)N(s.value,e,n,r,o,i,a);break;case"arrayLiteral":for(let s of t.elements)N(s,e,n,r,o,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function vr(t,e,n,r,o,i,a){if(!br.has(t.name)||t.args.length===0)return;lt.has(t.name)&&(e==="available"?W(o,i,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?W(o,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?W(o,i,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&W(o,i,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&W(o,i,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!ct(t.args[0],r)&&W(o,i,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=Cr(t.args[0],n,r);if(!s)return;let c=nn(s,r);if(!c){W(o,i,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}Re(c,r)||W(o,i,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function Ar(t,e,n,r){for(let o of t.members)if(o.kind==="state")for(let i of o.fields)wr(i,e,n,r)}function wr(t,e,n,r){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let o=B(t.typeExpr,e);if(!o)return;let i=nn(o,e);if(!i||!Re(i,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)){W(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function Cr(t,e,n){return B(y(t,e,n),n)}function nn(t,e){return Z(t,"id",e)}function ct(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return ct(t.object,e);case"indexAccess":return ct(t.object,e);default:return!1}}function rn(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Pr=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function T(t,e){return{kind:"simpleType",name:t,location:e}}function q(t,e,n){let r=S(t,n),o=S(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=r.kind==="unionType"?r.types:[r],a=!1;for(let s of i){let c=o.types.map(l=>q(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 i=!1;for(let a of r.types){let s=q(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:q(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=q(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:q(r.valueType,o.valueType,n):null}function v(t,e){let n=S(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<${v(n.elementType,e)}>`;case"recordType":return`Record<${v(n.keyType,e)}, ${v(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(r=>`${r.name}${r.optional?"?":""}: ${v(r.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(r=>v(r,e)).join(" | ")}}function Le(t,e){let n=S(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 o of n.types){let i=Le(o,e);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)r.add(a)}return r}}}function dt(t,e){let n=Le(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let r=[...n].filter(o=>o!=="null");return r.length!==1||n.has("null")?"invalid":r[0]}function an(t,e,n){let r=Le(t,n),o=Le(e,n);if(r===null||o===null)return null;if(r==="nonprimitive"||o==="nonprimitive")return!1;if(!(r instanceof Set)||!(o instanceof Set))return null;let i=[...r].filter(s=>s!=="null"),a=[...o].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function sn(t,e){let n=S(t,e);if(!n||U(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(a=>sn(a,e)).filter(a=>a!==null);if(r.length===0)return null;let o=[],i=new Set;for(let a of r){let s=JSON.stringify(a);i.has(s)||(i.add(s),o.push(a))}return o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function pt(t,e,n){if(!t||!e)return null;let r=q(t,e,n);if(r===!0)return!0;let o=q(e,t,n);if(o===!0)return!0;let i=an(t,e,n);return i!==null?i:r===!1&&o===!1?!1:null}function ut(t,e,n){let r=S(t,n),o=S(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=!1;for(let a of o.types){if(U(a))continue;let s=ut(r,a,n);if(s===!0)return!0;s===null&&(i=!0)}return i?null:!1}if(r.kind==="unionType"){let i=!1;for(let a of r.types){let s=ut(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind!=="objectType"||r.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a)return!1;let s=q(i.typeExpr,a.typeExpr,n);if(s!==!0)return s}return!0}function cn(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>cn(o,e));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"}function ln(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>ln(o,e));return r.every(o=>o===!0)?!0:r.some(o=>o===!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 Ir(t,e){let n=new Map(t);return n.set("$item",e),n}function on(t){let e=Fe(t);if(typeof e=="number")return e;if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function Fe(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=Fe(t.operand);return typeof e=="number"?-e:void 0}}function Mr(t,e){let[n,...r]=t.segments;if(!n||n.kind!=="propertySegment")return null;let o=e.stateTypes.get(n.name)??null;for(let i of r){if(!o)return null;o=i.kind==="propertySegment"?Z(o,i.name,e):Ne(o,e)}return o}function Dr(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 ft=class{ctx=rn();symbols=null;validate(e){return this.ctx=rn(),this.symbols=De(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 o=n.get(r.name);o?this.error(`Duplicate state field '${r.name}'. First declared at line ${o.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(qt("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=Oe(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 o=Mr(e.path,this.symbols);if(!o||!r)return;(e.op==="merge"?ut(r,o,this.symbols):q(r,o,this.symbols))===!1&&this.error(`Patch value for '${Dr(e.path)}' must be assignable to ${v(o,this.symbols)}, got ${v(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"),Pr.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,o=this.validateExpr(e,"action");r===this.ctx.diagnostics.length&&this.requireAssignable(o,T("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 o=this.ctx.diagnostics.length,i=this.validateExpr(e.left,n,r),a=this.validateExpr(e.right,n,r);if(!(o!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,i,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,T("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,T("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,T("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,T("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],e.location);break}return this.inferType(e,r)}case"unary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(e.operand,n,r);return o===this.ctx.diagnostics.length&&this.requireAssignable(i,T(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 o=this.ctx.diagnostics.length,i=this.validateExpr(e.condition,n,r);return this.validateExpr(e.consequent,n,r),this.validateExpr(e.alternate,n,r),o===this.ctx.diagnostics.length&&this.requireAssignable(i,T("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 o of e.properties)this.validateExpr(o.value,n,r);return this.inferType(e,r);case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,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:o,args:i,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(o)&&this.error(`Function '${o}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(o)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${o}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${o}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(o){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.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":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.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":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${o}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${o}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${o}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${o}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(o)&&i.length>0){let c=this.validateExpr(i[0],n,r);s.push(c);let l=r;if(this.symbols){let d=B(c,this.symbols);d&&(l=Ir(r,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:r))}else for(let c of i)s.push(this.validateExpr(c,n,r));if(this.symbols)switch(o){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],T("boolean",l.location),l.location,`Function '${o}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],T("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=Fe(i[1]),l=Fe(i[2]);typeof c=="number"&&typeof l=="number"&&c>l&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,`Function '${o}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],T("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],T("number",i[2].location),i[2].location,`Function '${o}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,o),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,`Function '${o}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,o);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,r);break;case"argmax":case"argmin":this.validateArgSelectionCall(o,i,a,r);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,`Function '${o}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,r,o,i){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",i,"E_TYPE_MISMATCH");return}an(r,o,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(r,this.symbols)} and ${v(o,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?y(e,n,this.symbols):null}requireAssignable(e,n,r,o){if(!this.symbols||!e)return;q(e,n,this.symbols)===!1&&this.error(`${o}, got ${v(e,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,r){if(!this.symbols||!e)return;cn(e,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;ln(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let r=e.map(o=>sn(o,this.symbols)).filter(o=>o!==null);for(let o=0;o<r.length;o+=1)for(let i=o+1;i<r.length;i+=1)if(pt(r[o],r[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(r[o],this.symbols)} and ${v(r[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,r,o){if(!this.symbols||e.length<3)return;let i=n[0],a=dt(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(i,this.symbols)}`,e[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<e.length-1;l+=1){let d=e[l];if(d.kind!=="arrayLiteral"||d.elements.length!==2){this.error("Function 'match' requires each arm to be an inline [key, value] array literal",d.location,"E050");continue}let[p,f]=d.elements,m=on(p);if(m==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let $=`${typeof m}:${String(m)}`;s.has($)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(m)}`,p.location,"E051"):s.add($)}let A=this.inferType(p,o),b=dt(A,this.symbols);(b==="invalid"||a!==null&&b!==null&&a!==b)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${v(i,this.symbols)} and ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(f,o))}c.push(n[n.length-1]);for(let l=0;l<c.length;l+=1)for(let d=l+1;d<c.length;d+=1)if(pt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,r,o){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=on(i);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,i.location,"E052");let s=[],c=null;for(let l=0;l<n.length-1;l+=1){let d=n[l];if(d.kind!=="arrayLiteral"||d.elements.length!==3){this.error(`Function '${e}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[p,f,m]=d.elements,A=this.inferType(p,o),b=dt(A,this.symbols);b==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=b:b!==null&&b!==c&&this.error(`Function '${e}' candidate labels must share one primitive scalar type, got ${c} and ${b}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(f,o),T("boolean",f.location),f.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(m,o),T("number",m.location),m.location,`Function '${e}' expects a numeric score value`),s.push(A)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(pt(s[l],s[d],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,r,"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 dn(t){let n=new ft().validate(t),r=tn(t),o=[...n.diagnostics,...r];return{valid:!o.some(i=>i.severity==="error"),diagnostics:o}}var mt={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},ht={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},yt={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},gt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Or={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var _=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 je(t,e,n){return new _("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function g(t,e){return new _("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function _e(t,e){return new _("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function Et(t,e){return new _("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function Rr(t,e){return new _("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function Tt(t,e){return new _("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function Lr(t,e){let n=Array.from(t),r=Array.from(e),o=Math.min(n.length,r.length);for(let i=0;i<o;i+=1){let a=n[i].codePointAt(0)??0,s=r[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-r.length}function pn(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let r=Lr(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 Fr(t);case"var":return jr(t,e);case"sys":return _r(t,e);case"get":return $r(t,e);case"field":return un(t,e);case"call":return Gr(t,e);case"obj":return Br(t,e);case"arr":return Ur(t,e);default:throw Tt(t.kind)}}function Fr(t){return{kind:"lit",value:t.value}}function jr(t,e){if(!e.allowItem)throw je("var",e.mode);return{kind:"get",path:"$item"}}function _r(t,e){if(t.path.length===0)throw _e(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw _e(t.path);return{kind:"get",path:t.path.join(".")}}function $r(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 je("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw Et(t.base.kind)}function un(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 Gr(t,e){let{fn:n,args:r}=t;if(n==="absDiff"){if(r.length!==2)throw g(n);return{kind:"abs",arg:{kind:"sub",left:u(r[0],e),right:u(r[1],e)}}}if(n==="clamp"){if(r.length!==3)throw g(n);return{kind:"min",args:[{kind:"max",args:[u(r[0],e),u(r[1],e)]},u(r[2],e)]}}if(n==="idiv"){if(r.length!==2)throw g(n);return{kind:"floor",arg:{kind:"div",left:u(r[0],e),right:u(r[1],e)}}}if(n==="streak"){if(r.length!==2)throw g(n);return{kind:"if",cond:u(r[1],e),then:{kind:"add",left:u(r[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return qr(r,e);if(n==="argmax"||n==="argmin")return zr(n,r,e);if(Yr(n)){if(r.length!==2)throw g(n);let[o,i]=r;return{kind:n,left:u(o,e),right:u(i,e)}}if(n==="isNotNull"){if(r.length!==1)throw g(n);return{kind:"not",arg:{kind:"isNull",arg:u(r[0],e)}}}if(fn(n)){if(r.length!==1)throw g(n);return{kind:Qr(n),arg:u(r[0],e)}}if(n==="trim"){if(r.length!==1)throw g(n);return{kind:"trim",str:u(r[0],e)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw g(n);return{kind:"toLowerCase",str:u(r[0],e)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw g(n);return{kind:"toUpperCase",str:u(r[0],e)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw g(n);return{kind:"strLen",str:u(r[0],e)}}if(Xr(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(r[0],e)}:{kind:n,args:r.map(o=>u(o,e))};if(n==="sum"){if(r.length!==1)throw g(n);return{kind:"sumArray",array:u(r[0],e)}}if(n==="pow"){if(r.length!==2)throw g(n);return{kind:"pow",base:u(r[0],e),exponent:u(r[1],e)}}if(Jr(n))return{kind:n,args:r.map(o=>u(o,e))};if(n==="if"||n==="cond"){if(r.length!==3)throw g(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 g(n);let o=u(r[0],e),i=r[1];if(i.kind!=="lit"||typeof i.value!="string")throw g(n);return un({kind:"field",object:r[0],property:i.value},e)}if(Zr(n)){if(r.length!==1)throw g(n);return{kind:n,array:u(r[0],e)}}if(eo(n)){if(r.length!==1)throw g(n);return{kind:n,obj:u(r[0],e)}}if(n==="at"){if(r.length!==2)throw g(n);return{kind:"at",array:u(r[0],e),index:u(r[1],e)}}if(n==="includes"){if(r.length!==2)throw g(n);return{kind:"includes",array:u(r[0],e),item:u(r[1],e)}}if(to(n)){if(r.length!==2)throw g(n);let o={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(r[0],e),mapper:u(r[1],o)}:{kind:n,array:u(r[0],e),predicate:u(r[1],o)}}if(n==="slice"){if(r.length<2||r.length>3)throw g(n);let o={kind:"slice",array:u(r[0],e),start:u(r[1],e)};return r.length===3&&(o.end=u(r[2],e)),o}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw g(n);let o={kind:"substring",str:u(r[0],e),start:u(r[1],e)};return r.length===3&&(o.end=u(r[2],e)),o}if(n==="append"){if(r.length<1)throw g(n);return{kind:"append",array:u(r[0],e),items:r.slice(1).map(o=>u(o,e))}}if(n==="merge")return{kind:"merge",objects:r.map(o=>u(o,e))};throw g(n)}function Br(t,e){let n={};for(let r of pn(t.fields))n[r.key]=u(r.value,e);return{kind:"object",fields:n}}function Ur(t,e){if(t.elements.every(o=>o.kind==="lit"))return{kind:"lit",value:t.elements.map(i=>i.value)};let r=t.elements.map(o=>u(o,e));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function qr(t,e){if(t.length<3)throw g("match");let n=u(t[0],e),r=u(t[t.length-1],e);for(let o=t.length-2;o>=1;o-=1){let i=t[o];if(i.kind!=="arr"||i.elements.length!==2)throw g("match");r={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],e)},then:u(i.elements[1],e),else:r}}return r}function zr(t,e,n){if(e.length<2)throw g(t);let r=e[e.length-1];if(r.kind!=="lit"||r.value!=="first"&&r.value!=="last")throw g(t);let o=e.slice(0,-1).map(i=>Vr(i,n,t));if(o.length===0)throw g(t);return Hr(t,o,r.value)}function Vr(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw g(n);return{label:u(t.elements[0],e),eligible:u(t.elements[1],e),score:u(t.elements[2],e)}}function Hr(t,e,n){let r={kind:"lit",value:null};for(let o=e.length-1;o>=0;o-=1)r={kind:"if",cond:Kr(t,e,n,o),then:e[o].label,else:r};return r}function Kr(t,e,n,r){let o=e[r],i=[];for(let a=0;a<e.length;a+=1){if(a===r)continue;let s=e[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:Wr(t,n,r,a),left:o.score,right:s.score}]})}return i.length===0?o.eligible:{kind:"and",args:[o.eligible,...i]}}function Wr(t,e,n,r){let o=e==="first"?n<r:n>r;return t==="argmax"?o?"gte":"gt":o?"lte":"lt"}function Yr(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function fn(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function Qr(t){if(t==="isNotNull")throw g(t);if(!fn(t))throw g(t);return t}function Xr(t){return t==="min"||t==="max"}function Jr(t){return["and","or","concat","coalesce"].includes(t)}function Zr(t){return["first","last"].includes(t)}function eo(t){return["keys","values","entries"].includes(t)}function to(t){return["filter","find","every","some","map"].includes(t)}function no(t,e){return t.map(n=>ro(n,e))}function ro(t,e){let n=t.condition?u(t.condition,$e(e,"action")):void 0,r=oo(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:r,confidence:t.confidence}}function oo(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:se(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:se(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:se(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,$e(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,$e(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,$e(e,"schema"))}}}function se(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:se(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:se(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(se)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function $e(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function io(t,e){return t.map(n=>Ge(n,e))}function Ge(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:ao(t.path,e),value:r}}function ao(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function I(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:lo(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??z(t.name);case"systemIdent":return so(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return co(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[I(t.object,e),I(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>I(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[I(t.operand,e)]};case"binary":return{kind:"call",fn:po(t.operator),args:[I(t.left,e),I(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[I(t.condition,e),I(t.consequent,e),I(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:I(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>I(n,e))}}}function z(...t){return{kind:"get",path:mn(...t)}}function kt(t,...e){return{kind:"get",base:t,path:mn(...e)}}function be(...t){return{kind:"sys",path:t}}function Be(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function mn(...t){return t.map(e=>({kind:"prop",name:e}))}function so(t,e){return e.resolveSystemIdent?.(t.path)??be(...t.path)}function co(t,e,n){let r=I(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"?kt(r,e):{kind:"field",object:r,property:e}}function lo(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 po(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 go,semanticPathToPatchPath as Eo,sha256Sync as To}from"@manifesto-ai/core";var uo=new Set(["findById","existsById","updateById","removeById"]);function hn(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,fo(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,mo(n)]))}}function fo(t){return{...t,expr:yn(t.expr)}}function mo(t){return{...t,flow:Ue(t.flow),available:t.available?yn(t.available):void 0,dispatchable:t.dispatchable?ho(t.dispatchable):void 0}}function Ue(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>Ue(e))};case"if":return{kind:"if",cond:Nt(t.cond),then:Ue(t.then),else:t.else?Ue(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?Nt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,yo(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?Nt(t.message):void 0};case"call":case"halt":return t}}function yn(t){return u(R(t),mt)}function Nt(t){return u(R(t),ht)}function ho(t){return u(R(t),yt)}function yo(t){return u(R(t),gt)}function R(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?z("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:R(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:R(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:R(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>R(e))};case"call":return uo.has(t.fn)?R(gn(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>R(e))}}}function gn(t,e){let[n,r,o]=e,i=R(n),a=r?R(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=kt(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[gn("findById",e)]}]};case"updateById":{let l=o?R(o):Be({});return{kind:"call",fn:"map",args:[i,{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:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>R(l))}}}function ko(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 No(t){let e=ko(t.domain.name);bo(t.domain,e);let n=So(t.domain,e),r=xo(t.domain,e),o=Co(t.domain,e),i=Oo(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:o,actions:i,meta:{name:t.domain.name}},s=Vo(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function En(t){let e=No(t);return e.schema?{schema:hn(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function bo(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 So(t,e){let n={};for(let r of t.types){let o=Y(r.typeExpr);e.typeDefinitions.set(r.name,o),n[r.name]={name:r.name,definition:o}}return n}function Y(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:Y(t.elementType)};case"recordType":return{kind:"record",key:Y(t.keyType),value:Y(t.valueType)};case"objectType":let e={};for(let r of t.fields)e[r.name]={type:Y(r.typeExpr),optional:r.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(Y)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function xo(t,e){let n={},r={};for(let o of t.members)if(o.kind==="state")for(let i of o.fields){let a=Y(i.typeExpr);r[i.name]=a,e.stateFieldTypes.set(i.name,a);let s=te(i.typeExpr,e);s&&e.stateFieldSpecs.set(i.name,s);let c=vo(i,e);c&&(n[i.name]=c)}return{fields:n,fieldTypes:r}}function vo(t,e){let n=te(t.typeExpr,e);if(!n)return null;let r=t.initializer?ze(t.initializer,e):void 0;return r!==void 0&&xe(r,Y(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:r}}function te(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)?(bt(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):te(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)),o=r.length!==t.types.length,i=[],a=!o;for(let s of r){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:o&&r.length===1?te(r[0],e,n):(bt(e,"E043",`Union type '${ce(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let r=te(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 o of t.fields){let i=te(o.typeExpr,e,n);if(!i)return null;r[o.name]={...i,required:!o.optional}}return{type:"object",required:!0,fields:r}}}}function bt(t,e,n,r){t.diagnostics.push({severity:"error",code:e,message:n,location:r})}function ce(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>ce(e)).join(" | ");case"arrayType":return`Array<${ce(t.elementType)}>`;case"recordType":return`Record<${ce(t.keyType)}, ${ce(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${ce(e.typeExpr)}`).join("; ")} }`}}function ne(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?ne(r,e,[...n,t.name]):null}function Ao(t){return t?.kind==="primitive"&&t.type==="null"||t?.kind==="literal"&&t.value===null}function Tn(t,e){let n=ne(t,e);if(!n||n.kind!=="union")return null;let r=n.types.filter(o=>{let i=ne(o,e);return!Ao(i)});return r.length===1?r[0]:null}function wo(t,e,n){if(e===null||Array.isArray(e)||typeof e!="object")return t;let r=Tn(t,n);return r&&ne(r,n)?.kind==="object"?r:t}function Q(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${Q(t.element)}>`;case"record":return`Record<${Q(t.key)}, ${Q(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${Q(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>Q(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function Se(t,e,n){let r=ne(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(o=>Se(o,r.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(o=>Se(o,r.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let o of Object.keys(t))if(!(o in r.fields))return!1;for(let[o,i]of Object.entries(r.fields)){if(!(o in t)){if(!i.optional)return!1;continue}if(!Se(t[o],i.type,n))return!1}return!0;case"union":return r.types.some(o=>Se(t,o,n));case"ref":return!1}}function xe(t,e,n,r,o){if(t===void 0)return;let i=ne(e,o);if(!i){o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(e)}, got ${JSON.stringify(t)}`,location:r});return}if(i.kind==="union"){if(Se(t,i,o))return;o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(i)}, got ${JSON.stringify(t)}`,location:r});return}switch(i.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(i.type){case"null":t!==null&&ee(o,n,"null",a,r);return;case"string":case"number":case"boolean":typeof t!==i.type&&ee(o,n,i.type,a,r);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&ee(o,n,"object",a,r);return;case"array":Array.isArray(t)||ee(o,n,"array",a,r);return}return}case"literal":Object.is(t,i.value)||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(t)}`,location:r});return;case"array":if(!Array.isArray(t)){ee(o,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,r);return}for(let a=0;a<t.length;a+=1)xe(t[a],i.element,`${n}[${a}]`,r,o);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;ee(o,n,"object",a,r);return}for(let[a,s]of Object.entries(t))xe(s,i.value,`${n}.${a}`,r,o);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;ee(o,n,"object",a,r);return}for(let a of Object.keys(t))a in i.fields||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${Q(i)}`,location:r});for(let[a,s]of Object.entries(i.fields)){if(!(a in t)){s.optional||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:r});continue}xe(t[a],s.type,`${n}.${a}`,r,o)}return;case"ref":o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(e)}, got ${JSON.stringify(t)}`,location:r});return}}function ee(t,e,n,r,o){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${r}`,location:o})}function ze(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>ze(n,e));case"objectLiteral":{let n={};for(let r of t.properties)n[r.key]=ze(r.value,e);return n}default:return}}function Co(t,e){let n=[],r=0;for(let i of t.members)if(i.kind==="computed"){let a=V(i.expression,e),s=Do(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:r}),r+=1}let o={};for(let i of Po(n,e))o[i.name]={deps:i.deps,expr:i.expr};return{fields:o}}function Po(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),r=new Map,o=new Map,i=new Map;for(let c of t)o.set(c.name,[]),i.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),i.set(c.name,l.length);for(let d of l)o.get(d).push(c.name)}let a=t.filter(c=>(i.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 o.get(c)??[]){let d=(i.get(l)??0)-1;i.set(l,d),d===0&&Io(a,l,n)}}if(s.length!==t.length){let c=new Set(s.map(f=>f.name)),l=t.filter(f=>!c.has(f.name)),d=Mo(l[0].name,r),p=d?d.join(" -> "):l.map(f=>f.name).join(", ");return bt(e,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function Io(t,e,n){let r=n.get(e)?.order??Number.MAX_SAFE_INTEGER,o=t.length;for(let i=0;i<t.length;i+=1){let a=n.get(t[i])?.order??Number.MAX_SAFE_INTEGER;if(r<a){o=i;break}}t.splice(o,0,e)}function Mo(t,e){let n=new Set,r=[],o=new Set;function i(a){n.add(a),r.push(a),o.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(o.has(s)){let c=r.indexOf(s);return[...r.slice(c),s]}}else{let c=i(s);if(c)return c}return r.pop(),o.delete(a),null}return i(t)}function Do(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(o=>o.name).join(".")):n(r.base);return;case"field":n(r.object);return;case"call":for(let o of r.args)n(o);return;case"obj":for(let o of r.fields)n(o.value);return;case"arr":for(let o of r.elements)n(o);return}}return n(t),Array.from(e)}function Oo(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 o=new Set;for(let p of r.params)o.add(p.name);e.actionParams.set(r.name,o);let i=r.params.map(p=>p.name),a=kn(r.body,e),s,c;if(r.params.length>0){let p={},f={};for(let m of r.params){let A=te(m.typeExpr,e);A&&(p[m.name]=structuredClone(A),f[m.name]={type:Y(m.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:f}}let l;r.available&&(l=V(r.available,e));let d;r.dispatchable&&(d=V(r.dispatchable,e,{preferActionParams:!0})),n[r.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},e.currentAction=null}return n}function kn(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Ve(t[0],e):{kind:"seq",steps:t.map(n=>Ve(n,e))}}function Ve(t,e){switch(t.kind){case"when":return Ro(t,e);case"once":return Lo(t,e);case"onceIntent":return Fo(t,e);case"patch":return jo(t,e);case"effect":return _o(t,e);case"fail":return Go(t,e);case"stop":return Bo(t,e);case"include":return{kind:"seq",steps:[]}}}function Ro(t,e){let n=V(t.condition,e),r=kn(t.body,e);return{kind:"if",cond:n,then:r}}function Lo(t,e){let n=St(t.marker,e),r=be("meta","intentId"),o=He("neq",[z(...Nn(n)),r]);if(t.condition){let s=V(t.condition,e);o=He("and",[o,s])}let i={kind:"patch",op:"set",path:xt(n),value:r},a=t.body.map(s=>Ve(s,e));return{kind:"if",cond:o,then:{kind:"seq",steps:[i,...a]}}}function Fo(t,e){let n=e.currentAction??"unknown",r=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,r+1);let o=To(`${n}:${r}:intent`),i=`$mel.guards.intent.${o}`,a=be("meta","intentId"),s=He("neq",[z(...Nn(i)),a]);if(t.condition){let d=V(t.condition,e);s=He("and",[s,d])}let c={kind:"patch",op:"merge",path:xt("$mel.guards.intent"),value:Be({[o]:a})},l=t.body.map(d=>Ve(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function jo(t,e){let n=St(t.path,e),r={kind:"patch",op:t.op,path:xt(n)};if(t.value){let o=V(t.value,e);if(r.value=o,t.op==="set"){let i=t.path.segments[0];if(i.kind==="propertySegment"){let a=e.stateFieldTypes.get(i.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?ne(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let f=Tn(s,e);if(!f){s=null;break}s=f,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=$o(t.value,e);if(l!==void 0){let d=t.path.segments.map(f=>f.kind==="propertySegment"?f.name:"[*]").join("."),p=wo(s,l,e);xe(l,p,d,t.location,e)}}}}}}return r}function _o(t,e){let n={};for(let r of t.args)r.isPath?n[r.name]={kind:"lit",value:St(r.value,e)}:n[r.name]=V(r.value,e);return{kind:"effect",type:t.effectType,params:n}}function $o(t,e){return ze(t,e)}function Go(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=V(t.message,e)),n}function Bo(t,e){return{kind:"halt",reason:t.reason}}function Uo(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function qe(...t){return t.map(Uo).join(".")}function St(t,e){let n=[];for(let o of t.segments)if(o.kind==="propertySegment")n.push(o.name);else{let i=V(o.index,e);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let r=n[0];return e.stateFields.has(r)?qe(...n):e.computedFields.has(r)?qe(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(r)?`input.${qe(...n)}`:qe(...n)}function xt(t){return Eo(t)}function He(t,e){return{kind:"call",fn:t,args:e}}function Nn(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function V(t,e,n={}){return I(t,{resolveIdentifier:r=>qo(r,e,n),resolveSystemIdent:r=>zo(r,e)})}function qo(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?z("input",t):e.stateFields.has(t)||e.computedFields.has(t)?z(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?z("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}}}),z(t))}function zo(t,e){let[n,...r]=t;switch(n){case"system":case"meta":case"input":return be(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 Vo(t){return go(t)}var Ho="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",Ko="Action-parameter annotations are not part of the current MEL syntax.",bn="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",Sn="Annotation payload nesting exceeds the current MEL limit of 2 levels.",Wo="Annotation target does not map to the emitted DomainSchema.",xn=2;function vn(t,e){let n=[],r=new Map,o=t.domain;le(o.annotations,`domain:${o.name}`,n,r);for(let a of o.types)le(a.annotations,`type:${a.name}`,n,r),de(a.typeExpr,a.name,0,n,r);for(let a of o.members)switch(a.kind){case"state":for(let s of a.fields)le(s.annotations,`state_field:${s.name}`,n,r),re(s.typeExpr,n);break;case"computed":le(a.annotations,`computed:${a.name}`,n,r);break;case"action":le(a.annotations,`action:${a.name}`,n,r),Yo(a,n);for(let s of a.params)re(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...r.keys()].sort()){if(!Jo(e,a)){n.push(D("E057",Wo,Zo(t,a)??o.location));continue}let s=r.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>Xo(c))))}return{annotations:Object.freeze({schemaHash:e.hash,entries:Object.freeze(i)}),diagnostics:n}}function le(t,e,n,r){if(!t||t.length===0)return;let o=[];for(let a of t){let s=a.payload===void 0?{ok:!0,value:void 0}:vt(a.payload,0,n);s.ok&&o.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(o.length===0)return;let i=r.get(e);if(i){i.push(...o);return}r.set(e,o)}function de(t,e,n,r,o){switch(t.kind){case"objectType":for(let i of t.fields)i.annotations?.length&&(n===0?le(i.annotations,`type_field:${e}.${i.name}`,r,o):An(i.annotations,r)),de(i.typeExpr,e,n+1,r,o);return;case"arrayType":de(t.elementType,e,n,r,o);return;case"recordType":de(t.keyType,e,n,r,o),de(t.valueType,e,n,r,o);return;case"unionType":for(let i of t.types)de(i,e,n,r,o);return;case"simpleType":case"literalType":return}}function re(t,e){switch(t.kind){case"objectType":for(let n of t.fields)An(n.annotations,e),re(n.typeExpr,e);return;case"arrayType":re(t.elementType,e);return;case"recordType":re(t.keyType,e),re(t.valueType,e);return;case"unionType":for(let n of t.types)re(n,e);return;case"simpleType":case"literalType":return}}function Yo(t,e){for(let n of t.params)Qo(n,e)}function Qo(t,e){if(t.annotations)for(let n of t.annotations)e.push(D("E054",Ko,n.location))}function An(t,e){if(t)for(let n of t)e.push(D("E053",Ho,n.location))}function vt(t,e,n){switch(t.kind){case"literal":return t.literalType==="string"||t.literalType==="number"||t.literalType==="boolean"||t.literalType==="null"?{ok:!0,value:t.value}:(n.push(D("E055",bn,t.location)),{ok:!1});case"arrayLiteral":{if(e+1>xn)return n.push(D("E056",Sn,t.location)),{ok:!1};let r=[];for(let o of t.elements){let i=vt(o,e+1,n);if(!i.ok)return{ok:!1};r.push(i.value)}return{ok:!0,value:r}}case"objectLiteral":{if(e+1>xn)return n.push(D("E056",Sn,t.location)),{ok:!1};let r={};for(let o of t.properties){let i=vt(o.value,e+1,n);if(!i.ok)return{ok:!1};r[o.key]=i.value}return{ok:!0,value:r}}default:return n.push(D("E055",bn,t.location)),{ok:!1}}}function Xo(t){return t.payload===void 0?Object.freeze({tag:t.tag}):Object.freeze({tag:t.tag,payload:At(t.payload)})}function At(t){if(Array.isArray(t))return Object.freeze(t.map(e=>At(e)));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=At(r);return Object.freeze(e)}return t}function Jo(t,e){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.meta?.name===o||t.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(t.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,o);case"computed":return Object.hasOwn(t.computed.fields,o);case"action":return Object.hasOwn(t.actions,o);default:return!1}}function Zo(t,e){let n=e.indexOf(":");if(n<0)return null;let r=e.slice(0,n),o=e.slice(n+1),i=t.domain;if(r==="domain"&&i.name===o)return i.location;if(r==="type")return i.types.find(a=>a.name===o)?.location??null;if(r==="type_field"){let a=o.indexOf(".");if(a<=0)return null;let s=o.slice(0,a),c=o.slice(a+1),l=i.types.find(d=>d.name===s);return!l||l.typeExpr.kind!=="objectType"?l?.location??null:l.typeExpr.fields.find(d=>d.name===c)?.location??l.location}if(r==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===o);if(s)return s.location}return null}return r==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===o)?.location??null:r==="action"?i.members.find(a=>a.kind==="action"&&a.name===o)?.location??null:null}var wt=16;function k(t){return structuredClone(t)}function C(t,e,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;e.has(i)||(e.add(i),t.push(D(n,r,o)))}function ei(t){let e=new Map,n=new Set,r=new Map,o=new Set,i=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":o.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:r,actionNames:o,flows:i}}function ti(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function ni(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function ri(t,e,n,r){let o=new Map;for(let i of e.flows.values()){o.set(i.name,[]),e.actionNames.has(i.name)&&C(n,r,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&C(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=ti(i);for(let s of i.body)ii(s,i.name,a,e,n,r,o.get(i.name))}for(let i of t.members)if(i.kind==="action"){let a=ni(i);for(let s of i.body)oi(s,a,e,n,r)}return o}function oi(t,e,n,r,o){switch(t.kind){case"include":We(t,e,n,r,o);break;case"when":for(let i of t.body)ue(i,e,n,r,o);break;case"once":for(let i of t.body)ue(i,e,n,r,o);break;case"onceIntent":for(let i of t.body)ue(i,e,n,r,o);break;case"fail":case"stop":break}}function ue(t,e,n,r,o){switch(t.kind){case"include":C(r,o,"E016","include is only allowed at action or flow body top-level.",t.location),We(t,e,n,r,o);break;case"when":for(let i of t.body)ue(i,e,n,r,o);break;case"once":for(let i of t.body)ue(i,e,n,r,o);break;case"onceIntent":for(let i of t.body)ue(i,e,n,r,o);break;case"patch":case"effect":case"fail":case"stop":break}}function ii(t,e,n,r,o,i,a){switch(t.kind){case"include":We(t,n,r,o,i)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Ke(s,e,n,r,o,i);break;case"once":C(o,i,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":C(o,i,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":C(o,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":C(o,i,"E020","effect is not allowed in flow bodies.",t.location);break}}function Ke(t,e,n,r,o,i){switch(t.kind){case"include":C(o,i,"E016","include is only allowed at action or flow body top-level.",t.location),We(t,n,r,o,i);break;case"when":for(let a of t.body)Ke(a,e,n,r,o,i);break;case"once":C(o,i,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Ke(a,e,n,r,o,i);break;case"onceIntent":C(o,i,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Ke(a,e,n,r,o,i);break;case"patch":C(o,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":C(o,i,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function We(t,e,n,r,o){let i=n.flows.get(t.flowName);if(!i)return C(r,o,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==i.params.length)return C(r,o,"E023",`include '${t.flowName}' expected ${i.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=i.params[a],l=ve(s,e,n);if(!l)continue;pe(l,c.typeExpr,n)===!1&&C(r,o,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function ai(t,e,n,r){function o(i,a,s){s.add(i);for(let c of t.get(i)??[]){if(a+1>wt){C(n,r,"E014",`Include expansion depth exceeds limit (${wt}).`,c.location);continue}if(s.has(c.target)){C(n,r,"E013","Circular include detected.",c.location);continue}o(c.target,a+1,new Set(s))}}for(let i of e.flows.keys())o(i,1,new Set)}function O(t,e){switch(t.kind){case"identifier":return e.has(t.name)?k(e.get(t.name)):k(t);case"systemIdent":case"literal":case"iterationVar":return k(t);case"functionCall":return{...k(t),args:t.args.map(n=>O(n,e))};case"binary":return{...k(t),left:O(t.left,e),right:O(t.right,e)};case"unary":return{...k(t),operand:O(t.operand,e)};case"ternary":return{...k(t),condition:O(t.condition,e),consequent:O(t.consequent,e),alternate:O(t.alternate,e)};case"propertyAccess":return{...k(t),object:O(t.object,e)};case"indexAccess":return{...k(t),object:O(t.object,e),index:O(t.index,e)};case"objectLiteral":return{...k(t),properties:t.properties.map(n=>({...k(n),value:O(n.value,e)}))};case"arrayLiteral":return{...k(t),elements:t.elements.map(n=>O(n,e))}}}function si(t,e){switch(t.kind){case"when":return[wn(t,e)];case"fail":return[{...k(t),message:t.message?O(t.message,e):void 0}];case"stop":return[k(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function wn(t,e){return{...k(t),condition:O(t.condition,e),body:t.body.flatMap(n=>si(n,e))}}function ci(t,e,n){let r=new Map;for(let o=0;o<t.params.length;o+=1)r.set(t.params[o].name,O(e.args[o],n));return r}function li(t,e,n,r,o){switch(t.kind){case"when":return[wn(t,n)];case"include":return Cn(t,e,n,r,o);case"once":case"onceIntent":case"patch":case"effect":return[]}}function Cn(t,e,n,r,o){let i=e.flows.get(t.flowName);if(!i||t.args.length!==i.params.length||r>wt||o.includes(t.flowName))return[];let a=ci(i,t,n),s=[...o,t.flowName];return i.body.flatMap(c=>li(c,e,a,r+1,s))}function fe(t){switch(t.kind){case"when":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"once":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"onceIntent":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[k(t)]}}function di(t,e,n){switch(t.kind){case"include":return Cn(t,e,new Map,n,[]);case"when":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"once":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"onceIntent":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"fail":case"stop":return[k(t)]}}function pi(t,e){let n=[];for(let r of t.domain.members)switch(r.kind){case"state":case"computed":n.push(k(r));break;case"action":n.push({...k(r),body:r.body.flatMap(o=>di(o,e,1))});break;case"flow":break}return{...k(t),domain:{...k(t.domain),types:t.domain.types.map(r=>k(r)),members:n}}}function ve(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=ve(t.object,e,n);return Pn(r,t.property,n)}case"indexAccess":{let r=ve(t.object,e,n);return In(r,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let o=ve(r.value,e,n);return o?{kind:"typeField",name:r.key,typeExpr:o,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let r=ve(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 Ae(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),Ae(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Pn(t,e,n){let r=Ae(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(i=>i.name===e)?.typeExpr??null;if(r.kind==="unionType")for(let o of r.types){if(o.kind==="simpleType"&&o.name==="null")continue;let i=Pn(o,e,n);if(i)return i}return null}function In(t,e){let n=Ae(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 o=In(r,e);if(o)return o}return null}function pe(t,e,n){let r=Ae(t,n),o=Ae(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=o.types.map(a=>pe(r,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(r.kind==="unionType"){let i=r.types.map(a=>pe(a,o,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:pe(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=pe(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:pe(r.valueType,o.valueType,n):null}function Mn(t){let e=ei(t.domain),n=[],r=new Set,o=ri(t.domain,e,n,r);return ai(o,e,n,r),{program:pi(t,e),diagnostics:n}}var ui=new Set(["$item","$index","$array"]);function Rn(t){let e=Object.keys(t.state.fields).filter(d=>!d.startsWith("$")),n=fi(t),r=new Set(n),o=new Set(e),i=Object.keys(t.actions),a=[...e.map(d=>({id:Ct(d),kind:"state",name:d})),...n.map(d=>({id:Pt(d),kind:"computed",name:d})),...i.map(d=>({id:On(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,f)=>{if(!d||!p)return;let m=`${d}|${f}|${p}`;s.has(m)||(s.add(m),c.push({from:d,to:p,relation:f}))};for(let d of n){let p=t.computed.fields[d];if(p)for(let f of p.deps)l(Dn(f,t,r,o),Pt(d),"feeds")}for(let d of i){let p=t.actions[d],f=On(d);for(let m of mi(p.flow,t))o.has(m)&&l(f,Ct(m),"mutates");if(p.available)for(let m of $n(p.available))l(Dn(m,t,r,o),f,"unlocks")}return gi({nodes:a,edges:c})}function fi(t){let e=t.computed.fields,n=new Map,r=(o,i)=>{let a=n.get(o);if(a!==void 0)return a;if(i.has(o))return!1;i.add(o);let s=e[o];if(!s)return i.delete(o),n.set(o,!0),!0;for(let c of $n(s.expr)){if(_n(c))return i.delete(o),n.set(o,!1),!1;let l=Ln(c,e);if(l!==null&&!r(l,i))return i.delete(o),n.set(o,!1),!1}return i.delete(o),n.set(o,!0),!0};return Object.keys(e).filter(o=>r(o,new Set))}function mi(t,e){let n=new Set,r=(o,i)=>{if(o)switch(o.kind){case"seq":o.steps.forEach(a=>r(a,i));return;case"if":r(o.then,i),r(o.else,i);return;case"patch":{let a=hi(o.path);a&&n.add(a);return}case"effect":{let a=yi(o.params.into);a&&n.add(a);return}case"call":{if(i.has(o.flow))return;let a=e.actions[o.flow];if(!a)return;let s=new Set(i);s.add(o.flow),r(a.flow,s);return}case"halt":case"fail":return}};return r(t,new Set),[...n]}function hi(t){let[e]=t;return!e||e.kind!=="prop"||e.name.startsWith("$")?null:e.name}function yi(t){return typeof t!="object"||t===null||t.kind!=="lit"||typeof t.value!="string"?null:Fn(t.value)}function Dn(t,e,n,r){let o=Ln(t,e.computed.fields);if(o!==null&&n.has(o))return Pt(o);if(_n(t))return null;let i=Fn(t);return!i||!r.has(i)?null:Ct(i)}function Ln(t,e){if(Object.prototype.hasOwnProperty.call(e,t))return t;if(!t.startsWith("computed."))return null;let n=t.slice(9);return Object.prototype.hasOwnProperty.call(e,n)?n:null}function Fn(t){let e=jn(t),n=e.startsWith("data.")?e.slice(5):e,r=/^([^.[\]]+)/.exec(n);if(!r)return null;let[o]=r.slice(1);return!o||o.startsWith("$")?null:o}function jn(t){return t.startsWith("/")?t.slice(1).replace(/\//g,"."):t}function _n(t){let e=jn(t),n=e.startsWith("data.")?e.slice(5):e,o=/^([^.[\]]+)/.exec(n)?.[1]??"";return o.startsWith("$")?!ui.has(o):!1}function $n(t){let e=[],n=new WeakSet,r=o=>{if(o==null)return;if(Array.isArray(o)){o.forEach(r);return}if(typeof o!="object")return;let i=o;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){e.push(i.path);return}for(let a of Object.values(i))r(a)}};return r(t),e}function Ct(t){return`state:${t}`}function Pt(t){return`computed:${t}`}function On(t){return`action:${t}`}function gi(t){return Object.freeze({nodes:Object.freeze(t.nodes.map(e=>Object.freeze(e))),edges:Object.freeze([...t.edges].sort(Ei).map(e=>Object.freeze(e)))})}function Ei(t,e){return t.from.localeCompare(e.from)||t.to.localeCompare(e.to)||t.relation.localeCompare(e.relation)}var Ti="Source-map target does not map to the emitted DomainSchema.",ki="Source-map entry missing for emitted DomainSchema target.",Ni=new TextEncoder;function zn(t){return Object.freeze({coordinateUnit:"utf16",compilerVersion:t,emissionOptionsFingerprint:"default"})}function Vn(t,e,n,r){let o=[],i=new Map,a=t.domain,s=xi(e,r.coordinateUnit);i.set(`domain:${a.name}`,ye({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,ye({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),me(l.typeExpr,l.name,0,i,s);for(let l of a.members)switch(l.kind){case"state":for(let d of l.fields)i.set(`state_field:${d.name}`,ye({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,ye({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,ye({target:{kind:"action",action:{name:l.name}},span:s(l.location)}));break;case"flow":break}let c={};for(let l of[...i.keys()].sort()){if(!Si(n,l)){o.push(D("E058",Ti,Gn(t,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of bi(t,n))Object.hasOwn(c,l)||o.push(D("E058",ki,Gn(t,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:Un(e),format:"manifesto/source-map-v1",coordinateUnit:r.coordinateUnit,emissionFingerprint:Un(`${r.coordinateUnit}\0${r.compilerVersion}\0${r.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:o}}function me(t,e,n,r,o){switch(t.kind){case"objectType":for(let i of t.fields)n===0&&r.set(`type_field:${e}.${i.name}`,ye({target:{kind:"type_field",type:{name:e},field:{name:i.name}},span:o(i.location)})),me(i.typeExpr,e,n+1,r,o);return;case"arrayType":me(t.elementType,e,n+1,r,o);return;case"recordType":me(t.keyType,e,n+1,r,o),me(t.valueType,e,n+1,r,o);return;case"unionType":for(let i of t.types)me(i,e,n+1,r,o);return;case"simpleType":case"literalType":return}}function bi(t,e){let n=new Set;n.add(`domain:${t.domain.name}`);for(let[r,o]of Object.entries(e.types))if(n.add(`type:${r}`),o.definition.kind==="object")for(let i of Object.keys(o.definition.fields))n.add(`type_field:${r}.${i}`);for(let r of Object.keys(e.state.fields))n.add(`state_field:${r}`);for(let r of Object.keys(e.computed.fields))n.add(`computed:${r}`);for(let r of Object.keys(e.actions))n.add(`action:${r}`);return[...n].sort()}function Si(t,e){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.meta?.name===o||t.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(t.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,o);case"computed":return Object.hasOwn(t.computed.fields,o);case"action":return Object.hasOwn(t.actions,o);default:return!1}}function Gn(t,e){let n=e.indexOf(":");if(n<0)return null;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.domain.name===o?t.domain.location:null;case"type":return t.domain.types.find(i=>i.name===o)?.location??null;case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return null;let a=o.slice(0,i),s=o.slice(i+1),c=t.domain.types.find(l=>l.name===a);return c?he(c.typeExpr,s,0):null}case"state_field":for(let i of t.domain.members){if(i.kind!=="state")continue;let a=i.fields.find(s=>s.name===o);if(a)return a.location}return null;case"computed":return t.domain.members.find(i=>i.kind==="computed"&&i.name===o)?.location??null;case"action":return t.domain.members.find(i=>i.kind==="action"&&i.name===o)?.location??null;default:return null}}function he(t,e,n){switch(t.kind){case"objectType":for(let r of t.fields){if(n===0&&r.name===e)return r.location;let o=he(r.typeExpr,e,n+1);if(o)return o}return null;case"arrayType":return he(t.elementType,e,n+1);case"recordType":return he(t.keyType,e,n+1)??he(t.valueType,e,n+1);case"unionType":for(let r of t.types){let o=he(r,e,n+1);if(o)return o}return null;case"simpleType":case"literalType":return null}}function xi(t,e){return e==="utf16"?n=>vi(n):n=>Ai(n,t)}function vi(t){return Object.freeze({start:Object.freeze({line:t.start.line,column:t.start.column}),end:Object.freeze({line:t.end.line,column:t.end.column})})}function Ai(t,e){return Object.freeze({start:Bn(t.start,e),end:Bn(t.end,e)})}function Bn(t,e){let n=qn(e.slice(0,t.offset)),r=t.offset-(t.column-1),o=qn(e.slice(0,r));return Object.freeze({line:t.line,column:n-o+1})}function ye(t){return Object.freeze({target:wi(t.target),span:Object.freeze({start:Object.freeze({...t.span.start}),end:Object.freeze({...t.span.end})})})}function wi(t){switch(t.kind){case"domain":return Object.freeze({kind:t.kind,domain:Object.freeze({...t.domain})});case"type":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type})});case"type_field":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type}),field:Object.freeze({...t.field})});case"state_field":return Object.freeze({kind:t.kind,field:Object.freeze({...t.field})});case"computed":return Object.freeze({kind:t.kind,computed:Object.freeze({...t.computed})});case"action":return Object.freeze({kind:t.kind,action:Object.freeze({...t.action})})}}function Un(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return`fnv1a32:${e.toString(16).padStart(8,"0")}`}function qn(t){return Ni.encode(t).length}import{sha256Sync as Ye}from"@manifesto-ai/core";function Hn(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function ge(t){return I(t)}var Qe=class{constructor(e){this.deps=e;this.exprValidator=new Mt(e.mapLocation)}conditionComposer=new It;exprValidator;collect(e,n,r,o){return this.collectPatchStatements(e,n,r,o)}collectPatchStatements(e,n,r,o){let i=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:o});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=o;try{s=this.conditionComposer.and(o,this.deps.toMelExpr(a.condition))}catch(f){n.push({severity:"error",code:"E_LOWER",message:f.message,location:this.deps.mapLocation(a.condition.location)})}let c=Ye(`${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=we(l),p=this.collectPatchStatements(a.body,n,r,void 0).map(f=>({patch:f.patch,condition:this.conditionComposer.and(d,f.condition)}));i.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=o,c=we(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($){n.push({severity:"error",code:"E_LOWER",message:$.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(o,p);let f=Ye(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let m={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:f,location:d}],location:d},A=we(m),b=this.collectPatchStatements(a.body,n,r,A);i.push({patch:{kind:"patch",op:"set",path:m,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:A},...b,{patch:{kind:"patch",op:"unset",path:m,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Ye(`${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=we(c),d=Ye(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let p=a.location,m={kind:"call",fn:"neq",args:[we({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{m=this.conditionComposer.and(m,this.deps.toMelExpr(a.condition))??m}catch(H){n.push({severity:"error",code:"E_LOWER",message:H.message,location:this.deps.mapLocation(a.condition.location)})}}let A=this.conditionComposer.and(o,m),b={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},$=this.collectPatchStatements(a.body,n,r,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:A},{patch:{kind:"patch",op:"merge",path:b,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},...$,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:A});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 i}};function Kn(t){return{op:t.patch.op,path:Ci(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:ge(t.patch.value)}:void 0}}function we(t){let e=t.segments,n;for(let r of e){if(r.kind==="propertySegment"){let o={kind:"prop",name:r.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:r.name}]}:n={kind:"get",path:[o]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,ge(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function Ci(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:ge(e.index)})}var It=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},Mt=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,o){let i=G(e,new Map,this.symbols),a=G(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||o.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(r)})}};function Yn(t){let e=[],n=0;for(let r of t)e.push(n),n+=r.length+1;return e}function Qn(t,e){return n=>Xn(n,t,e)}function Dt(t,e,n){return t.map(r=>Pi(r,e,n))}function Pi(t,e,n){return{...t,location:Xn(t.location,e,n)}}function Xn(t,e,n){return{...t,start:Wn(t.start,e,n),end:Wn(t.end,e,n)}}function Wn(t,e,n){let r=t.line-3,o=e.length,i=Math.min(Math.max(r,1),o),a=n[i-1]??0,s=e[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var Ce="__compileMelPatch",Mi="__patchDomain",Di=" ";function Jn(t,e){let n=[],r=[],o=[],i=t.split(`
9
+ `),a=Yn(i),s=Qn(i,a),c=Oi(t,Ce),l=performance.now(),d;try{let x=Pe(c);d=x.tokens;let M=Dt(x.diagnostics.filter(J=>J.severity==="error"),i,a);if(M.length>0)return o.push(...M),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:o}}catch(x){return o.push({severity:"error",code:"E_LEX",message:x.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:o}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),f;try{let x=Ie(d),M=Dt(x.diagnostics,i,a),J=M.filter(Xe=>Xe.severity==="error"),j=M.filter(Xe=>Xe.severity!=="error");if(J.length>0)return o.push(...J),r.push(...j),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};if(!x.program)return o.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(...j),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};f=x.program,r.push(...j)}catch(x){return o.push({severity:"error",code:"E_PARSE",message:x.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:o}}n.push({phase:"parse",durationMs:performance.now()-p});let m=performance.now(),A={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},b=f.domain.members.find(x=>x.kind==="action"&&x.name===Ce);if(!b)return o.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${Ce}' 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()-m}),{ops:[],trace:n,warnings:r,errors:o};let $=i.length+3+2;if(b.location.end.line!==$)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ce}'.`,location:s(b.location)}),n.push({phase:"analyze",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:r,errors:o};let[H]=b.body;if(!H||H.kind!=="when"||!Hn(H.condition)||b.body.length!==1)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ce}'.`,location:s(b.location)}),n.push({phase:"analyze",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:r,errors:o};let E=new Qe({mapLocation:s,toMelExpr:ge}).collect(H.body,o,A,void 0);if(o.length===0&&t.trim()!==""&&E.length===0&&o.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(H.location)}),n.push({phase:"analyze",durationMs:performance.now()-m,details:{count:E.length}}),o.length>0)return{ops:[],trace:n,warnings:r,errors:o};let L=performance.now(),X={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},K=[];for(let x of E)try{let M=Kn(x);K.push(Ge(M,X))}catch(M){M instanceof _?o.push({severity:"error",code:M.code,message:M.message,location:s(x.patch.location)}):M instanceof Error?o.push({severity:"error",code:"E_LOWER",message:M.message,location:s(x.patch.location)}):o.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-L,details:{count:K.length}}),o.length>0?{ops:[],trace:n,warnings:r,errors:o}:{ops:K,trace:n,warnings:r,errors:o}}function Oi(t,e){let n=t.split(`
10
+ `).map(r=>`${Di}${r}`).join(`
11
+ `);return[`domain ${Mi} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
+ `)}var Ri="3.5.0";function Li(t,e){let n=Zn(t,e);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function Fi(t,e){let n=Zn(t,e);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:ji(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function Zn(t,e){let n=[],r=[],o=[],i=performance.now(),a;try{let E=Pe(t);a=E.tokens;let L=E.diagnostics.filter(K=>K.severity==="error");if(L.length>0)return o.push(...L),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o};let X=E.diagnostics.filter(K=>K.severity==="warning");r.push(...X)}catch(E){let L=E;return o.push({severity:"error",code:"E_LEX",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let E=Ie(a),L=E.diagnostics.filter(X=>X.severity==="error");if(L.length>0)return o.push(...L),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};c=E.program}catch(E){let L=E;return o.push({severity:"error",code:"E_PARSE",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Mn(c),p=d.diagnostics.filter(E=>E.severity==="error"),f=d.diagnostics.filter(E=>E.severity==="warning"),m=Ut(d.program),A=dn(d.program),b=[...p,...m.diagnostics.filter(E=>E.severity==="error"),...A.diagnostics.filter(E=>E.severity==="error")],$=[...f,...m.diagnostics.filter(E=>E.severity==="warning"),...A.diagnostics.filter(E=>E.severity==="warning")];if(r.push(...$),n.push({phase:"analyze",durationMs:performance.now()-l}),b.length>0)return o.push(...b),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};let H=performance.now(),oe=En(d.program);n.push({phase:"generate",durationMs:performance.now()-H});for(let E of oe.diagnostics)E.severity==="warning"?r.push(E):o.push(E);if(oe.schema){let E=vn(d.program,oe.schema),L=E.diagnostics.filter(j=>j.severity==="warning"),X=E.diagnostics.filter(j=>j.severity==="error");if(r.push(...L),o.push(...X),X.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};let K=zn(Ri),x=Vn(d.program,t,oe.schema,K),M=x.diagnostics.filter(j=>j.severity==="warning"),J=x.diagnostics.filter(j=>j.severity==="error");return r.push(...M),o.push(...J),J.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)}:{program:d.program,schema:oe.schema,annotations:E.annotations,sourceMap:x.sourceMap,trace:n,warnings:r,errors:Ee(o)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)}}function ji(t,e,n){return Object.freeze({schema:t,graph:Rt(Rn(t)),annotations:e,sourceMap:n})}function Rt(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let e of t)Rt(e);return Object.freeze(t)}for(let e of Object.values(t))Rt(e);return Object.freeze(t)}var Ot=10;function Ee(t){if(t.length<=Ot)return t;let e=t.slice(0,Ot);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-Ot} 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 _i(t,e){return Jn(t,e)}export{Je as a,er as b,$i as c,Lt as d,Ft as e,Ze as f,jt as g,_t as h,Bi as i,h as j,et as k,Pe as l,Qi as m,Xi as n,$t as o,tt as p,Gt as q,Zi as r,ea as s,Bt as t,nt as u,Ie as v,Me as w,rt as x,Ut as y,D as z,qt as A,da as B,tr as C,pa as D,ua as E,ft as F,dn as G,mt as H,ht as I,yt as J,gt as K,Or as L,_ as M,je as N,g as O,_e as P,Et as Q,Rr as R,Tt as S,Lr as T,u as U,no as V,io as W,Ge as X,No as Y,En as Z,vn as _,Mn as $,Rn as aa,zn as ba,Vn as ca,Li as da,Fi as ea,_i as fa};
@@ -1,3 +1,3 @@
1
- import{a as f,b as g}from"./chunk-E4EHOM7R.js";import{da as d}from"./chunk-YIGJ5PGV.js";import{createHash as p}from"crypto";import*as i from"path";import{createUnplugin as h}from"unplugin";var M=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function b(e,t){return e.lastIndex=0,e.test(t)}function y(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)?w(t):n.split(i.sep).join("/")}function w(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=p("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 E(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(!M.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 O=h((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=E(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return b(t,l(r))},async transform(r,s){let m=l(s),a=d(r,{mode:"domain"});if(a.errors.length>0){let u=a.errors.map(f).join(`
1
+ import{a as f,b as g}from"./chunk-2ZRNXFBQ.js";import{da as d}from"./chunk-O654OLQV.js";import{createHash as p}from"crypto";import*as i from"path";import{createUnplugin as h}from"unplugin";var M=new Set(["transform","build","both"]);function l(e){return e.split("?",1)[0]}function b(e,t){return e.lastIndex=0,e.test(t)}function y(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)?w(t):n.split(i.sep).join("/")}function w(e){let t=i.posix.basename(e)||"domain.mel",n=i.posix.extname(t),o=t.slice(0,t.length-n.length)||"domain",r=p("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 E(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(!M.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 O=h((e={})=>{let t=e.include??/\.mel$/,n=new Map,o=E(e.codegen);return{name:"manifesto:mel",enforce:"pre",transformInclude(r){return b(t,l(r))},async transform(r,s){let m=l(s),a=d(r,{mode:"domain"});if(a.errors.length>0){let u=a.errors.map(f).join(`
2
2
  `);throw new Error(`MEL compilation failed for ${m}
3
3
  ${u}`)}if(!a.schema)throw new Error(`MEL compilation produced no schema for ${m}`);let c=y(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)),g(a.schema)},async buildEnd(){if(!(!o||n.size===0))for(let[r,s]of n)await o.emit({schema:s,sourceId:r})}}});export{O as a};
package/dist/esbuild.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
1
+ import{a as e}from"./chunk-Q56VWGSA.js";import"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-YIGJ5PGV.js";var Y={E001:{code:"E001",message:"$system.* cannot be used in computed expressions (non-deterministic)",category:"semantic"},E002:{code:"E002",message:"$system.* cannot be used in state initializers",category:"semantic"},E003:{code:"E003",message:"Invalid $system reference",category:"semantic"},E004:{code:"E004",message:"Identifier starts with reserved prefix '__sys__'",category:"syntax"},E005:{code:"E005",message:"available expression must be pure (no Effects, no $system.*)",category:"semantic"},E006:{code:"E006",message:"fail must be inside a guard (when, once, or onceIntent)",category:"semantic"},E007:{code:"E007",message:"stop must be inside a guard (when, once, or onceIntent)",category:"semantic"},E008:{code:"E008",message:"stop message suggests waiting/pending - use 'Already processed' style instead",category:"semantic"},E009:{code:"E009",message:"Primitive aggregation (sum, min, max) only allowed in computed",category:"semantic"},E010:{code:"E010",message:"Primitive aggregation does not allow composition - use direct reference only",category:"semantic"},E011:{code:"E011",message:"reduce/fold/scan is forbidden - use sum, min, max for aggregation",category:"semantic"},E013:{code:"E013",message:"Circular include detected",category:"semantic"},E014:{code:"E014",message:"Include expansion depth exceeds limit",category:"semantic"},E015:{code:"E015",message:"Include target is not a declared flow",category:"semantic"},E016:{code:"E016",message:"Include not allowed in InnerStmt position",category:"semantic"},E017:{code:"E017",message:"once() not allowed in flow",category:"semantic"},E018:{code:"E018",message:"onceIntent not allowed in flow",category:"semantic"},E019:{code:"E019",message:"patch not allowed in flow",category:"semantic"},E020:{code:"E020",message:"effect not allowed in flow",category:"semantic"},E021:{code:"E021",message:"Flow parameter name conflicts with top-level identifier",category:"semantic"},E022:{code:"E022",message:"Flow and action share the same name",category:"semantic"},E023:{code:"E023",message:"Wrong number of arguments for included flow",category:"semantic"},E024:{code:"E024",message:"Include argument type mismatch",category:"type"},E030:{code:"E030",message:"Collection element type does not have an 'id' field",category:"type"},E030a:{code:"E030a",message:"Collection element 'id' field is not a primitive type",category:"type"},E030b:{code:"E030b",message:"Duplicate '.id' values detected in state initializer",category:"type"},E031:{code:"E031",message:"updateById/removeById not allowed in this context",category:"semantic"},E032:{code:"E032",message:"Nested transform primitive",category:"semantic"},E033:{code:"E033",message:"Transform primitive collection argument is not a state path",category:"semantic"},E034:{code:"E034",message:"Transform primitive in guard condition",category:"semantic"},E035:{code:"E035",message:"Transform primitive in available condition",category:"semantic"},E040:{code:"E040",message:"Circular computed dependency",category:"semantic"},E041:{code:"E041",message:"Computed references undeclared identifier",category:"semantic"},E042:{code:"E042",message:"State initializer references non-constant value",category:"semantic"},E043:{code:"E043",message:"Non-trivial union type cannot be lowered to FieldSpec",category:"type"},E044:{code:"E044",message:"Recursive named type cannot be lowered to FieldSpec",category:"type"},E045:{code:"E045",message:"Nullable type cannot be lowered to FieldSpec",category:"type"},E046:{code:"E046",message:"Record type cannot be lowered to FieldSpec",category:"type"},E047:{code:"E047",message:"dispatchable expression must be pure (state/computed/action parameters only)",category:"semantic"},E048:{code:"E048",message:"Transform primitive in dispatchable condition",category:"semantic"},E049:{code:"E049",message:"Invalid literal clamp bounds",category:"semantic"},E050:{code:"E050",message:"Invalid match() form",category:"semantic"},E051:{code:"E051",message:"Duplicate match() key",category:"semantic"},E052:{code:"E052",message:"Invalid argmax()/argmin() form",category:"semantic"},E053:{code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations",category:"syntax"},E054:{code:"E054",message:"Action-parameter annotations are not part of the current MEL syntax",category:"syntax"},E055:{code:"E055",message:"Annotation payloads must be JSON-like literals",category:"semantic"},E056:{code:"E056",message:"Annotation payload nesting exceeds the current MEL limit of 2 levels",category:"semantic"},E057:{code:"E057",message:"Annotation target does not map to the emitted DomainSchema",category:"semantic"},E_UNDEFINED:{code:"E_UNDEFINED",message:"Undefined identifier",category:"semantic"},E_DUPLICATE:{code:"E_DUPLICATE",message:"Duplicate identifier",category:"semantic"},E_INVALID_ACCESS:{code:"E_INVALID_ACCESS",message:"Invalid access to identifier in this context",category:"semantic"},E_UNGUARDED_STMT:{code:"E_UNGUARDED_STMT",message:"Statement must be inside a guard (when or once)",category:"semantic"},E_UNGUARDED_PATCH:{code:"E_UNGUARDED_PATCH",message:"Patch must be inside a guard",category:"semantic"},E_UNGUARDED_EFFECT:{code:"E_UNGUARDED_EFFECT",message:"Effect must be inside a guard",category:"semantic"},E_ARG_COUNT:{code:"E_ARG_COUNT",message:"Wrong number of arguments",category:"type"},E_TYPE_MISMATCH:{code:"E_TYPE_MISMATCH",message:"Type mismatch",category:"type"},W_NON_BOOL_COND:{code:"W_NON_BOOL_COND",message:"Condition may not be boolean",category:"semantic"},W_UNUSED:{code:"W_UNUSED",message:"Unused identifier",category:"semantic"},W012:{code:"W012",message:"Anonymous object type in state field - use named type declaration instead",category:"type"},MEL_LEXER:{code:"MEL_LEXER",message:"Lexer error",category:"syntax"},MEL_PARSER:{code:"MEL_PARSER",message:"Parser error",category:"syntax"}};function Ht(e){return Y[e]}function Jt(e){let n=Y[e];return n?`${e}: ${n.message}`:e}function Q(e,n){let{code:t,message:r,location:a}=e;if(!a||a.start.line===0&&a.start.column===0)return`[${t}] ${r}`;let{line:o,column:s}=a.start,l=`[${t}] ${r} (${o}:${s})`;if(!n)return l;let y=n.split(`
1
+ import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-O654OLQV.js";var Y={E001:{code:"E001",message:"$system.* cannot be used in computed expressions (non-deterministic)",category:"semantic"},E002:{code:"E002",message:"$system.* cannot be used in state initializers",category:"semantic"},E003:{code:"E003",message:"Invalid $system reference",category:"semantic"},E004:{code:"E004",message:"Identifier starts with reserved prefix '__sys__'",category:"syntax"},E005:{code:"E005",message:"available expression must be pure (no Effects, no $system.*)",category:"semantic"},E006:{code:"E006",message:"fail must be inside a guard (when, once, or onceIntent)",category:"semantic"},E007:{code:"E007",message:"stop must be inside a guard (when, once, or onceIntent)",category:"semantic"},E008:{code:"E008",message:"stop message suggests waiting/pending - use 'Already processed' style instead",category:"semantic"},E009:{code:"E009",message:"Primitive aggregation (sum, min, max) only allowed in computed",category:"semantic"},E010:{code:"E010",message:"Primitive aggregation does not allow composition - use direct reference only",category:"semantic"},E011:{code:"E011",message:"reduce/fold/scan is forbidden - use sum, min, max for aggregation",category:"semantic"},E013:{code:"E013",message:"Circular include detected",category:"semantic"},E014:{code:"E014",message:"Include expansion depth exceeds limit",category:"semantic"},E015:{code:"E015",message:"Include target is not a declared flow",category:"semantic"},E016:{code:"E016",message:"Include not allowed in InnerStmt position",category:"semantic"},E017:{code:"E017",message:"once() not allowed in flow",category:"semantic"},E018:{code:"E018",message:"onceIntent not allowed in flow",category:"semantic"},E019:{code:"E019",message:"patch not allowed in flow",category:"semantic"},E020:{code:"E020",message:"effect not allowed in flow",category:"semantic"},E021:{code:"E021",message:"Flow parameter name conflicts with top-level identifier",category:"semantic"},E022:{code:"E022",message:"Flow and action share the same name",category:"semantic"},E023:{code:"E023",message:"Wrong number of arguments for included flow",category:"semantic"},E024:{code:"E024",message:"Include argument type mismatch",category:"type"},E030:{code:"E030",message:"Collection element type does not have an 'id' field",category:"type"},E030a:{code:"E030a",message:"Collection element 'id' field is not a primitive type",category:"type"},E030b:{code:"E030b",message:"Duplicate '.id' values detected in state initializer",category:"type"},E031:{code:"E031",message:"updateById/removeById not allowed in this context",category:"semantic"},E032:{code:"E032",message:"Nested transform primitive",category:"semantic"},E033:{code:"E033",message:"Transform primitive collection argument is not a state path",category:"semantic"},E034:{code:"E034",message:"Transform primitive in guard condition",category:"semantic"},E035:{code:"E035",message:"Transform primitive in available condition",category:"semantic"},E040:{code:"E040",message:"Circular computed dependency",category:"semantic"},E041:{code:"E041",message:"Computed references undeclared identifier",category:"semantic"},E042:{code:"E042",message:"State initializer references non-constant value",category:"semantic"},E043:{code:"E043",message:"Non-trivial union type cannot be lowered to FieldSpec",category:"type"},E044:{code:"E044",message:"Recursive named type cannot be lowered to FieldSpec",category:"type"},E045:{code:"E045",message:"Nullable type cannot be lowered to FieldSpec",category:"type"},E046:{code:"E046",message:"Record type cannot be lowered to FieldSpec",category:"type"},E047:{code:"E047",message:"dispatchable expression must be pure (state/computed/action parameters only)",category:"semantic"},E048:{code:"E048",message:"Transform primitive in dispatchable condition",category:"semantic"},E049:{code:"E049",message:"Invalid literal clamp bounds",category:"semantic"},E050:{code:"E050",message:"Invalid match() form",category:"semantic"},E051:{code:"E051",message:"Duplicate match() key",category:"semantic"},E052:{code:"E052",message:"Invalid argmax()/argmin() form",category:"semantic"},E053:{code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations",category:"syntax"},E054:{code:"E054",message:"Action-parameter annotations are not part of the current MEL syntax",category:"syntax"},E055:{code:"E055",message:"Annotation payloads must be JSON-like literals",category:"semantic"},E056:{code:"E056",message:"Annotation payload nesting exceeds the current MEL limit of 2 levels",category:"semantic"},E057:{code:"E057",message:"Annotation target does not map to the emitted DomainSchema",category:"semantic"},E_UNDEFINED:{code:"E_UNDEFINED",message:"Undefined identifier",category:"semantic"},E_DUPLICATE:{code:"E_DUPLICATE",message:"Duplicate identifier",category:"semantic"},E_INVALID_ACCESS:{code:"E_INVALID_ACCESS",message:"Invalid access to identifier in this context",category:"semantic"},E_UNGUARDED_STMT:{code:"E_UNGUARDED_STMT",message:"Statement must be inside a guard (when or once)",category:"semantic"},E_UNGUARDED_PATCH:{code:"E_UNGUARDED_PATCH",message:"Patch must be inside a guard",category:"semantic"},E_UNGUARDED_EFFECT:{code:"E_UNGUARDED_EFFECT",message:"Effect must be inside a guard",category:"semantic"},E_ARG_COUNT:{code:"E_ARG_COUNT",message:"Wrong number of arguments",category:"type"},E_TYPE_MISMATCH:{code:"E_TYPE_MISMATCH",message:"Type mismatch",category:"type"},W_NON_BOOL_COND:{code:"W_NON_BOOL_COND",message:"Condition may not be boolean",category:"semantic"},W_UNUSED:{code:"W_UNUSED",message:"Unused identifier",category:"semantic"},W012:{code:"W012",message:"Anonymous object type in state field - use named type declaration instead",category:"type"},MEL_LEXER:{code:"MEL_LEXER",message:"Lexer error",category:"syntax"},MEL_PARSER:{code:"MEL_PARSER",message:"Parser error",category:"syntax"}};function Ht(e){return Y[e]}function Jt(e){let n=Y[e];return n?`${e}: ${n.message}`:e}function Q(e,n){let{code:t,message:r,location:a}=e;if(!a||a.start.line===0&&a.start.column===0)return`[${t}] ${r}`;let{line:o,column:s}=a.start,l=`[${t}] ${r} (${o}:${s})`;if(!n)return l;let y=n.split(`
2
2
  `)[o-1];if(!y)return l;let h=String(o).padStart(4," "),f=`${h} | ${y}`,p=Math.max(1,a.end.line===a.start.line?Math.min(a.end.column-s,y.length-s+1):1),E=`${" ".repeat(h.length+3+s-1)}${"^".repeat(p)}`;return`${l}
3
3
  ${f}
4
4
  ${E}`}function me(e,n){return e.map(t=>Q(t,n)).join(`
@@ -1 +1 @@
1
- import{c as n}from"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";import{readFile as i}from"fs/promises";import{fileURLToPath as c}from"url";function u(o){let[t]=o.split("?",1),[r]=t.split("#",1);return r}function s(o){return u(o).endsWith(".mel")}function a(o){try{return c(o)}catch{return o}}var h=async(o,t,r)=>s(o)?{...await r(o,t),shortCircuit:!0}:r(o,t),p=async(o,t,r)=>{if(!s(o))return r(o,t);let e=await i(new URL(o),"utf8");return{format:"module",source:n(e,a(o)),shortCircuit:!0}};export{p as load,h as resolve};
1
+ import{c as n}from"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";import{readFile as i}from"fs/promises";import{fileURLToPath as c}from"url";function u(o){let[t]=o.split("?",1),[r]=t.split("#",1);return r}function s(o){return u(o).endsWith(".mel")}function a(o){try{return c(o)}catch{return o}}var h=async(o,t,r)=>s(o)?{...await r(o,t),shortCircuit:!0}:r(o,t),p=async(o,t,r)=>{if(!s(o))return r(o,t);let e=await i(new URL(o),"utf8");return{format:"module",source:n(e,a(o)),shortCircuit:!0}};export{p as load,h as resolve};
package/dist/rollup.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var l=e.rollup,t=l;export{t as default,l as melPlugin};
1
+ import{a as e}from"./chunk-Q56VWGSA.js";import"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";var l=e.rollup,t=l;export{t as default,l as melPlugin};
package/dist/rspack.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.rspack,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-Q56VWGSA.js";import"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";var t=e.rspack,o=t;export{o as default,t as melPlugin};
package/dist/vite.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.vite,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-Q56VWGSA.js";import"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";var t=e.vite,o=t;export{o as default,t as melPlugin};
package/dist/webpack.js CHANGED
@@ -1 +1 @@
1
- import{a as e}from"./chunk-7BIJ7ZQJ.js";import"./chunk-E4EHOM7R.js";import"./chunk-YIGJ5PGV.js";var t=e.webpack,o=t;export{o as default,t as melPlugin};
1
+ import{a as e}from"./chunk-Q56VWGSA.js";import"./chunk-2ZRNXFBQ.js";import"./chunk-O654OLQV.js";var t=e.webpack,o=t;export{o as default,t as melPlugin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@manifesto-ai/compiler",
3
- "version": "3.7.0",
3
+ "version": "3.7.1",
4
4
  "description": "Manifesto Compiler - MEL (Manifesto Expression Language) to DomainSchema compiler",
5
5
  "author": "eggplantiny <eggplantiny@gmail.com>",
6
6
  "license": "MIT",
@@ -1,12 +0,0 @@
1
- var Ye={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"},jn=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 mi(t){return t in Ye}function wt(t){return jn.has(t)}function Ct(t){return Object.hasOwn(Ye,t)?Ye[t]:void 0}function Qe(t,e,n,o){return{kind:t,lexeme:e,location:n,value:o}}function Pt(t,e,n){return{line:t,column:e,offset:n}}function It(t,e,n){return{start:t,end:e,source:n}}function hi(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 Xe=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(Qe("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("AT");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
2
- `:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(e)?this.number():this.isAlpha(e)?this.identifier():this.error(`Unexpected character '${e}'`)}}lineComment(){for(;this.peek()!==`
3
- `&&!this.isAtEnd();)this.advance()}blockComment(){let e=this.line,n=this.column-2;for(;!this.isAtEnd();){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance();return}this.peek()===`
4
- `&&this.newline(),this.advance()}this.error(`Unterminated block comment starting at line ${e}:${n}`)}string(e){let n=this.line,o=this.column-1,r="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
5
- `){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":r+=`
6
- `;break;case"r":r+="\r";break;case"t":r+=" ";break;case"\\":r+="\\";break;case"'":r+="'";break;case'"':r+='"';break;case"0":r+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),r+=i}}else r+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${o}`);return}this.advance(),this.addToken("STRING",r)}number(){if(this.source[this.start]==="0"&&(this.peek()==="x"||this.peek()==="X")){for(this.advance();this.isHexDigit(this.peek());)this.advance();let n=this.source.slice(this.start+2,this.current),o=parseInt(n,16);this.addToken("NUMBER",o);return}for(;this.isDigit(this.peek());)this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(this.advance();this.isDigit(this.peek());)this.advance();if(this.peek()==="e"||this.peek()==="E"){if(this.advance(),(this.peek()==="+"||this.peek()==="-")&&this.advance(),!this.isDigit(this.peek())){this.error("Invalid number: expected digits after exponent");return}for(;this.isDigit(this.peek());)this.advance()}let e=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",e)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let e=this.source.slice(this.start,this.current);if(e.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(wt(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ct(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 It(e,n,this.sourcePath)}positionAt(e){let n=1,o=0;for(let r=0;r<e;r++)this.source[r]===`
7
- `&&(n++,o=r+1);return Pt(n,e-o+1,e)}addToken(e,n){let o=this.source.slice(this.start,this.current);this.tokens.push(Qe(e,o,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let o=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:o,source:this.getSourceLine(o.start.line)})}getSourceLine(e){return this.source.split(`
8
- `)[e-1]??""}};function Ae(t,e){return new Xe(t,e).tokenize()}function xi(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function vi(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var Mt=(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))(Mt||{});function Je(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 Dt(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 wi(t){return Je(t)!==0}function Ci(t){return t==="BANG"||t==="MINUS"}function Rt(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 o=this.parseAnnotationList();o.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(o);let r=this.parseDomain(o);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 o=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:o.value,location:h(e,o.location)}}parseDomain(e=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,o=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let r=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))r.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:o,annotations:e.length>0?e:void 0,types:r,members:i,location:h(n,a)}}parseTypeDecl(e=[]){let n=this.consume("TYPE","Expected 'type'").location,o=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let r=this.parseTypeExpr();return{kind:"typeDecl",name:o,annotations:e.length>0?e:void 0,typeExpr:r,location:h(n,r.location)}}parseDomainMember(e=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(e),this.parseState()):this.check("COMPUTED")?this.parseComputed(e):this.check("ACTION")?this.parseAction(e):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(e),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(e),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();){let r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}n.push(this.parseStateField(r))}let o=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,o)}}parseStateField(e=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let o=this.parseTypeExpr(),r;return this.match("EQ")&&(r=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,initializer:r,location:h(n.location,r?.location??o.location)}}parseComputed(e=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,o=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let r=this.parseExpression();return{kind:"computed",name:o,annotations:e.length>0?e:void 0,expression:r,location:h(n,r.location)}}parseAction(e=[]){let n=this.consume("ACTION","Expected 'action'").location,o=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let r=[];if(!this.check("RPAREN"))do{let l=this.parseAnnotationList();if(l.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(l);break}r.push(this.parseParam(l))}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 a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let l=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(l)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let l=this.parseGuardedStmt();l&&s.push(l)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:o,annotations:e.length>0?e:void 0,params:r,available:i,dispatchable:a,body:s,location:h(n,c)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;o.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:o,body:r,location:h(e.location,i)}}parseParam(e=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let o=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:o,location:h(n.location,o.location)}}parseGuardedStmt(){let e=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(e),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 n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("WHEN")?this.parseWhenStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'when', 'include', 'once', 'onceIntent', 'patch', or 'effect'.`),this.advance(),null)}skipToRecoveryPoint(){let e=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){e++,this.advance();continue}if(n.kind==="RBRACE"){if(e===0)return;e--,this.advance();continue}if(e===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let e=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:o,location:h(e,r)}}parseOnceStmt(){let e=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let o;this.match("WHEN")&&(o=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&r.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:o,body:r,location:h(e,i)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&o.push(i)}let r=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:o,location:h(e.location,r)}}parseInnerStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():this.check("WHEN")?this.parseWhenStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("FAIL")?this.parseFailStmt():this.check("STOP")?this.parseStopStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'patch', 'effect', 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseIncludeStmt(){let e=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let o=[];if(!this.check("RPAREN"))do o.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:o,location:h(e.location,r)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),o,r,i;return this.match("UNSET")?(o="unset",i=this.previous().location):this.match("MERGE")?(o="merge",r=this.parseExpression(),i=r.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),o="set",r=this.parseExpression(),i=r.location),{kind:"patch",path:n,op:o,value:r,location:h(e,i)}}parseEffectStmt(){let e=this.consume("EFFECT","Expected 'effect'").location,n=this.consume("IDENTIFIER","Expected effect type").lexeme;for(;this.match("DOT");)n+="."+this.consume("IDENTIFIER","Expected identifier after '.'").lexeme;this.consume("LPAREN","Expected '(' after effect type"),this.consume("LBRACE","Expected '{' for effect arguments");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)o.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let r=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:o,location:h(e,r)}}parseEffectArg(){let e=this.match("IDENTIFIER","FAIL")?this.previous():this.consume("IDENTIFIER","Expected argument name");this.consume("COLON","Expected ':' after argument name");let n=["into","pass","fail"].includes(e.lexeme),o=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:o,isPath:n,location:h(e.location,o.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),o=n.value,r,i=n.location;return this.match("WITH")&&(r=this.parseExpression(),i=r.location),{kind:"fail",code:o,message:r,location:h(e,i)}}parseStopStmt(){let e=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:h(e,n.location)}}parseTypeExpr(){let e=this.parseBaseType();if(this.check("PIPE")){let n=[e];for(;this.match("PIPE");)n.push(this.parseBaseType());e={kind:"unionType",types:n,location:h(n[0].location,n[n.length-1].location)}}return e}parseBaseType(){if(this.check("LBRACE"))return this.parseObjectType();if(this.check("STRING")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("NUMBER")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("TRUE")||this.check("FALSE")){let n=this.advance();return{kind:"literalType",value:n.kind==="TRUE",location:n.location}}if(this.check("NULL"))return{kind:"literalType",value:null,location:this.advance().location};let e=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(e.lexeme==="Array"){let n=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,o)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let o=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:o,location:h(e.location,r)}}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 r=this.parseAnnotationList();if(r.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(r);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:r.length>0?r:void 0,typeExpr:s,optional:a,location:h(i.location,s.location)}),this.match("COMMA")}let o=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,o)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let o=Je(this.peek().kind);if(o<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let r=Dt(this.peek().kind);if(!r)break;this.advance();let i=Rt(this.previous().kind)?o-1:o,a=this.parseExpression(i);n={kind:"binary",operator:r,left:n,right:a,location:h(n.location,a.location)}}return n}parseTernary(e){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let o=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:o,location:h(e.location,o.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let e=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:e.kind==="BANG"?"!":"-",operand:n,location:h(e.location,n.location)}}if(this.match("LPAREN")){let e=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),e}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"number",location:e.location}}if(this.check("STRING")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"string",location:e.location}}if(this.check("TRUE")||this.check("FALSE")){let e=this.advance();return{kind:"literal",value:e.kind==="TRUE",literalType:"boolean",location:e.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let e=this.advance(),n=e.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:e.location})}if(this.check("ITEM")){let e=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:e.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let e=this.advance();return this.parseFunctionCall(e)}if(this.check("IDENTIFIER")){let e=this.advance();return this.check("LPAREN")?this.parseFunctionCall(e):this.parsePostfix({kind:"identifier",name:e.lexeme,location:e.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(e){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,o)})}parsePostfix(e){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"propertyAccess",object:e,property:n.lexeme,location:h(e.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),o=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,o)}}else break;return e}parseObjectLiteral(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let r=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:r.lexeme,value:i,location:h(r.location,i.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let o=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,o)}}parseArrayLiteral(){let e=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();)n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements");let o=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,o)}}parsePath(){let e=[],n=this.peek().location,o=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:o.lexeme,location:o.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:i,location:h(i.location,a)})}else break;let r=e[e.length-1];return{kind:"path",segments:e,location:h(n,r.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","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)}parseAnnotationList(){let e=[];for(;this.check("AT");)e.push(this.parseAnnotation());return e}parseAnnotation(){let e=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let o=this.consume("STRING","Expected string tag as first @meta argument"),r;this.match("COMMA")&&(r=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:o.value,payload:r,location:h(e,i)}}reportUnsupportedAnnotations(e){for(let n of e)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}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)}errorAtToken(e,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:e.location}),new Error(n)}};function we(t){return new Ze(t).parse()}var Ce=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)}},et=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 Ce("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let o of e.members)if(o.kind==="state")for(let r of o.fields)this.defineSymbol({name:r.name,kind:"state",location:r.location});else o.kind==="computed"?this.defineSymbol({name:o.name,kind:"computed",location:o.location}):o.kind==="action"?this.defineSymbol({name:o.name,kind:"action",location:o.location}):o.kind;for(let o of e.members)o.kind==="computed"?this.analyzeComputedExpr(o):o.kind==="action"&&this.analyzeAction(o)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new Ce("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let o of e.params)n.define({name:o.name,kind:"param",location:o.location});for(let o of e.body)this.analyzeStmt(o);this.currentScope=this.domainScope}analyzeStmt(e){switch(e.kind){case"when":this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"onceIntent":e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"once":this.validatePath(e.marker),e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"patch":this.validatePath(e.path),e.value&&this.analyzeExpr(e.value,"action");break;case"effect":for(let n of e.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(e,n){switch(e.kind){case"identifier":this.checkIdentifier(e.name,e.location,n);break;case"systemIdent":this.checkSystemIdent(e.path,e.location,n);break;case"propertyAccess":this.analyzeExpr(e.object,n);break;case"indexAccess":this.analyzeExpr(e.object,n),this.analyzeExpr(e.index,n);break;case"functionCall":for(let o of e.args)this.analyzeExpr(o,n);break;case"binary":this.analyzeExpr(e.left,n),this.analyzeExpr(e.right,n);break;case"unary":this.analyzeExpr(e.operand,n);break;case"ternary":this.analyzeExpr(e.condition,n),this.analyzeExpr(e.consequent,n),this.analyzeExpr(e.alternate,n);break;case"objectLiteral":for(let o of e.properties)this.analyzeExpr(o.value,n);break;case"arrayLiteral":for(let o of e.elements)this.analyzeExpr(o,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,o){let r=this.currentScope?.lookup(e);if(!r){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}o==="computed"&&r.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,o){let[r,...i]=e;if(r==="system"&&o==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),r==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(r==="meta"){let a=["intentId","actionName","timestamp"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(e){if(!e||!e.segments)return;let n=e.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,e.location,"E_UNDEFINED"))}defineSymbol(e){if(this.currentScope){if(this.currentScope.isDefined(e.name)){this.error(`Duplicate identifier '${e.name}'`,e.location,"E_DUPLICATE");return}this.currentScope.define(e)}}error(e,n,o){this.diagnostics.push({severity:"error",code:o,message:e,location:n})}};function Ot(t){return new et().analyze(t)}function P(t,e,n,o){return{severity:"error",code:t,message:e,location:n,...o}}function Lt(t,e,n,o){return{severity:"warning",code:t,message:e,location:n,...o}}function _i(t,e,n){return{severity:"info",code:t,message:e,location:n}}function _n(t){return t.severity==="error"}function $i(t){return t.some(_n)}function Gi(t,e){return t.filter(n=>n.severity===e)}var Ft=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),jt=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),_t=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),$n=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Gn=new Set(["updateById","removeById"]);function Pe(t){let e=new Map,n=new Map,o=new Map;for(let r of t.types)o.set(r.name,r);for(let r of t.members){if(r.kind==="state"){for(let i of r.fields)e.set(i.name,i.typeExpr);continue}r.kind==="computed"&&n.set(r.name,r)}return{stateTypes:e,computedDecls:n,typeDefs:o,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Ie(t){let e=new Map;for(let n of t)e.set(n.name,n.typeExpr);return e}function k(t,e,n){switch(t.kind){case"literal":return Vn(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??Un(t.name,n);case"propertyAccess":return X(k(t.object,e,n),t.property,n);case"indexAccess":return ge(k(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=k(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{let o=D(t.elements.map(r=>k(r,e,n)),t.location);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"unary":return Bn(t);case"binary":return zn(t,e,n);case"ternary":return D([k(t.consequent,e,n),k(t.alternate,e,n)],t.location);case"functionCall":return qn(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function $(t,e,n){let o=k(t,e,n);if(o)return $t(o,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?ye([$(t.left,e,n),$(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 ye([$(t.consequent,e,n),$(t.alternate,e,n)]);case"functionCall":return $n.has(t.name)?"nonprimitive":Ft.has(t.name)||jt.has(t.name)||_t.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?ye([$(t.args[1],e,n),$(t.args[2],e,n)]):t.name==="coalesce"?ye(t.args.map(r=>$(r,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function $t(t,e){let n=R(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 ye(n.types.map(o=>$t(o,e)))}}function R(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),R(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function X(t,e,n){let o=R(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType"){let r=o.types.filter(i=>!ne(i)).map(i=>X(i,e,n)).filter(i=>i!==null);return D(r,o.location)}return null}function ge(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let o=n.types.filter(r=>!ne(r)).map(r=>ge(r,e)).filter(r=>r!==null);return D(o,n.location)}return null}function G(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let o=n.types.filter(r=>!ne(r)).map(r=>G(r,e)).filter(r=>r!==null);return D(o,n.location)}return null}function Me(t,e){let n=R(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number";case"literalType":return typeof n.value=="string"||typeof n.value=="number";case"unionType":return n.types.length>0&&n.types.every(o=>Me(o,e));default:return!1}}function ne(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function Un(t,e){if(e.computedTypeCache.has(t))return e.computedTypeCache.get(t)??null;let n=e.computedDecls.get(t);if(!n||e.computedTypeInFlight.has(t))return null;e.computedTypeInFlight.add(t);let o=k(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,o),o}function Bn(t){return t.operator==="!"?I("boolean",t.location):I("number",t.location)}function zn(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return I("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return I("number",t.location);case"??":return D([k(t.left,e,n),k(t.right,e,n)],t.location)}}function qn(t,e,n){if(Ft.has(t.name))return I("boolean",t.location);if(jt.has(t.name))return I("number",t.location);if(t.name==="idiv")return D([I("number",t.location),I("null",t.location)],t.location);if(_t.has(t.name))return I("string",t.location);if(t.name==="toBoolean")return I("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?D([o,I("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let o=G(k(t.args[0],e,n),n);return o?D([o,I("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return k(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let o=k(t.args[0],e,n),r=G(o,n);if(!r)return null;let i=k(t.args[1],Yn(e,r),n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return G(k(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return ge(k(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let o=Wn(t.args[1]);return o?X(k(t.args[0],e,n),o,n):null}return Gn.has(t.name)&&t.args.length>=1?k(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?D([k(t.args[1],e,n),k(t.args[2],e,n)],t.location):t.name==="coalesce"?D(t.args.map(o=>k(o,e,n)),t.location):t.name==="match"?Hn(t,e,n):t.name==="argmax"||t.name==="argmin"?Kn(t,e,n):t.name==="slice"&&t.args.length>=1?k(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:I("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:I("string",t.location),location:t.location}:null}function ye(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function D(t,e){let n=t.filter(i=>i!==null);if(n.length===0)return null;if(n.length===1)return n[0];let o=[],r=new Set;for(let i of n){let a=JSON.stringify(i);r.has(a)||(r.add(a),o.push(i))}return o.length===1?o[0]:{kind:"unionType",types:o,location:e}}function Hn(t,e,n){if(t.args.length<3)return null;let o=[];for(let r=1;r<t.args.length-1;r+=1){let i=t.args[r];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;o.push(k(i.elements[1],e,n))}return o.push(k(t.args[t.args.length-1],e,n)),D(o,t.location)}function Kn(t,e,n){if(t.args.length<2)return null;let o=[];for(let i=0;i<t.args.length-1;i+=1){let a=t.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;o.push(k(a.elements[0],e,n))}let r=D(o,t.location);return r?D([r,I("null",t.location)],t.location):null}function Vn(t,e){return{kind:"literalType",value:t,location:e}}function I(t,e){return{kind:"simpleType",name:t,location:e}}function Wn(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function Yn(t,e){let n=new Map(t);return n.set("$item",e),n}var Qn=new Set(["findById","existsById"]),nt=new Set(["updateById","removeById"]),Xn=new Set([...Qn,...nt]);function H(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(P(n,o,r)))}function Gt(t){let e=[],n=new Set,o=Pe(t.domain);to(t.domain,o,e,n);for(let r of t.domain.members)switch(r.kind){case"computed":b(r.expression,"computed",new Map,o,e,n,0);break;case"action":{let i=Ie(r.params);Jn(r,i,o,e,n);break}case"state":case"flow":break}return e}function Jn(t,e,n,o,r){t.available&&b(t.available,"available",e,n,o,r,0),t.dispatchable&&b(t.dispatchable,"dispatchable",e,n,o,r,0);for(let i of t.body)Zn(i,e,n,o,r)}function Zn(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"include":break}}function oe(t,e,n,o,r){switch(t.kind){case"when":b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"once":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"onceIntent":t.condition&&b(t.condition,"guard",e,n,o,r,0);for(let i of t.body)oe(i,e,n,o,r);break;case"patch":t.value&&b(t.value,"patch",e,n,o,r,0);break;case"effect":for(let i of t.args)i.isPath||b(i.value,"action",e,n,o,r,0);break;case"fail":t.message&&b(t.message,"action",e,n,o,r,0);break;case"include":case"stop":break}}function b(t,e,n,o,r,i,a){switch(t.kind){case"functionCall":{eo(t,e,n,o,r,i,a);let s=a+(nt.has(t.name)?1:0);for(let c of t.args)b(c,e,n,o,r,i,s);break}case"binary":b(t.left,e,n,o,r,i,a),b(t.right,e,n,o,r,i,a);break;case"unary":b(t.operand,e,n,o,r,i,a);break;case"ternary":b(t.condition,e,n,o,r,i,a),b(t.consequent,e,n,o,r,i,a),b(t.alternate,e,n,o,r,i,a);break;case"propertyAccess":b(t.object,e,n,o,r,i,a);break;case"indexAccess":b(t.object,e,n,o,r,i,a),b(t.index,e,n,o,r,i,a);break;case"objectLiteral":for(let s of t.properties)b(s.value,e,n,o,r,i,a);break;case"arrayLiteral":for(let s of t.elements)b(s,e,n,o,r,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function eo(t,e,n,o,r,i,a){if(!Xn.has(t.name)||t.args.length===0)return;nt.has(t.name)&&(e==="available"?H(r,i,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?H(r,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?H(r,i,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&H(r,i,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&H(r,i,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!tt(t.args[0],o)&&H(r,i,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=oo(t.args[0],n,o);if(!s)return;let c=Ut(s,o);if(!c){H(r,i,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}Me(c,o)||H(r,i,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function to(t,e,n,o){for(let r of t.members)if(r.kind==="state")for(let i of r.fields)no(i,e,n,o)}function no(t,e,n,o){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let r=G(t.typeExpr,e);if(!r)return;let i=Ut(r,e);if(!i||!Me(i,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)){H(n,o,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function oo(t,e,n){return G(k(t,e,n),n)}function Ut(t,e){return X(t,"id",e)}function tt(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return tt(t.object,e);case"indexAccess":return tt(t.object,e);default:return!1}}function Bt(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var ro=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function E(t,e){return{kind:"simpleType",name:t,location:e}}function K(t,e,n){let o=R(t,n),r=R(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=o.kind==="unionType"?o.types:[o],a=!1;for(let s of i){let c=r.types.map(l=>K(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(o.kind==="unionType"){let i=!1;for(let a of o.types){let s=K(a,r,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:K(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=K(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:K(o.valueType,r.valueType,n):null}function v(t,e){let n=R(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<${v(n.elementType,e)}>`;case"recordType":return`Record<${v(n.keyType,e)}, ${v(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(o=>`${o.name}${o.optional?"?":""}: ${v(o.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(o=>v(o,e)).join(" | ")}}function De(t,e){let n=R(t,e);if(!n)return null;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?new Set([n.name]):n.name==="object"?"nonprimitive":null;case"literalType":return new Set([n.value===null?"null":typeof n.value]);case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":{let o=new Set;for(let r of n.types){let i=De(r,e);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)o.add(a)}return o}}}function ot(t,e){let n=De(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let o=[...n].filter(r=>r!=="null");return o.length!==1||n.has("null")?"invalid":o[0]}function qt(t,e,n){let o=De(t,n),r=De(e,n);if(o===null||r===null)return null;if(o==="nonprimitive"||r==="nonprimitive")return!1;if(!(o instanceof Set)||!(r instanceof Set))return null;let i=[...o].filter(s=>s!=="null"),a=[...r].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function io(t,e){let n=R(t,e);if(!n||ne(n))return null;if(n.kind!=="unionType")return n;let o=n.types.filter(r=>!ne(r));return o.length===0?null:o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function rt(t,e,n){if(!t||!e)return null;let o=K(t,e,n);if(o===!0)return!0;let r=K(e,t,n);if(r===!0)return!0;let i=qt(t,e,n);return i!==null?i:o===!1&&r===!1?!1:null}function Ht(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>Ht(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!1)?!1:null}return n.kind==="arrayType"}function Kt(t,e){let n=R(t,e);if(!n)return null;if(n.kind==="unionType"){let o=n.types.map(r=>Kt(r,e));return o.every(r=>r===!0)?!0:o.some(r=>r===!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 ao(t,e){let n=new Map(t);return n.set("$item",e),n}function zt(t){let e=Re(t);if(typeof e=="number")return e;if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function Re(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=Re(t.operand);return typeof e=="number"?-e:void 0}}function so(t,e){let[n,...o]=t.segments;if(!n||n.kind!=="propertySegment")return null;let r=e.stateTypes.get(n.name)??null;for(let i of o){if(!r)return null;r=i.kind==="propertySegment"?X(r,i.name,e):ge(r,e)}return r}function co(t){let e="";for(let[n,o]of t.segments.entries()){if(o.kind==="propertySegment"){e+=n===0?o.name:`.${o.name}`;continue}o.index.kind==="literal"?e+=`[${JSON.stringify(o.index.value)}]`:e+="[*]"}return e}var it=class{ctx=Bt();symbols=null;validate(e){return this.ctx=Bt(),this.symbols=Pe(e.domain),this.validateDomain(e.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(e){e.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",e.location,"E_RESERVED_NAME");for(let n of e.members)switch(n.kind){case"state":this.validateState(n);break;case"computed":this.validateExpr(n.expression,"computed");break;case"action":this.validateAction(n);break;case"flow":break}}validateState(e){let n=new Map;for(let o of e.fields){let r=n.get(o.name);r?this.error(`Duplicate state field '${o.name}'. First declared at line ${r.start.line}`,o.location,"E_DUPLICATE_FIELD"):n.set(o.name,o.location),this.validateStateField(o)}}validateStateField(e){this.checkAnonymousObjectType(e.typeExpr,e.location),e.initializer&&this.validateStateInitializer(e.initializer)}validateStateInitializer(e){switch(e.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",e.location,"E042");return;case"systemIdent":e.path[0]==="system"?this.error("$system.* cannot be used in state initializers",e.location,"E002"):this.error("State initializers must be compile-time constants",e.location,"E042");return;case"objectLiteral":for(let n of e.properties)this.validateStateInitializer(n.value);return;case"arrayLiteral":for(let n of e.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let o of e.args)this.validateStateInitializer(o);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.left),this.validateStateInitializer(e.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.condition),this.validateStateInitializer(e.consequent),this.validateStateInitializer(e.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.validateStateInitializer(e.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}}}checkAnonymousObjectType(e,n){switch(e.kind){case"objectType":this.ctx.diagnostics.push(Lt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",e.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let o of e.fields)this.checkAnonymousObjectType(o.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(e.elementType,n);break;case"recordType":this.checkAnonymousObjectType(e.keyType,n),this.checkAnonymousObjectType(e.valueType,n);break;case"unionType":for(let o of e.types)this.checkAnonymousObjectType(o,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Ie(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,o=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let r=so(e.path,this.symbols);if(!r||!o)return;K(o,r,this.symbols)===!1&&this.error(`Patch value for '${co(e.path)}' must be assignable to ${v(r,this.symbols)}, got ${v(o,this.symbols)}`,e.value.location,"E_TYPE_MISMATCH")}}validateEffect(e){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_EFFECT");for(let n of e.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(e){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",e.location,"E006"),e.message&&this.validateExpr(e.message,"action")}validateStop(e){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",e.location,"E007"),ro.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let o=this.ctx.diagnostics.length,r=this.validateExpr(e,"action");o===this.ctx.diagnostics.length&&this.requireAssignable(r,E("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,o=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,o),this.inferType(e,o);case"binary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.left,n,o),a=this.validateExpr(e.right,n,o);if(!(r!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,i,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,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(i,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(i,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([i,a],e.location);break}return this.inferType(e,o)}case"unary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.operand,n,o);return r===this.ctx.diagnostics.length&&this.requireAssignable(i,E(e.operator==="!"?"boolean":"number",e.operand.location),e.operand.location,e.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(e,o)}case"ternary":{let r=this.ctx.diagnostics.length,i=this.validateExpr(e.condition,n,o);return this.validateExpr(e.consequent,n,o),this.validateExpr(e.alternate,n,o),r===this.ctx.diagnostics.length&&this.requireAssignable(i,E("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,o)}case"propertyAccess":return this.validateExpr(e.object,n,o),this.inferType(e,o);case"indexAccess":return this.validateExpr(e.object,n,o),this.validateExpr(e.index,n,o),this.inferType(e,o);case"objectLiteral":for(let r of e.properties)this.validateExpr(r.value,n,o);return this.inferType(e,o);case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n,o);return this.inferType(e,o);case"systemIdent":return this.inferType(e,o);case"literal":case"identifier":case"iterationVar":return this.inferType(e,o)}}validateFunctionCall(e,n,o){let{name:r,args:i,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(r)&&this.error(`Function '${r}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(r)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${r}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${r}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(r){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.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":i.length!==1&&this.error(`Function '${r}' expects 1 argument, got ${i.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":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${r}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${r}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${r}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${r}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${r}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${r}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(r)&&i.length>0){let c=this.validateExpr(i[0],n,o);s.push(c);let l=o;if(this.symbols){let d=G(c,this.symbols);d&&(l=ao(o,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:o))}else for(let c of i)s.push(this.validateExpr(c,n,o));if(this.symbols)switch(r){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],E("boolean",l.location),l.location,`Function '${r}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],E("number",i[0].location),i[0].location,`Function '${r}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],E("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=Re(i[1]),l=Re(i[2]);typeof c=="number"&&typeof l=="number"&&c>l&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":i.length===2&&(this.requireAssignable(s[0],E("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,`Function '${r}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],E("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],E("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],E("string",i[0].location),i[0].location,`Function '${r}' expects a string first argument`),this.requireAssignable(s[1],E("number",i[1].location),i[1].location,`Function '${r}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],E("number",i[2].location),i[2].location,`Function '${r}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,r),this.requireAssignable(s[1],E("boolean",i[1].location),i[1].location,`Function '${r}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,r);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,o);break;case"argmax":case"argmin":this.validateArgSelectionCall(r,i,a,o);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],E("boolean",i[0].location),i[0].location,`Function '${r}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,o,r,i){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",i,"E_TYPE_MISMATCH");return}qt(o,r,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(o,this.symbols)} and ${v(r,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?k(e,n,this.symbols):null}requireAssignable(e,n,o,r){if(!this.symbols||!e)return;K(e,n,this.symbols)===!1&&this.error(`${r}, got ${v(e,this.symbols)}`,o,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,o){if(!this.symbols||!e)return;Ht(e,this.symbols)===!1&&this.error(`Function '${o}' expects an array first argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;Kt(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let o=e.map(r=>io(r,this.symbols)).filter(r=>r!==null);for(let r=0;r<o.length;r+=1)for(let i=r+1;i<o.length;i+=1)if(rt(o[r],o[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(o[r],this.symbols)} and ${v(o[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,o,r){if(!this.symbols||e.length<3)return;let i=n[0],a=ot(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(i,this.symbols)}`,e[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<e.length-1;l+=1){let d=e[l];if(d.kind!=="arrayLiteral"||d.elements.length!==2){this.error("Function 'match' requires each arm to be an inline [key, value] array literal",d.location,"E050");continue}let[p,m]=d.elements,f=zt(p);if(f==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let _=`${typeof f}:${String(f)}`;s.has(_)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(f)}`,p.location,"E051"):s.add(_)}let N=this.inferType(p,r),S=ot(N,this.symbols);(S==="invalid"||a!==null&&S!==null&&a!==S)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${v(i,this.symbols)} and ${v(N,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(m,r))}c.push(n[n.length-1]);for(let l=0;l<c.length;l+=1)for(let d=l+1;d<c.length;d+=1)if(rt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,o,r){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=zt(i);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,i.location,"E052");let s=[],c=null;for(let l=0;l<n.length-1;l+=1){let d=n[l];if(d.kind!=="arrayLiteral"||d.elements.length!==3){this.error(`Function '${e}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[p,m,f]=d.elements,N=this.inferType(p,r),S=ot(N,this.symbols);S==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${v(N,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=S:S!==null&&S!==c&&this.error(`Function '${e}' candidate labels must share one primitive scalar type, got ${c} and ${S}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(m,r),E("boolean",m.location),m.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(f,r),E("number",f.location),f.location,`Function '${e}' expects a numeric score value`),s.push(N)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(rt(s[l],s[d],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,o,"E_TYPE_MISMATCH");return}}error(e,n,o){this.ctx.diagnostics.push({severity:"error",code:o,message:e,location:n})}warn(e,n,o){this.ctx.diagnostics.push({severity:"warning",code:o,message:e,location:n})}};function Vt(t){let n=new it().validate(t),o=Gt(t),r=[...n.diagnostics,...o];return{valid:!r.some(i=>i.severity==="error"),diagnostics:r}}var at={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},st={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},ct={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},lt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},lo={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var j=class extends Error{code;path;details;constructor(e,n,o){super(n),this.name="LoweringError",this.code=e,this.path=o?.path,this.details=o?.details}};function Oe(t,e,n){return new j("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function y(t,e){return new j("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function Le(t,e){return new j("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function dt(t,e){return new j("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function po(t,e){return new j("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function pt(t,e){return new j("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function uo(t,e){let n=Array.from(t),o=Array.from(e),r=Math.min(n.length,o.length);for(let i=0;i<r;i+=1){let a=n[i].codePointAt(0)??0,s=o[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-o.length}function Wt(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let o=uo(e.item.key,n.item.key);return o!==0?o:e.index-n.index}).map(({item:e})=>e)}function u(t,e){switch(t.kind){case"lit":return mo(t);case"var":return fo(t,e);case"sys":return ho(t,e);case"get":return yo(t,e);case"field":return Yt(t,e);case"call":return go(t,e);case"obj":return Eo(t,e);case"arr":return ko(t,e);default:throw pt(t.kind)}}function mo(t){return{kind:"lit",value:t.value}}function fo(t,e){if(!e.allowItem)throw Oe("var",e.mode);return{kind:"get",path:"$item"}}function ho(t,e){if(t.path.length===0)throw Le(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw Le(t.path);return{kind:"get",path:t.path.join(".")}}function yo(t,e){let n=t.path.map(o=>o.name).join(".");if(t.base===void 0)return{kind:"get",path:n};if(t.base.kind==="var"&&t.base.name==="item"){if(!e.allowItem)throw Oe("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw dt(t.base.kind)}function Yt(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(o=>o.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:u(t.object,e),property:t.property}}function go(t,e){let{fn:n,args:o}=t;if(n==="absDiff"){if(o.length!==2)throw y(n);return{kind:"abs",arg:{kind:"sub",left:u(o[0],e),right:u(o[1],e)}}}if(n==="clamp"){if(o.length!==3)throw y(n);return{kind:"min",args:[{kind:"max",args:[u(o[0],e),u(o[1],e)]},u(o[2],e)]}}if(n==="idiv"){if(o.length!==2)throw y(n);return{kind:"floor",arg:{kind:"div",left:u(o[0],e),right:u(o[1],e)}}}if(n==="streak"){if(o.length!==2)throw y(n);return{kind:"if",cond:u(o[1],e),then:{kind:"add",left:u(o[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return To(o,e);if(n==="argmax"||n==="argmin")return No(n,o,e);if(Ao(n)){if(o.length!==2)throw y(n);let[r,i]=o;return{kind:n,left:u(r,e),right:u(i,e)}}if(n==="isNotNull"){if(o.length!==1)throw y(n);return{kind:"not",arg:{kind:"isNull",arg:u(o[0],e)}}}if(Qt(n)){if(o.length!==1)throw y(n);return{kind:wo(n),arg:u(o[0],e)}}if(n==="trim"){if(o.length!==1)throw y(n);return{kind:"trim",str:u(o[0],e)}}if(n==="lower"||n==="toLowerCase"){if(o.length!==1)throw y(n);return{kind:"toLowerCase",str:u(o[0],e)}}if(n==="upper"||n==="toUpperCase"){if(o.length!==1)throw y(n);return{kind:"toUpperCase",str:u(o[0],e)}}if(n==="strlen"||n==="strLen"){if(o.length!==1)throw y(n);return{kind:"strLen",str:u(o[0],e)}}if(Co(n))return o.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(o[0],e)}:{kind:n,args:o.map(r=>u(r,e))};if(n==="sum"){if(o.length!==1)throw y(n);return{kind:"sumArray",array:u(o[0],e)}}if(n==="pow"){if(o.length!==2)throw y(n);return{kind:"pow",base:u(o[0],e),exponent:u(o[1],e)}}if(Po(n))return{kind:n,args:o.map(r=>u(r,e))};if(n==="if"||n==="cond"){if(o.length!==3)throw y(n);return{kind:"if",cond:u(o[0],e),then:u(o[1],e),else:u(o[2],e)}}if(n==="field"){if(o.length!==2)throw y(n);let r=u(o[0],e),i=o[1];if(i.kind!=="lit"||typeof i.value!="string")throw y(n);return Yt({kind:"field",object:o[0],property:i.value},e)}if(Io(n)){if(o.length!==1)throw y(n);return{kind:n,array:u(o[0],e)}}if(Mo(n)){if(o.length!==1)throw y(n);return{kind:n,obj:u(o[0],e)}}if(n==="at"){if(o.length!==2)throw y(n);return{kind:"at",array:u(o[0],e),index:u(o[1],e)}}if(n==="includes"){if(o.length!==2)throw y(n);return{kind:"includes",array:u(o[0],e),item:u(o[1],e)}}if(Do(n)){if(o.length!==2)throw y(n);let r={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(o[0],e),mapper:u(o[1],r)}:{kind:n,array:u(o[0],e),predicate:u(o[1],r)}}if(n==="slice"){if(o.length<2||o.length>3)throw y(n);let r={kind:"slice",array:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="substring"||n==="substr"){if(o.length<2||o.length>3)throw y(n);let r={kind:"substring",str:u(o[0],e),start:u(o[1],e)};return o.length===3&&(r.end=u(o[2],e)),r}if(n==="append"){if(o.length<1)throw y(n);return{kind:"append",array:u(o[0],e),items:o.slice(1).map(r=>u(r,e))}}if(n==="merge")return{kind:"merge",objects:o.map(r=>u(r,e))};throw y(n)}function Eo(t,e){let n={};for(let o of Wt(t.fields))n[o.key]=u(o.value,e);return{kind:"object",fields:n}}function ko(t,e){if(t.elements.every(r=>r.kind==="lit"))return{kind:"lit",value:t.elements.map(i=>i.value)};let o=t.elements.map(r=>u(r,e));return o.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:o}}function To(t,e){if(t.length<3)throw y("match");let n=u(t[0],e),o=u(t[t.length-1],e);for(let r=t.length-2;r>=1;r-=1){let i=t[r];if(i.kind!=="arr"||i.elements.length!==2)throw y("match");o={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],e)},then:u(i.elements[1],e),else:o}}return o}function No(t,e,n){if(e.length<2)throw y(t);let o=e[e.length-1];if(o.kind!=="lit"||o.value!=="first"&&o.value!=="last")throw y(t);let r=e.slice(0,-1).map(i=>bo(i,n,t));if(r.length===0)throw y(t);return So(t,r,o.value)}function bo(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw y(n);return{label:u(t.elements[0],e),eligible:u(t.elements[1],e),score:u(t.elements[2],e)}}function So(t,e,n){let o={kind:"lit",value:null};for(let r=e.length-1;r>=0;r-=1)o={kind:"if",cond:xo(t,e,n,r),then:e[r].label,else:o};return o}function xo(t,e,n,o){let r=e[o],i=[];for(let a=0;a<e.length;a+=1){if(a===o)continue;let s=e[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:vo(t,n,o,a),left:r.score,right:s.score}]})}return i.length===0?r.eligible:{kind:"and",args:[r.eligible,...i]}}function vo(t,e,n,o){let r=e==="first"?n<o:n>o;return t==="argmax"?r?"gte":"gt":r?"lte":"lt"}function Ao(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function Qt(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function wo(t){if(t==="isNotNull")throw y(t);if(!Qt(t))throw y(t);return t}function Co(t){return t==="min"||t==="max"}function Po(t){return["and","or","concat","coalesce"].includes(t)}function Io(t){return["first","last"].includes(t)}function Mo(t){return["keys","values","entries"].includes(t)}function Do(t){return["filter","find","every","some","map"].includes(t)}function Ro(t,e){return t.map(n=>Oo(n,e))}function Oo(t,e){let n=t.condition?u(t.condition,Fe(e,"action")):void 0,o=Lo(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:o,confidence:t.confidence}}function Lo(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:re(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:re(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:re(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,Fe(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,Fe(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,Fe(e,"schema"))}}}function re(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:re(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:re(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(re)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function Fe(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function Fo(t,e){return t.map(n=>je(n,e))}function je(t,e){let n=t.condition?u(t.condition,e):void 0,o=t.value?u(t.value,e):void 0;return{condition:n,op:t.op,path:jo(t.path,e),value:o}}function jo(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function w(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:Go(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??U(t.name);case"systemIdent":return _o(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return $o(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[w(t.object,e),w(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>w(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[w(t.operand,e)]};case"binary":return{kind:"call",fn:Uo(t.operator),args:[w(t.left,e),w(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[w(t.condition,e),w(t.consequent,e),w(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:w(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>w(n,e))}}}function U(...t){return{kind:"get",path:Xt(...t)}}function ut(t,...e){return{kind:"get",base:t,path:Xt(...e)}}function Ee(...t){return{kind:"sys",path:t}}function _e(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function Xt(...t){return t.map(e=>({kind:"prop",name:e}))}function _o(t,e){return e.resolveSystemIdent?.(t.path)??Ee(...t.path)}function $o(t,e,n){let o=w(t,n);return o.kind==="get"?{kind:"get",...o.base?{base:o.base}:void 0,path:[...o.path,{kind:"prop",name:e}]}:o.kind==="var"&&o.name==="item"?ut(o,e):{kind:"field",object:o,property:e}}function Go(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 Uo(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 Vo,semanticPathToPatchPath as Wo,sha256Sync as Yo}from"@manifesto-ai/core";var Bo=new Set(["findById","existsById","updateById","removeById"]);function Jt(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,zo(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,qo(n)]))}}function zo(t){return{...t,expr:Zt(t.expr)}}function qo(t){return{...t,flow:$e(t.flow),available:t.available?Zt(t.available):void 0,dispatchable:t.dispatchable?Ho(t.dispatchable):void 0}}function $e(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>$e(e))};case"if":return{kind:"if",cond:mt(t.cond),then:$e(t.then),else:t.else?$e(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?mt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,Ko(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?mt(t.message):void 0};case"call":case"halt":return t}}function Zt(t){return u(O(t),at)}function mt(t){return u(O(t),st)}function Ho(t){return u(O(t),ct)}function Ko(t){return u(O(t),lt)}function O(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?U("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:O(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:O(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:O(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>O(e))};case"call":return Bo.has(t.fn)?O(en(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>O(e))}}}function en(t,e){let[n,o,r]=e,i=O(n),a=o?O(o):{kind:"lit",value:null},s={kind:"var",name:"item"},c=ut(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[en("findById",e)]}]};case"updateById":{let l=r?O(r):_e({});return{kind:"call",fn:"map",args:[i,{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:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>O(l))}}}function Qo(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 Xo(t){let e=Qo(t.domain.name);Jo(t.domain,e);let n=Zo(t.domain,e),o=er(t.domain,e),r=nr(t.domain,e),i=sr(t.domain,e);if(e.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:e.diagnostics};let a={id:`mel:${t.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:o,computed:r,actions:i,meta:{name:t.domain.name}},s=kr(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function tn(t){let e=Xo(t);return e.schema?{schema:Jt(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function Jo(t,e){for(let n of t.types)e.typeDefs.set(n.name,n);for(let n of t.members)if(n.kind==="state")for(let o of n.fields)e.stateFields.add(o.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function Zo(t,e){let n={};for(let o of t.types){let r=V(o.typeExpr);e.typeDefinitions.set(o.name,r),n[o.name]={name:o.name,definition:r}}return n}function V(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:V(t.elementType)};case"recordType":return{kind:"record",key:V(t.keyType),value:V(t.valueType)};case"objectType":let e={};for(let o of t.fields)e[o.name]={type:V(o.typeExpr),optional:o.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(V)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function er(t,e){let n={},o={};for(let r of t.members)if(r.kind==="state")for(let i of r.fields){let a=V(i.typeExpr);o[i.name]=a,e.stateFieldTypes.set(i.name,a);let s=Z(i.typeExpr,e);s&&e.stateFieldSpecs.set(i.name,s);let c=tr(i,e);c&&(n[i.name]=c)}return{fields:n,fieldTypes:o}}function tr(t,e){let n=Z(t.typeExpr,e);if(!n)return null;let o=t.initializer?Ue(t.initializer,e):void 0;return o!==void 0&&Te(o,V(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:o}}function Z(t,e,n=[]){switch(t.kind){case"simpleType":switch(t.name){case"string":return{type:"string",required:!0};case"number":return{type:"number",required:!0};case"boolean":return{type:"boolean",required:!0};case"null":return{type:"null",required:!0};default:{let o=e.typeDefs.get(t.name);return o?n.includes(t.name)?(ft(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):Z(o.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let o=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),r=o.length!==t.types.length,i=[],a=!r;for(let s of o){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:r&&o.length===1?Z(o[0],e,n):(ft(e,"E043",`Union type '${ie(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let o=Z(t.elementType,e,n);return o?{type:"array",required:!0,items:o}: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 o={};for(let r of t.fields){let i=Z(r.typeExpr,e,n);if(!i)return null;o[r.name]={...i,required:!r.optional}}return{type:"object",required:!0,fields:o}}}}function ft(t,e,n,o){t.diagnostics.push({severity:"error",code:e,message:n,location:o})}function ie(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>ie(e)).join(" | ");case"arrayType":return`Array<${ie(t.elementType)}>`;case"recordType":return`Record<${ie(t.keyType)}, ${ie(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${ie(e.typeExpr)}`).join("; ")} }`}}function Ne(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let o=e.typeDefinitions.get(t.name);return o?Ne(o,e,[...n,t.name]):null}function W(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${W(t.element)}>`;case"record":return`Record<${W(t.key)}, ${W(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${W(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>W(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function ke(t,e,n){let o=Ne(e,n);if(!o)return!1;switch(o.kind){case"primitive":switch(o.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,o.value);case"array":return Array.isArray(t)&&t.every(r=>ke(r,o.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(r=>ke(r,o.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let r of Object.keys(t))if(!(r in o.fields))return!1;for(let[r,i]of Object.entries(o.fields)){if(!(r in t)){if(!i.optional)return!1;continue}if(!ke(t[r],i.type,n))return!1}return!0;case"union":return o.types.some(r=>ke(t,r,n));case"ref":return!1}}function Te(t,e,n,o,r){if(t===void 0)return;let i=Ne(e,r);if(!i){r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(e)}, got ${JSON.stringify(t)}`,location:o});return}if(i.kind==="union"){if(ke(t,i,r))return;r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(i)}, got ${JSON.stringify(t)}`,location:o});return}switch(i.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(i.type){case"null":t!==null&&J(r,n,"null",a,o);return;case"string":case"number":case"boolean":typeof t!==i.type&&J(r,n,i.type,a,o);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&J(r,n,"object",a,o);return;case"array":Array.isArray(t)||J(r,n,"array",a,o);return}return}case"literal":Object.is(t,i.value)||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(t)}`,location:o});return;case"array":if(!Array.isArray(t)){J(r,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,o);return}for(let a=0;a<t.length;a+=1)Te(t[a],i.element,`${n}[${a}]`,o,r);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;J(r,n,"object",a,o);return}for(let[a,s]of Object.entries(t))Te(s,i.value,`${n}.${a}`,o,r);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;J(r,n,"object",a,o);return}for(let a of Object.keys(t))a in i.fields||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${W(i)}`,location:o});for(let[a,s]of Object.entries(i.fields)){if(!(a in t)){s.optional||r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:o});continue}Te(t[a],s.type,`${n}.${a}`,o,r)}return;case"ref":r.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${W(e)}, got ${JSON.stringify(t)}`,location:o});return}}function J(t,e,n,o,r){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${o}`,location:r})}function Ue(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>Ue(n,e));case"objectLiteral":{let n={};for(let o of t.properties)n[o.key]=Ue(o.value,e);return n}default:return}}function nr(t,e){let n=[],o=0;for(let i of t.members)if(i.kind==="computed"){let a=B(i.expression,e),s=ar(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:o}),o+=1}let r={};for(let i of or(n,e))r[i.name]={deps:i.deps,expr:i.expr};return{fields:r}}function or(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),o=new Map,r=new Map,i=new Map;for(let c of t)r.set(c.name,[]),i.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));o.set(c.name,l),i.set(c.name,l.length);for(let d of l)r.get(d).push(c.name)}let a=t.filter(c=>(i.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 r.get(c)??[]){let d=(i.get(l)??0)-1;i.set(l,d),d===0&&rr(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=ir(l[0].name,o),p=d?d.join(" -> "):l.map(m=>m.name).join(", ");return ft(e,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function rr(t,e,n){let o=n.get(e)?.order??Number.MAX_SAFE_INTEGER,r=t.length;for(let i=0;i<t.length;i+=1){let a=n.get(t[i])?.order??Number.MAX_SAFE_INTEGER;if(o<a){r=i;break}}t.splice(r,0,e)}function ir(t,e){let n=new Set,o=[],r=new Set;function i(a){n.add(a),o.push(a),r.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(r.has(s)){let c=o.indexOf(s);return[...o.slice(c),s]}}else{let c=i(s);if(c)return c}return o.pop(),r.delete(a),null}return i(t)}function ar(t){let e=new Set;function n(o){switch(o.kind){case"lit":case"sys":case"var":return;case"get":o.base===void 0?e.add(o.path.map(r=>r.name).join(".")):n(o.base);return;case"field":n(o.object);return;case"call":for(let r of o.args)n(r);return;case"obj":for(let r of o.fields)n(r.value);return;case"arr":for(let r of o.elements)n(r);return}}return n(t),Array.from(e)}function sr(t,e){let n={};for(let o of t.members)if(o.kind==="action"){e.currentAction=o.name,e.onceIntentCounters.set(o.name,0);let r=new Set;for(let p of o.params)r.add(p.name);e.actionParams.set(o.name,r);let i=o.params.map(p=>p.name),a=nn(o.body,e),s,c;if(o.params.length>0){let p={},m={};for(let f of o.params){let N=Z(f.typeExpr,e);N&&(p[f.name]=structuredClone(N),m[f.name]={type:V(f.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:m}}let l;o.available&&(l=B(o.available,e));let d;o.dispatchable&&(d=B(o.dispatchable,e,{preferActionParams:!0})),n[o.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},e.currentAction=null}return n}function nn(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Be(t[0],e):{kind:"seq",steps:t.map(n=>Be(n,e))}}function Be(t,e){switch(t.kind){case"when":return cr(t,e);case"once":return lr(t,e);case"onceIntent":return dr(t,e);case"patch":return pr(t,e);case"effect":return ur(t,e);case"fail":return fr(t,e);case"stop":return hr(t,e);case"include":return{kind:"seq",steps:[]}}}function cr(t,e){let n=B(t.condition,e),o=nn(t.body,e);return{kind:"if",cond:n,then:o}}function lr(t,e){let n=ht(t.marker,e),o=Ee("meta","intentId"),r=ze("neq",[U(...on(n)),o]);if(t.condition){let s=B(t.condition,e);r=ze("and",[r,s])}let i={kind:"patch",op:"set",path:yt(n),value:o},a=t.body.map(s=>Be(s,e));return{kind:"if",cond:r,then:{kind:"seq",steps:[i,...a]}}}function dr(t,e){let n=e.currentAction??"unknown",o=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,o+1);let r=Yo(`${n}:${o}:intent`),i=`$mel.guards.intent.${r}`,a=Ee("meta","intentId"),s=ze("neq",[U(...on(i)),a]);if(t.condition){let d=B(t.condition,e);s=ze("and",[s,d])}let c={kind:"patch",op:"merge",path:yt("$mel.guards.intent"),value:_e({[r]:a})},l=t.body.map(d=>Be(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function pr(t,e){let n=ht(t.path,e),o={kind:"patch",op:t.op,path:yt(n)};if(t.value){let r=B(t.value,e);if(o.value=r,t.op==="set"){let i=t.path.segments[0];if(i.kind==="propertySegment"){let a=e.stateFieldTypes.get(i.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?Ne(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let m=p.types.filter(f=>{let N=Ne(f,e);return!(N?.kind==="primitive"&&N.type==="null")&&!(N?.kind==="literal"&&N.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=mr(t.value,e);if(l!==void 0){let d=t.path.segments.map(p=>p.kind==="propertySegment"?p.name:"[*]").join(".");Te(l,s,d,t.location,e)}}}}}}return o}function ur(t,e){let n={};for(let o of t.args)o.isPath?n[o.name]={kind:"lit",value:ht(o.value,e)}:n[o.name]=B(o.value,e);return{kind:"effect",type:t.effectType,params:n}}function mr(t,e){return Ue(t,e)}function fr(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=B(t.message,e)),n}function hr(t,e){return{kind:"halt",reason:t.reason}}function yr(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Ge(...t){return t.map(yr).join(".")}function ht(t,e){let n=[];for(let r of t.segments)if(r.kind==="propertySegment")n.push(r.name);else{let i=B(r.index,e);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let o=n[0];return e.stateFields.has(o)?Ge(...n):e.computedFields.has(o)?Ge(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(o)?`input.${Ge(...n)}`:Ge(...n)}function yt(t){return Wo(t)}function ze(t,e){return{kind:"call",fn:t,args:e}}function on(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function B(t,e,n={}){return w(t,{resolveIdentifier:o=>gr(o,e,n),resolveSystemIdent:o=>Er(o,e)})}function gr(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("input",t):e.stateFields.has(t)||e.computedFields.has(t)?U(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?U("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}}}),U(t))}function Er(t,e){let[n,...o]=t;switch(n){case"system":case"meta":case"input":return Ee(n,...o);default:return e.diagnostics.push({severity:"error",code:"E_INVALID_SYSTEM",message:`Invalid system identifier namespace '$${n}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),{kind:"lit",value:null}}}function kr(t){return Vo(t)}var Tr="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",Nr="Action-parameter annotations are not part of the current MEL syntax.",rn="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",an="Annotation payload nesting exceeds the current MEL limit of 2 levels.",br="Annotation target does not map to the emitted DomainSchema.",sn=2;function cn(t,e){let n=[],o=new Map,r=t.domain;ae(r.annotations,`domain:${r.name}`,n,o);for(let a of r.types)ae(a.annotations,`type:${a.name}`,n,o),se(a.typeExpr,a.name,0,n,o);for(let a of r.members)switch(a.kind){case"state":for(let s of a.fields)ae(s.annotations,`state_field:${s.name}`,n,o),ee(s.typeExpr,n);break;case"computed":ae(a.annotations,`computed:${a.name}`,n,o);break;case"action":ae(a.annotations,`action:${a.name}`,n,o),Sr(a,n);for(let s of a.params)ee(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...o.keys()].sort()){if(!Ar(e,a)){n.push(P("E057",br,wr(t,a)??r.location));continue}let s=o.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>vr(c))))}return{annotations:Object.freeze({schemaHash:e.hash,entries:Object.freeze(i)}),diagnostics:n}}function ae(t,e,n,o){if(!t||t.length===0)return;let r=[];for(let a of t){let s=a.payload===void 0?{ok:!0,value:void 0}:gt(a.payload,0,n);s.ok&&r.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(r.length===0)return;let i=o.get(e);if(i){i.push(...r);return}o.set(e,r)}function se(t,e,n,o,r){switch(t.kind){case"objectType":for(let i of t.fields)i.annotations?.length&&(n===0?ae(i.annotations,`type_field:${e}.${i.name}`,o,r):ln(i.annotations,o)),se(i.typeExpr,e,n+1,o,r);return;case"arrayType":se(t.elementType,e,n,o,r);return;case"recordType":se(t.keyType,e,n,o,r),se(t.valueType,e,n,o,r);return;case"unionType":for(let i of t.types)se(i,e,n,o,r);return;case"simpleType":case"literalType":return}}function ee(t,e){switch(t.kind){case"objectType":for(let n of t.fields)ln(n.annotations,e),ee(n.typeExpr,e);return;case"arrayType":ee(t.elementType,e);return;case"recordType":ee(t.keyType,e),ee(t.valueType,e);return;case"unionType":for(let n of t.types)ee(n,e);return;case"simpleType":case"literalType":return}}function Sr(t,e){for(let n of t.params)xr(n,e)}function xr(t,e){if(t.annotations)for(let n of t.annotations)e.push(P("E054",Nr,n.location))}function ln(t,e){if(t)for(let n of t)e.push(P("E053",Tr,n.location))}function gt(t,e,n){switch(t.kind){case"literal":return t.literalType==="string"||t.literalType==="number"||t.literalType==="boolean"||t.literalType==="null"?{ok:!0,value:t.value}:(n.push(P("E055",rn,t.location)),{ok:!1});case"arrayLiteral":{if(e+1>sn)return n.push(P("E056",an,t.location)),{ok:!1};let o=[];for(let r of t.elements){let i=gt(r,e+1,n);if(!i.ok)return{ok:!1};o.push(i.value)}return{ok:!0,value:o}}case"objectLiteral":{if(e+1>sn)return n.push(P("E056",an,t.location)),{ok:!1};let o={};for(let r of t.properties){let i=gt(r.value,e+1,n);if(!i.ok)return{ok:!1};o[r.key]=i.value}return{ok:!0,value:o}}default:return n.push(P("E055",rn,t.location)),{ok:!1}}}function vr(t){return t.payload===void 0?Object.freeze({tag:t.tag}):Object.freeze({tag:t.tag,payload:Et(t.payload)})}function Et(t){if(Array.isArray(t))return Object.freeze(t.map(e=>Et(e)));if(t!==null&&typeof t=="object"){let e={};for(let[n,o]of Object.entries(t))e[n]=Et(o);return Object.freeze(e)}return t}function Ar(t,e){let n=e.indexOf(":");if(n<0)return!1;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.meta?.name===r||t.id===`mel:${r.toLowerCase()}`;case"type":return Object.hasOwn(t.types,r);case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return!1;let a=r.slice(0,i),s=r.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,r);case"computed":return Object.hasOwn(t.computed.fields,r);case"action":return Object.hasOwn(t.actions,r);default:return!1}}function wr(t,e){let n=e.indexOf(":");if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+1),i=t.domain;if(o==="domain"&&i.name===r)return i.location;if(o==="type")return i.types.find(a=>a.name===r)?.location??null;if(o==="type_field"){let a=r.indexOf(".");if(a<=0)return null;let s=r.slice(0,a),c=r.slice(a+1),l=i.types.find(d=>d.name===s);return!l||l.typeExpr.kind!=="objectType"?l?.location??null:l.typeExpr.fields.find(d=>d.name===c)?.location??l.location}if(o==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===r);if(s)return s.location}return null}return o==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===r)?.location??null:o==="action"?i.members.find(a=>a.kind==="action"&&a.name===r)?.location??null:null}var kt=16;function T(t){return structuredClone(t)}function A(t,e,n,o,r){let i=`${n}:${r.start.offset}:${r.end.offset}:${o}`;e.has(i)||(e.add(i),t.push(P(n,o,r)))}function Cr(t){let e=new Map,n=new Set,o=new Map,r=new Set,i=new Map;for(let a of t.types)o.set(a.name,a);for(let a of t.members)switch(a.kind){case"state":for(let s of a.fields)e.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":r.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:o,actionNames:r,flows:i}}function Pr(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Ir(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function Mr(t,e,n,o){let r=new Map;for(let i of e.flows.values()){r.set(i.name,[]),e.actionNames.has(i.name)&&A(n,o,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&A(n,o,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Pr(i);for(let s of i.body)Rr(s,i.name,a,e,n,o,r.get(i.name))}for(let i of t.members)if(i.kind==="action"){let a=Ir(i);for(let s of i.body)Dr(s,a,e,n,o)}return r}function Dr(t,e,n,o,r){switch(t.kind){case"include":He(t,e,n,o,r);break;case"when":for(let i of t.body)le(i,e,n,o,r);break;case"once":for(let i of t.body)le(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)le(i,e,n,o,r);break;case"fail":case"stop":break}}function le(t,e,n,o,r){switch(t.kind){case"include":A(o,r,"E016","include is only allowed at action or flow body top-level.",t.location),He(t,e,n,o,r);break;case"when":for(let i of t.body)le(i,e,n,o,r);break;case"once":for(let i of t.body)le(i,e,n,o,r);break;case"onceIntent":for(let i of t.body)le(i,e,n,o,r);break;case"patch":case"effect":case"fail":case"stop":break}}function Rr(t,e,n,o,r,i,a){switch(t.kind){case"include":He(t,n,o,r,i)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)qe(s,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break}}function qe(t,e,n,o,r,i){switch(t.kind){case"include":A(r,i,"E016","include is only allowed at action or flow body top-level.",t.location),He(t,n,o,r,i);break;case"when":for(let a of t.body)qe(a,e,n,o,r,i);break;case"once":A(r,i,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)qe(a,e,n,o,r,i);break;case"onceIntent":A(r,i,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)qe(a,e,n,o,r,i);break;case"patch":A(r,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":A(r,i,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function He(t,e,n,o,r){let i=n.flows.get(t.flowName);if(!i)return A(o,r,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==i.params.length)return A(o,r,"E023",`include '${t.flowName}' expected ${i.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=i.params[a],l=be(s,e,n);if(!l)continue;ce(l,c.typeExpr,n)===!1&&A(o,r,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function Or(t,e,n,o){function r(i,a,s){s.add(i);for(let c of t.get(i)??[]){if(a+1>kt){A(n,o,"E014",`Include expansion depth exceeds limit (${kt}).`,c.location);continue}if(s.has(c.target)){A(n,o,"E013","Circular include detected.",c.location);continue}r(c.target,a+1,new Set(s))}}for(let i of e.flows.keys())r(i,1,new Set)}function M(t,e){switch(t.kind){case"identifier":return e.has(t.name)?T(e.get(t.name)):T(t);case"systemIdent":case"literal":case"iterationVar":return T(t);case"functionCall":return{...T(t),args:t.args.map(n=>M(n,e))};case"binary":return{...T(t),left:M(t.left,e),right:M(t.right,e)};case"unary":return{...T(t),operand:M(t.operand,e)};case"ternary":return{...T(t),condition:M(t.condition,e),consequent:M(t.consequent,e),alternate:M(t.alternate,e)};case"propertyAccess":return{...T(t),object:M(t.object,e)};case"indexAccess":return{...T(t),object:M(t.object,e),index:M(t.index,e)};case"objectLiteral":return{...T(t),properties:t.properties.map(n=>({...T(n),value:M(n.value,e)}))};case"arrayLiteral":return{...T(t),elements:t.elements.map(n=>M(n,e))}}}function Lr(t,e){switch(t.kind){case"when":return[dn(t,e)];case"fail":return[{...T(t),message:t.message?M(t.message,e):void 0}];case"stop":return[T(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function dn(t,e){return{...T(t),condition:M(t.condition,e),body:t.body.flatMap(n=>Lr(n,e))}}function Fr(t,e,n){let o=new Map;for(let r=0;r<t.params.length;r+=1)o.set(t.params[r].name,M(e.args[r],n));return o}function jr(t,e,n,o,r){switch(t.kind){case"when":return[dn(t,n)];case"include":return pn(t,e,n,o,r);case"once":case"onceIntent":case"patch":case"effect":return[]}}function pn(t,e,n,o,r){let i=e.flows.get(t.flowName);if(!i||t.args.length!==i.params.length||o>kt||r.includes(t.flowName))return[];let a=Fr(i,t,n),s=[...r,t.flowName];return i.body.flatMap(c=>jr(c,e,a,o+1,s))}function de(t){switch(t.kind){case"when":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"once":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(e=>de(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[T(t)]}}function _r(t,e,n){switch(t.kind){case"include":return pn(t,e,new Map,n,[]);case"when":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"once":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"onceIntent":return[{...T(t),body:t.body.flatMap(o=>de(o))}];case"fail":case"stop":return[T(t)]}}function $r(t,e){let n=[];for(let o of t.domain.members)switch(o.kind){case"state":case"computed":n.push(T(o));break;case"action":n.push({...T(o),body:o.body.flatMap(r=>_r(r,e,1))});break;case"flow":break}return{...T(t),domain:{...T(t.domain),types:t.domain.types.map(o=>T(o)),members:n}}}function be(t,e,n){switch(t.kind){case"literal":return{kind:"literalType",value:t.value,location:t.location};case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??null;case"propertyAccess":{let o=be(t.object,e,n);return un(o,t.property,n)}case"indexAccess":{let o=be(t.object,e,n);return mn(o,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(o=>{let r=be(o.value,e,n);return r?{kind:"typeField",name:o.key,typeExpr:r,optional:!1,location:o.location}:null}).filter(o=>o!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let o=be(t.elements[0],e,n);return o?{kind:"arrayType",elementType:o,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function Se(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),Se(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function un(t,e,n){let o=Se(t,n);if(!o)return null;if(o.kind==="objectType")return o.fields.find(i=>i.name===e)?.typeExpr??null;if(o.kind==="unionType")for(let r of o.types){if(r.kind==="simpleType"&&r.name==="null")continue;let i=un(r,e,n);if(i)return i}return null}function mn(t,e){let n=Se(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType")for(let o of n.types){if(o.kind==="simpleType"&&o.name==="null")continue;let r=mn(o,e);if(r)return r}return null}function ce(t,e,n){let o=Se(t,n),r=Se(e,n);if(!o||!r)return null;if(r.kind==="unionType"){let i=r.types.map(a=>ce(o,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(o.kind==="unionType"){let i=o.types.map(a=>ce(a,r,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(r.kind==="simpleType"){if(o.kind==="simpleType")return o.name===r.name;if(o.kind==="literalType")return r.name==="null"?o.value===null:typeof o.value===r.name}if(r.kind==="literalType")return o.kind!=="literalType"?!1:o.value===r.value;if(r.kind==="arrayType")return o.kind!=="arrayType"?!1:ce(o.elementType,r.elementType,n);if(r.kind==="objectType"){if(o.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=ce(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return r.kind==="recordType"?o.kind!=="recordType"?null:ce(o.valueType,r.valueType,n):null}function fn(t){let e=Cr(t.domain),n=[],o=new Set,r=Mr(t.domain,e,n,o);return Or(r,e,n,o),{program:$r(t,e),diagnostics:n}}var Gr=new Set(["$item","$index","$array"]);function gn(t){let e=Object.keys(t.state.fields).filter(d=>!d.startsWith("$")),n=Ur(t),o=new Set(n),r=new Set(e),i=Object.keys(t.actions),a=[...e.map(d=>({id:Tt(d),kind:"state",name:d})),...n.map(d=>({id:Nt(d),kind:"computed",name:d})),...i.map(d=>({id:yn(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,m)=>{if(!d||!p)return;let f=`${d}|${m}|${p}`;s.has(f)||(s.add(f),c.push({from:d,to:p,relation:m}))};for(let d of n){let p=t.computed.fields[d];if(p)for(let m of p.deps)l(hn(m,t,o,r),Nt(d),"feeds")}for(let d of i){let p=t.actions[d],m=yn(d);for(let f of Br(p.flow,t))r.has(f)&&l(m,Tt(f),"mutates");if(p.available)for(let f of bn(p.available))l(hn(f,t,o,r),m,"unlocks")}return Hr({nodes:a,edges:c})}function Ur(t){let e=t.computed.fields,n=new Map,o=(r,i)=>{let a=n.get(r);if(a!==void 0)return a;if(i.has(r))return!1;i.add(r);let s=e[r];if(!s)return i.delete(r),n.set(r,!0),!0;for(let c of bn(s.expr)){if(Nn(c))return i.delete(r),n.set(r,!1),!1;let l=En(c,e);if(l!==null&&!o(l,i))return i.delete(r),n.set(r,!1),!1}return i.delete(r),n.set(r,!0),!0};return Object.keys(e).filter(r=>o(r,new Set))}function Br(t,e){let n=new Set,o=(r,i)=>{if(r)switch(r.kind){case"seq":r.steps.forEach(a=>o(a,i));return;case"if":o(r.then,i),o(r.else,i);return;case"patch":{let a=zr(r.path);a&&n.add(a);return}case"effect":{let a=qr(r.params.into);a&&n.add(a);return}case"call":{if(i.has(r.flow))return;let a=e.actions[r.flow];if(!a)return;let s=new Set(i);s.add(r.flow),o(a.flow,s);return}case"halt":case"fail":return}};return o(t,new Set),[...n]}function zr(t){let[e]=t;return!e||e.kind!=="prop"||e.name.startsWith("$")?null:e.name}function qr(t){return typeof t!="object"||t===null||t.kind!=="lit"||typeof t.value!="string"?null:kn(t.value)}function hn(t,e,n,o){let r=En(t,e.computed.fields);if(r!==null&&n.has(r))return Nt(r);if(Nn(t))return null;let i=kn(t);return!i||!o.has(i)?null:Tt(i)}function En(t,e){if(Object.prototype.hasOwnProperty.call(e,t))return t;if(!t.startsWith("computed."))return null;let n=t.slice(9);return Object.prototype.hasOwnProperty.call(e,n)?n:null}function kn(t){let e=Tn(t),n=e.startsWith("data.")?e.slice(5):e,o=/^([^.[\]]+)/.exec(n);if(!o)return null;let[r]=o.slice(1);return!r||r.startsWith("$")?null:r}function Tn(t){return t.startsWith("/")?t.slice(1).replace(/\//g,"."):t}function Nn(t){let e=Tn(t),n=e.startsWith("data.")?e.slice(5):e,r=/^([^.[\]]+)/.exec(n)?.[1]??"";return r.startsWith("$")?!Gr.has(r):!1}function bn(t){let e=[],n=new WeakSet,o=r=>{if(r==null)return;if(Array.isArray(r)){r.forEach(o);return}if(typeof r!="object")return;let i=r;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){e.push(i.path);return}for(let a of Object.values(i))o(a)}};return o(t),e}function Tt(t){return`state:${t}`}function Nt(t){return`computed:${t}`}function yn(t){return`action:${t}`}function Hr(t){return Object.freeze({nodes:Object.freeze(t.nodes.map(e=>Object.freeze(e))),edges:Object.freeze([...t.edges].sort(Kr).map(e=>Object.freeze(e)))})}function Kr(t,e){return t.from.localeCompare(e.from)||t.to.localeCompare(e.to)||t.relation.localeCompare(e.relation)}var Vr="Source-map target does not map to the emitted DomainSchema.",Wr="Source-map entry missing for emitted DomainSchema target.",Yr=new TextEncoder;function wn(t){return Object.freeze({coordinateUnit:"utf16",compilerVersion:t,emissionOptionsFingerprint:"default"})}function Cn(t,e,n,o){let r=[],i=new Map,a=t.domain,s=Jr(e,o.coordinateUnit);i.set(`domain:${a.name}`,me({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,me({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),pe(l.typeExpr,l.name,0,i,s);for(let l of a.members)switch(l.kind){case"state":for(let d of l.fields)i.set(`state_field:${d.name}`,me({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,me({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,me({target:{kind:"action",action:{name:l.name}},span:s(l.location)}));break;case"flow":break}let c={};for(let l of[...i.keys()].sort()){if(!Xr(n,l)){r.push(P("E058",Vr,Sn(t,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of Qr(t,n))Object.hasOwn(c,l)||r.push(P("E058",Wr,Sn(t,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:vn(e),format:"manifesto/source-map-v1",coordinateUnit:o.coordinateUnit,emissionFingerprint:vn(`${o.coordinateUnit}\0${o.compilerVersion}\0${o.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:r}}function pe(t,e,n,o,r){switch(t.kind){case"objectType":for(let i of t.fields)n===0&&o.set(`type_field:${e}.${i.name}`,me({target:{kind:"type_field",type:{name:e},field:{name:i.name}},span:r(i.location)})),pe(i.typeExpr,e,n+1,o,r);return;case"arrayType":pe(t.elementType,e,n+1,o,r);return;case"recordType":pe(t.keyType,e,n+1,o,r),pe(t.valueType,e,n+1,o,r);return;case"unionType":for(let i of t.types)pe(i,e,n+1,o,r);return;case"simpleType":case"literalType":return}}function Qr(t,e){let n=new Set;n.add(`domain:${t.domain.name}`);for(let[o,r]of Object.entries(e.types))if(n.add(`type:${o}`),r.definition.kind==="object")for(let i of Object.keys(r.definition.fields))n.add(`type_field:${o}.${i}`);for(let o of Object.keys(e.state.fields))n.add(`state_field:${o}`);for(let o of Object.keys(e.computed.fields))n.add(`computed:${o}`);for(let o of Object.keys(e.actions))n.add(`action:${o}`);return[...n].sort()}function Xr(t,e){let n=e.indexOf(":");if(n<0)return!1;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.meta?.name===r||t.id===`mel:${r.toLowerCase()}`;case"type":return Object.hasOwn(t.types,r);case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return!1;let a=r.slice(0,i),s=r.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,r);case"computed":return Object.hasOwn(t.computed.fields,r);case"action":return Object.hasOwn(t.actions,r);default:return!1}}function Sn(t,e){let n=e.indexOf(":");if(n<0)return null;let o=e.slice(0,n),r=e.slice(n+1);switch(o){case"domain":return t.domain.name===r?t.domain.location:null;case"type":return t.domain.types.find(i=>i.name===r)?.location??null;case"type_field":{let i=r.indexOf(".");if(i<=0||i!==r.lastIndexOf("."))return null;let a=r.slice(0,i),s=r.slice(i+1),c=t.domain.types.find(l=>l.name===a);return c?ue(c.typeExpr,s,0):null}case"state_field":for(let i of t.domain.members){if(i.kind!=="state")continue;let a=i.fields.find(s=>s.name===r);if(a)return a.location}return null;case"computed":return t.domain.members.find(i=>i.kind==="computed"&&i.name===r)?.location??null;case"action":return t.domain.members.find(i=>i.kind==="action"&&i.name===r)?.location??null;default:return null}}function ue(t,e,n){switch(t.kind){case"objectType":for(let o of t.fields){if(n===0&&o.name===e)return o.location;let r=ue(o.typeExpr,e,n+1);if(r)return r}return null;case"arrayType":return ue(t.elementType,e,n+1);case"recordType":return ue(t.keyType,e,n+1)??ue(t.valueType,e,n+1);case"unionType":for(let o of t.types){let r=ue(o,e,n+1);if(r)return r}return null;case"simpleType":case"literalType":return null}}function Jr(t,e){return e==="utf16"?n=>Zr(n):n=>ei(n,t)}function Zr(t){return Object.freeze({start:Object.freeze({line:t.start.line,column:t.start.column}),end:Object.freeze({line:t.end.line,column:t.end.column})})}function ei(t,e){return Object.freeze({start:xn(t.start,e),end:xn(t.end,e)})}function xn(t,e){let n=An(e.slice(0,t.offset)),o=t.offset-(t.column-1),r=An(e.slice(0,o));return Object.freeze({line:t.line,column:n-r+1})}function me(t){return Object.freeze({target:ti(t.target),span:Object.freeze({start:Object.freeze({...t.span.start}),end:Object.freeze({...t.span.end})})})}function ti(t){switch(t.kind){case"domain":return Object.freeze({kind:t.kind,domain:Object.freeze({...t.domain})});case"type":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type})});case"type_field":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type}),field:Object.freeze({...t.field})});case"state_field":return Object.freeze({kind:t.kind,field:Object.freeze({...t.field})});case"computed":return Object.freeze({kind:t.kind,computed:Object.freeze({...t.computed})});case"action":return Object.freeze({kind:t.kind,action:Object.freeze({...t.action})})}}function vn(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return`fnv1a32:${e.toString(16).padStart(8,"0")}`}function An(t){return Yr.encode(t).length}import{sha256Sync as Ke}from"@manifesto-ai/core";function Pn(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function fe(t){return w(t)}var Ve=class{constructor(e){this.deps=e;this.exprValidator=new St(e.mapLocation)}conditionComposer=new bt;exprValidator;collect(e,n,o,r){return this.collectPatchStatements(e,n,o,r)}collectPatchStatements(e,n,o,r){let i=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:r});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=r;try{s=this.conditionComposer.and(r,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=Ke(`${o.actionName}:${o.whenCounter}:when`);o.whenCounter+=1;let l={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__whenGuards",location:a.location},{kind:"propertySegment",name:c,location:a.location}],location:a.location},d=xe(l),p=this.collectPatchStatements(a.body,n,o,void 0).map(m=>({patch:m.patch,condition:this.conditionComposer.and(d,m.condition)}));i.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=r,c=xe(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(_){n.push({severity:"error",code:"E_LOWER",message:_.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(r,p);let m=Ke(`${o.actionName}:${o.onceCounter}:once`);o.onceCounter+=1;let f={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:m,location:d}],location:d},N=xe(f),S=this.collectPatchStatements(a.body,n,o,N);i.push({patch:{kind:"patch",op:"set",path:f,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:N},...S,{patch:{kind:"patch",op:"unset",path:f,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Ke(`${o.actionName}:${o.onceCounter}:onceIntent`);o.onceCounter+=1;let c={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__onceScopeGuards",location:a.location},{kind:"propertySegment",name:s,location:a.location}],location:a.location},l=xe(c),d=Ke(`${o.actionName}:${o.onceIntentCounter}:intent`);o.onceIntentCounter+=1;let p=a.location,f={kind:"call",fn:"neq",args:[xe({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{f=this.conditionComposer.and(f,this.deps.toMelExpr(a.condition))??f}catch(z){n.push({severity:"error",code:"E_LOWER",message:z.message,location:this.deps.mapLocation(a.condition.location)})}}let N=this.conditionComposer.and(r,f),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},_=this.collectPatchStatements(a.body,n,o,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:N},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},..._,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:N});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 i}};function In(t){return{op:t.patch.op,path:ni(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:fe(t.patch.value)}:void 0}}function xe(t){let e=t.segments,n;for(let o of e){if(o.kind==="propertySegment"){let r={kind:"prop",name:o.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:o.name}]}:n={kind:"get",path:[r]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,fe(o.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function ni(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:fe(e.index)})}var bt=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},St=class{constructor(e){this.mapLocation=e}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(e,n){for(let o of e.segments)o.kind==="indexSegment"&&this.validateExpr(o.index,n)}validateExpr(e,n){switch(e.kind){case"functionCall":(e.name==="eq"||e.name==="neq")&&e.args.length>=2&&this.validatePrimitiveEquality(e.args[0],e.args[1],e.location,n);for(let o of e.args)this.validateExpr(o,n);return;case"binary":(e.operator==="=="||e.operator==="!=")&&this.validatePrimitiveEquality(e.left,e.right,e.location,n),this.validateExpr(e.left,n),this.validateExpr(e.right,n);return;case"unary":this.validateExpr(e.operand,n);return;case"ternary":this.validateExpr(e.condition,n),this.validateExpr(e.consequent,n),this.validateExpr(e.alternate,n);return;case"propertyAccess":this.validateExpr(e.object,n);return;case"indexAccess":this.validateExpr(e.object,n),this.validateExpr(e.index,n);return;case"objectLiteral":for(let o of e.properties)this.validateExpr(o.value,n);return;case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,o,r){let i=$(e,new Map,this.symbols),a=$(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||r.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(o)})}};function Dn(t){let e=[],n=0;for(let o of t)e.push(n),n+=o.length+1;return e}function Rn(t,e){return n=>On(n,t,e)}function xt(t,e,n){return t.map(o=>oi(o,e,n))}function oi(t,e,n){return{...t,location:On(t.location,e,n)}}function On(t,e,n){return{...t,start:Mn(t.start,e,n),end:Mn(t.end,e,n)}}function Mn(t,e,n){let o=t.line-3,r=e.length,i=Math.min(Math.max(o,1),r),a=n[i-1]??0,s=e[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var ve="__compileMelPatch",ii="__patchDomain",ai=" ";function Ln(t,e){let n=[],o=[],r=[],i=t.split(`
9
- `),a=Dn(i),s=Rn(i,a),c=si(t,ve),l=performance.now(),d;try{let x=Ae(c);d=x.tokens;let C=xt(x.diagnostics.filter(Q=>Q.severity==="error"),i,a);if(C.length>0)return r.push(...C),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:o,errors:r}}catch(x){return r.push({severity:"error",code:"E_LEX",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-l}),{ops:[],trace:n,warnings:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),m;try{let x=we(d),C=xt(x.diagnostics,i,a),Q=C.filter(We=>We.severity==="error"),F=C.filter(We=>We.severity!=="error");if(Q.length>0)return r.push(...Q),o.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};if(!x.program)return r.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),o.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:o,errors:r};m=x.program,o.push(...F)}catch(x){return r.push({severity:"error",code:"E_PARSE",message:x.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:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-p});let f=performance.now(),N={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=m.domain.members.find(x=>x.kind==="action"&&x.name===ve);if(!S)return r.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${ve}' 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()-f}),{ops:[],trace:n,warnings:o,errors:r};let _=i.length+3+2;if(S.location.end.line!==_)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ve}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let[z]=S.body;if(!z||z.kind!=="when"||!Pn(z.condition)||S.body.length!==1)return r.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${ve}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-f}),{ops:[],trace:n,warnings:o,errors:r};let g=new Ve({mapLocation:s,toMelExpr:fe}).collect(z.body,r,N,void 0);if(r.length===0&&t.trim()!==""&&g.length===0&&r.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(z.location)}),n.push({phase:"analyze",durationMs:performance.now()-f,details:{count:g.length}}),r.length>0)return{ops:[],trace:n,warnings:o,errors:r};let L=performance.now(),Y={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},q=[];for(let x of g)try{let C=In(x);q.push(je(C,Y))}catch(C){C instanceof j?r.push({severity:"error",code:C.code,message:C.message,location:s(x.patch.location)}):C instanceof Error?r.push({severity:"error",code:"E_LOWER",message:C.message,location:s(x.patch.location)}):r.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-L,details:{count:q.length}}),r.length>0?{ops:[],trace:n,warnings:o,errors:r}:{ops:q,trace:n,warnings:o,errors:r}}function si(t,e){let n=t.split(`
10
- `).map(o=>`${ai}${o}`).join(`
11
- `);return[`domain ${ii} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
12
- `)}var ci="3.5.0";function li(t,e){let n=Fn(t,e);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function di(t,e){let n=Fn(t,e);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:pi(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function Fn(t,e){let n=[],o=[],r=[],i=performance.now(),a;try{let g=Ae(t);a=g.tokens;let L=g.diagnostics.filter(q=>q.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r};let Y=g.diagnostics.filter(q=>q.severity==="warning");o.push(...Y)}catch(g){let L=g;return r.push({severity:"error",code:"E_LEX",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let g=we(a),L=g.diagnostics.filter(Y=>Y.severity==="error");if(L.length>0)return r.push(...L),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};c=g.program}catch(g){let L=g;return r.push({severity:"error",code:"E_PARSE",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:r}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=fn(c),p=d.diagnostics.filter(g=>g.severity==="error"),m=d.diagnostics.filter(g=>g.severity==="warning"),f=Ot(d.program),N=Vt(d.program),S=[...p,...f.diagnostics.filter(g=>g.severity==="error"),...N.diagnostics.filter(g=>g.severity==="error")],_=[...m,...f.diagnostics.filter(g=>g.severity==="warning"),...N.diagnostics.filter(g=>g.severity==="warning")];if(o.push(..._),n.push({phase:"analyze",durationMs:performance.now()-l}),S.length>0)return r.push(...S),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};let z=performance.now(),te=tn(d.program);n.push({phase:"generate",durationMs:performance.now()-z});for(let g of te.diagnostics)g.severity==="warning"?o.push(g):r.push(g);if(te.schema){let g=cn(d.program,te.schema),L=g.diagnostics.filter(F=>F.severity==="warning"),Y=g.diagnostics.filter(F=>F.severity==="error");if(o.push(...L),r.push(...Y),Y.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)};let q=wn(ci),x=Cn(d.program,t,te.schema,q),C=x.diagnostics.filter(F=>F.severity==="warning"),Q=x.diagnostics.filter(F=>F.severity==="error");return o.push(...C),r.push(...Q),Q.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)}:{program:d.program,schema:te.schema,annotations:g.annotations,sourceMap:x.sourceMap,trace:n,warnings:o,errors:he(r)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:o,errors:he(r)}}function pi(t,e,n){return Object.freeze({schema:t,graph:At(gn(t)),annotations:e,sourceMap:n})}function At(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let e of t)At(e);return Object.freeze(t)}for(let e of Object.values(t))At(e);return Object.freeze(t)}var vt=10;function he(t){if(t.length<=vt)return t;let e=t.slice(0,vt);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-vt} 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 ui(t,e){return Ln(t,e)}export{Ye as a,jn as b,mi as c,wt as d,Ct as e,Qe as f,Pt as g,It as h,hi as i,h as j,Xe as k,Ae as l,xi as m,vi as n,Mt as o,Je as p,Dt as q,wi as r,Ci as s,Rt as t,Ze as u,we as v,Ce as w,et as x,Ot as y,P as z,Lt as A,_i as B,_n as C,$i as D,Gi as E,it as F,Vt as G,at as H,st as I,ct as J,lt as K,lo as L,j as M,Oe as N,y as O,Le as P,dt as Q,po as R,pt as S,uo as T,u as U,Ro as V,Fo as W,je as X,Xo as Y,tn as Z,cn as _,fn as $,gn as aa,wn as ba,Cn as ca,li as da,di as ea,ui as fa};