@manifesto-ai/compiler 3.8.0 → 3.9.0

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.
@@ -0,0 +1,27 @@
1
+ var Ft={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"},jo=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 ac(e){return e in Ft}function Fn(e){return jo.has(e)}function jn(e){return Object.hasOwn(Ft,e)?Ft[e]:void 0}function jt(e,t,n,r){return{kind:e,lexeme:t,location:n,value:r}}function $n(e,t,n){return{line:e,column:t,offset:n}}function Gn(e,t,n){return{start:e,end:t,source:n}}function cc(e,t){return{start:e,end:e,source:t}}function k(e,t){return{start:e.start.offset<t.start.offset?e.start:t.start,end:e.end.offset>t.end.offset?e.end:t.end,source:e.source??t.source}}var $t=class{source;sourcePath;tokens=[];diagnostics=[];start=0;current=0;line=1;column=1;lineStart=0;constructor(t,n){this.source=t,this.sourcePath=n}tokenize(){for(;!this.isAtEnd();)this.start=this.current,this.scanToken();return this.tokens.push(jt("EOF","",this.currentLocation())),{tokens:this.tokens,diagnostics:this.diagnostics}}scanToken(){let t=this.advance();switch(t){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.peek()==="."&&this.peekNext()==="."?(this.advance(),this.advance(),this.addToken("ELLIPSIS")):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(t)?this.number():this.isAlpha(t)?this.identifier():this.error(`Unexpected character '${t}'`)}}lineComment(){for(;this.peek()!==`
3
+ `&&!this.isAtEnd();)this.advance()}blockComment(){let t=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 ${t}:${n}`)}string(t){let n=this.line,r=this.column-1,o="";for(;this.peek()!==t&&!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 t=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",t)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let t=this.source.slice(this.start,this.current);if(t.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(Fn(t)){this.error(`'${t}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=jn(t);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 t=this.source.slice(this.start,this.current);if(t==="$item"){this.addToken("ITEM");return}if(t==="$system"||t==="$meta"||t==="$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 '${t}'. Expected $system.*, $meta.*, $input.*, or $item`),this.addToken("ERROR")}isAtEnd(){return this.current>=this.source.length}advance(){let t=this.source[this.current];return this.current++,this.column++,t}peek(){return this.isAtEnd()?"\0":this.source[this.current]}peekNext(){return this.current+1>=this.source.length?"\0":this.source[this.current+1]}match(t){return this.isAtEnd()||this.source[this.current]!==t?!1:(this.current++,this.column++,!0)}newline(){this.line++,this.column=1,this.lineStart=this.current}isDigit(t){return t>="0"&&t<="9"}isHexDigit(t){return this.isDigit(t)||t>="a"&&t<="f"||t>="A"&&t<="F"}isAlpha(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"}isAlphaNumeric(t){return this.isAlpha(t)||this.isDigit(t)}currentLocation(){let t=this.positionAt(this.start),n=this.positionAt(this.current);return Gn(t,n,this.sourcePath)}positionAt(t){let n=1,r=0;for(let o=0;o<t;o++)this.source[o]===`
7
+ `&&(n++,r=o+1);return $n(n,t-r+1,t)}addToken(t,n){let r=this.source.slice(this.start,this.current);this.tokens.push(jt(t,r,this.currentLocation(),n))}error(t,n="MEL_LEXER"){let r=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:t,location:r,source:this.getSourceLine(r.start.line)})}getSourceLine(t){return this.source.split(`
8
+ `)[t-1]??""}};function j(e,t){return new $t(e,t).tokenize()}function gc(e){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(e.kind)}function Ec(e){return["when","once","onceIntent","patch","effect","fail","stop"].includes(e.kind)}var Bn=(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))(Bn||{});function Gt(e){switch(e){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 Vn(e){switch(e){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 kc(e){return Gt(e)!==0}function Nc(e){return e==="BANG"||e==="MINUS"}function Un(e){return e==="QUESTION"||e==="QUESTION_QUESTION"}var Bt=class{tokens;current=0;diagnostics=[];constructor(t){this.tokens=t}parse(){try{return{program:this.parseProgram(),diagnostics:this.diagnostics}}catch{return{program:null,diagnostics:this.diagnostics}}}parseProgram(){let t=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:k(t,o.location)}}parseImport(){let t=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:k(t,r.location)}}parseDomain(t=[]){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:t.length>0?t:void 0,types:o,members:i,location:k(n,a)}}parseTypeDecl(t=[]){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:t.length>0?t:void 0,typeExpr:o,location:k(n,o.location)}}parseDomainMember(t=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(t),this.parseState()):this.check("COMPUTED")?this.parseComputed(t):this.check("ACTION")?this.parseAction(t):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(t),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(t),this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let t=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:k(t,r)}}parseStateField(t=[]){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:t.length>0?t:void 0,typeExpr:r,initializer:o,location:k(n.location,o?.location??r.location)}}parseComputed(t=[]){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:t.length>0?t:void 0,expression:o,location:k(n,o.location)}}parseAction(t=[]){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:t.length>0?t:void 0,params:o,available:i,dispatchable:a,body:s,location:k(n,c)}}parseFlowDecl(){let t=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:k(t.location,i)}}parseParam(t=[]){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:t.length>0?t:void 0,typeExpr:r,location:k(n.location,r.location)}}parseGuardedStmt(){let t=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(t),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 t=this.parseAnnotationList();return this.reportUnsupportedAnnotations(t),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 t=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){t++,this.advance();continue}if(n.kind==="RBRACE"){if(t===0)return;t--,this.advance();continue}if(t===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let t=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:k(t,o)}}parseOnceStmt(){let t=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:k(t,i)}}parseOnceIntentStmt(){let t=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:k(t.location,o)}}parseInnerStmt(){let t=this.parseAnnotationList();return this.reportUnsupportedAnnotations(t),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 t=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:k(t.location,o)}}parsePatchStmt(){let t=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:k(t,i)}}parseEffectStmt(){let t=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:k(t,o)}}parseEffectArg(){let t=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(t.lexeme),r=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:t.lexeme,value:r,isPath:n,location:k(t.location,r.location)}}parseFailStmt(){let t=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:k(t,i)}}parseStopStmt(){let t=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:k(t,n.location)}}parseTypeExpr(){let t=this.parseBaseType();if(this.check("PIPE")){let n=[t];for(;this.match("PIPE");)n.push(this.parseBaseType());t={kind:"unionType",types:n,location:k(n[0].location,n[n.length-1].location)}}return t}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 t=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(t.lexeme==="Array"){let n=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:k(t.location,r)}}else if(t.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:k(t.location,o)}}else{for(this.error(`Unknown generic type '${t.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:t.lexeme,location:t.location}}parseObjectType(){let t=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:k(i.location,s.location)}),this.match("COMMA")}let r=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:k(t,r)}}parseExpression(t=0){let n=this.parsePrimary();for(;;){if(this.check("QUESTION")&&this.peekNext().kind==="DOT")throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Optional chaining is not supported.");let r=Gt(this.peek().kind);if(r<=t)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let o=Vn(this.peek().kind);if(!o)break;this.advance();let i=Un(this.previous().kind)?r-1:r,a=this.parseExpression(i);n={kind:"binary",operator:o,left:n,right:a,location:k(n.location,a.location)}}return n}parseTernary(t){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let r=this.parseExpression(0);return{kind:"ternary",condition:t,consequent:n,alternate:r,location:k(t.location,r.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let t=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:t.kind==="BANG"?"!":"-",operand:n,location:k(t.location,n.location)}}if(this.match("LPAREN")){let t=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),t}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let t=this.advance();return{kind:"literal",value:t.value,literalType:"number",location:t.location}}if(this.check("STRING")){let t=this.advance();return{kind:"literal",value:t.value,literalType:"string",location:t.location}}if(this.check("TRUE")||this.check("FALSE")){let t=this.advance();return{kind:"literal",value:t.kind==="TRUE",literalType:"boolean",location:t.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let t=this.advance(),n=t.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:t.location})}if(this.check("ITEM")){let t=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:t.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let t=this.advance();return this.parseFunctionCall(t)}if(this.check("IDENTIFIER")){let t=this.advance();return this.check("LPAREN")?this.parseFunctionCall(t):this.parsePostfix({kind:"identifier",name:t.lexeme,location:t.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(t){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:t.lexeme,args:n,location:k(t.location,r)})}parsePostfix(t){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");t={kind:"propertyAccess",object:t,property:n.lexeme,location:k(t.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),r=this.consume("RBRACKET","Expected ']' after index").location;t={kind:"indexAccess",object:t,index:n,location:k(t.location,r)}}else break;return t}parseObjectLiteral(){let t=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){if(this.check("LBRACKET"))throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Computed object keys are not supported.");if(this.match("ELLIPSIS")){let o=this.previous().location,i=this.parseExpression();n.push({kind:"objectSpread",expr:i,location:k(o,i.location)})}else{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:k(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:k(t,r)}}parseArrayLiteral(){let t=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();){if(this.check("ELLIPSIS"))throw this.errorAtCurrent("Object spread is the only bounded JavaScript-like sugar admitted in current MEL. Array spread is not supported.");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:k(t,r)}}parsePath(){let t=[],n=this.peek().location,r=this.consume("IDENTIFIER","Expected identifier");for(t.push({kind:"propertySegment",name:r.lexeme,location:r.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");t.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;t.push({kind:"indexSegment",index:i,location:k(i.location,a)})}else break;let o=t[t.length-1];return{kind:"path",segments:t,location:k(n,o.location)}}isUnaryContext(){if(this.current===0)return!0;let t=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(t.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(t){return this.current+t>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+t]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(t){return this.isAtEnd()?!1:this.peek().kind===t}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(...t){for(let n of t)if(this.check(n))return this.advance(),!0;return!1}consume(t,n){if(this.check(t))return this.advance();throw this.errorAtCurrent(n)}parseAnnotationList(){let t=[];for(;this.check("AT");)t.push(this.parseAnnotation());return t}parseAnnotation(){let t=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:k(t,i)}}reportUnsupportedAnnotations(t){for(let n of t)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(t){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:t,location:this.previous().location})}errorAtCurrent(t){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:t,location:this.peek().location}),new Error(t)}errorAtToken(t,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:t.location}),new Error(n)}};function me(e){return new Bt(e).parse()}var tt=class{parent;symbols=new Map;kind;constructor(t,n=null){this.kind=t,this.parent=n}define(t){this.symbols.set(t.name,t)}lookup(t){let n=this.symbols.get(t);return n||this.parent?.lookup(t)}isDefined(t){return this.symbols.has(t)}},Vt=class{diagnostics=[];scopes=new Map;currentScope=null;domainScope=null;analyze(t){return this.diagnostics=[],this.scopes=new Map,this.currentScope=null,this.domainScope=null,this.analyzeDomain(t.domain),{scopes:this.scopes,diagnostics:this.diagnostics}}analyzeDomain(t){let n=new tt("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let r of t.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 t.members)r.kind==="computed"?this.analyzeComputedExpr(r):r.kind==="action"&&this.analyzeAction(r)}analyzeComputedExpr(t){this.analyzeExpr(t.expression,"computed")}analyzeAction(t){let n=new tt("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${t.name}`,n);for(let r of t.params)n.define({name:r.name,kind:"param",location:r.location});for(let r of t.body)this.analyzeStmt(r);this.currentScope=this.domainScope}analyzeStmt(t){switch(t.kind){case"when":this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"onceIntent":t.condition&&this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"once":this.validatePath(t.marker),t.condition&&this.analyzeExpr(t.condition,"action");for(let n of t.body)this.analyzeStmt(n);break;case"patch":this.validatePath(t.path),t.value&&this.analyzeExpr(t.value,"action");break;case"effect":for(let n of t.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(t,n){switch(t.kind){case"identifier":this.checkIdentifier(t.name,t.location,n);break;case"systemIdent":this.checkSystemIdent(t.path,t.location,n);break;case"propertyAccess":this.analyzeExpr(t.object,n);break;case"indexAccess":this.analyzeExpr(t.object,n),this.analyzeExpr(t.index,n);break;case"functionCall":for(let r of t.args)this.analyzeExpr(r,n);break;case"binary":this.analyzeExpr(t.left,n),this.analyzeExpr(t.right,n);break;case"unary":this.analyzeExpr(t.operand,n);break;case"ternary":this.analyzeExpr(t.condition,n),this.analyzeExpr(t.consequent,n),this.analyzeExpr(t.alternate,n);break;case"objectLiteral":for(let r of t.properties)this.analyzeExpr(r.kind==="objectProperty"?r.value:r.expr,n);break;case"arrayLiteral":for(let r of t.elements)this.analyzeExpr(r,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(t,n,r){let o=this.currentScope?.lookup(t);if(!o){this.error(`Undefined identifier '${t}'`,n,"E_UNDEFINED");return}r==="computed"&&o.kind==="param"&&this.error(`Cannot access parameter '${t}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(t,n,r){let[o,...i]=t;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(t){if(!t||!t.segments)return;let n=t.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,t.location,"E_UNDEFINED"))}defineSymbol(t){if(this.currentScope){if(this.currentScope.isDefined(t.name)){this.error(`Duplicate identifier '${t.name}'`,t.location,"E_DUPLICATE");return}this.currentScope.define(t)}}error(t,n,r){this.diagnostics.push({severity:"error",code:r,message:t,location:n})}};function zn(e){return new Vt().analyze(e)}function D(e,t,n,r){return{severity:"error",code:e,message:t,location:n,...r}}function qn(e,t,n,r){return{severity:"warning",code:e,message:t,location:n,...r}}function Pc(e,t,n){return{severity:"info",code:e,message:t,location:n}}function $o(e){return e.severity==="error"}function Mc(e){return e.some($o)}function Dc(e,t){return e.filter(n=>n.severity===t)}function nt(e,t,n,r,o){let i=[],a=[],s=()=>{a.length!==0&&(i.push({kind:"objectType",fields:a,location:e.location}),a=[])};for(let c of e.properties){if(c.kind==="objectProperty"){let d=r(c.value,t,n);if(!d)return null;a.push({kind:"typeField",name:c.key,typeExpr:d,optional:!1,location:c.location});continue}s();let l=r(c.expr,t,n);if(!l)return null;i.push(l)}return s(),i.length===0?{kind:"objectType",fields:[],location:e.location}:Yn(i,e.location,n,o)}function rt(e,t,n,r,o){let i=e.args.map(a=>r(a,t,n));return i.some(a=>a===null)?null:Yn(i,e.location,n,o)}function Kn(e,t,n){let r=n(e,t);if(!r)return"unknown";if(r.kind==="objectType")return"object";if(r.kind!=="unionType")return"invalid";let o=r.types.map(s=>n(s,t)).filter(s=>s!==null),i=o.filter(s=>!pe(s));return o.some(s=>pe(s))&&i.length===1&&i[0].kind==="objectType"?"nullable-object":"invalid"}function Y(e,t){if(!e)return!1;if(Hn(Ut(e,t),t)||e.kind==="arrayLiteral")return!0;if(e.kind==="ternary")return Y(e.consequent,t)||Y(e.alternate,t);if(e.kind!=="functionCall")return!1;if(e.name==="coalesce"){for(let n of e.args)if(!be(n,t)){if(Y(n,t))return!0;if(Se(n,t))return!1}return!1}return(e.name==="cond"||e.name==="if")&&e.args.length>=3?Y(e.args[1],t)||Y(e.args[2],t):!1}function be(e,t){let n=Ut(e,t);return n&&Jn(n,t)?!0:e.kind==="literal"?e.value===null:e.kind==="ternary"?be(e.consequent,t)&&be(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.length>0&&e.args.every(r=>be(r,t)):(e.name==="cond"||e.name==="if")&&e.args.length>=3?be(e.args[1],t)&&be(e.args[2],t):!1}function Se(e,t){let n=Ut(e,t);return n&&Wn(n,t)?!0:e.kind==="literal"?e.value!==null:e.kind==="arrayLiteral"||e.kind==="objectLiteral"?!0:e.kind==="ternary"?Se(e.consequent,t)&&Se(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.some(r=>Se(r,t)):e.name==="merge"?!0:(e.name==="cond"||e.name==="if")&&e.args.length>=3?Se(e.args[1],t)&&Se(e.args[2],t):!1}function Ut(e,t){return t?t.resolveType(t.inferExprType(e,t.env,t.symbols),t.symbols):null}function Hn(e,t){if(!e||!t)return!1;let n=t.resolveType(e,t.symbols);return n?n.kind==="arrayType"?!0:n.kind==="unionType"?n.types.some(r=>Hn(r,t)):!1:!1}function Jn(e,t){if(!t)return pe(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>Jn(r,t)):pe(n):!1}function Wn(e,t){if(!t)return!pe(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>Wn(r,t)):!pe(n):!1}function Yn(e,t,n,r){let o=new Map;for(let i of e){let a=Go(i,n,r);if(!a)return null;for(let s of a){let c=o.get(s.name);if(!c){o.set(s.name,s);continue}if(!s.optional){o.set(s.name,s);continue}let l=Bo([c.typeExpr,s.typeExpr],s.location);if(!l)return null;o.set(s.name,{kind:"typeField",name:s.name,typeExpr:l,optional:c.optional,location:s.location})}}return{kind:"objectType",fields:[...o.values()],location:t}}function Go(e,t,n){let r=n(e,t);if(!r)return null;if(r.kind==="objectType")return r.fields.map(c=>({...c,optional:c.optional}));if(r.kind!=="unionType")return null;let o=r.types.map(c=>n(c,t)).filter(c=>c!==null),i=o.filter(c=>!pe(c));if(!o.some(c=>pe(c))||i.length!==1)return null;let s=i[0];return s.kind!=="objectType"?null:s.fields.map(c=>({...c,optional:!0}))}function pe(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function Bo(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);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:t}}var Xn=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),Zn=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),er=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),Vo=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Uo=new Set(["updateById","removeById"]);function ot(e){let t=new Map,n=new Map,r=new Map;for(let o of e.types)r.set(o.name,o);for(let o of e.members){if(o.kind==="state"){for(let i of o.fields)t.set(i.name,i.typeExpr);continue}o.kind==="computed"&&n.set(o.name,o)}return{stateTypes:t,computedDecls:n,typeDefs:r,computedTypeCache:new Map,computedTypeInFlight:new Set}}function it(e){let t=new Map;for(let n of e)t.set(n.name,n.typeExpr);return t}function T(e,t,n){switch(e.kind){case"literal":return oi(e.value,e.location);case"identifier":return t.get(e.name)??n.stateTypes.get(e.name)??zo(e.name,n);case"propertyAccess":return he(T(e.object,t,n),e.property,n);case"indexAccess":return ze(T(e.object,t,n),n);case"objectLiteral":return nt(e,t,n,T,S);case"arrayLiteral":{let r=M(e.elements.map(o=>T(o,t,n)),e.location);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"unary":return qo(e);case"binary":return Ko(e,t,n);case"ternary":return M([T(e.consequent,t,n),T(e.alternate,t,n)],e.location);case"functionCall":return Ho(e,t,n);case"systemIdent":return null;case"iterationVar":return t.get("$item")??null}}function Q(e,t,n){let r=T(e,t,n);if(r)return tr(r,n);switch(e.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return e.operator==="??"?Ve([Q(e.left,t,n),Q(e.right,t,n)]):e.operator==="=="||e.operator==="!="||e.operator==="+"||e.operator==="-"||e.operator==="*"||e.operator==="/"||e.operator==="%"||e.operator==="<"||e.operator==="<="||e.operator===">"||e.operator===">="||e.operator==="&&"||e.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return Ve([Q(e.consequent,t,n),Q(e.alternate,t,n)]);case"functionCall":return Vo.has(e.name)?"nonprimitive":Xn.has(e.name)||Zn.has(e.name)||er.has(e.name)||e.name==="toBoolean"?"primitive":(e.name==="cond"||e.name==="if")&&e.args.length>=3?Ve([Q(e.args[1],t,n),Q(e.args[2],t,n)]):e.name==="coalesce"?Ve(e.args.map(o=>Q(o,t,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function tr(e,t){let n=S(e,t);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 Ve(n.types.map(r=>tr(r,t)))}}function S(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),S(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function he(e,t,n){let r=S(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?M([o.typeExpr,L("null",o.location)],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!Z(i)).map(i=>he(i,t,n)).filter(i=>i!==null);return M(o,r.location)}return null}function ze(e,t){let n=S(e,t);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=>!Z(o)).map(o=>ze(o,t)).filter(o=>o!==null);return M(r,n.location)}return null}function X(e,t){let n=S(e,t);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(o=>!Z(o)).map(o=>X(o,t)).filter(o=>o!==null);return M(r,n.location)}return null}function at(e,t){let n=S(e,t);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=>at(r,t));default:return!1}}function Z(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function st(e,t){return Kn(e,t,S)}function zo(e,t){if(t.computedTypeCache.has(e))return t.computedTypeCache.get(e)??null;let n=t.computedDecls.get(e);if(!n||t.computedTypeInFlight.has(e))return null;t.computedTypeInFlight.add(e);let r=T(n.expression,new Map,t);return t.computedTypeInFlight.delete(e),t.computedTypeCache.set(e,r),r}function qo(e){return e.operator==="!"?L("boolean",e.location):L("number",e.location)}function Ko(e,t,n){switch(e.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return L("boolean",e.location);case"+":case"-":case"*":case"/":case"%":return L("number",e.location);case"??":return M([T(e.left,t,n),T(e.right,t,n)],e.location)}}function Ho(e,t,n){if(Xn.has(e.name))return L("boolean",e.location);if(Zn.has(e.name))return L("number",e.location);if(e.name==="idiv")return M([L("number",e.location),L("null",e.location)],e.location);if(er.has(e.name))return L("string",e.location);if(e.name==="toBoolean")return L("boolean",e.location);if(e.name==="findById"&&e.args.length>=1){let r=X(T(e.args[0],t,n),n);return r?M([r,L("null",e.location)],e.location):null}if(e.name==="find"&&e.args.length>=1){let r=X(T(e.args[0],t,n),n);return r?M([r,L("null",e.location)],e.location):null}if(e.name==="filter"&&e.args.length>=1)return T(e.args[0],t,n);if(e.name==="map"&&e.args.length>=2){let r=T(e.args[0],t,n),o=X(r,n);if(!o)return null;let i=T(e.args[1],ai(t,o),n);return i?{kind:"arrayType",elementType:i,location:e.location}:null}if((e.name==="first"||e.name==="last")&&e.args.length>=1)return X(T(e.args[0],t,n),n);if(e.name==="at"&&e.args.length>=1)return ze(T(e.args[0],t,n),n);if(e.name==="field"&&e.args.length>=2){let r=ii(e.args[1]);return r?he(T(e.args[0],t,n),r,n):null}return Uo.has(e.name)&&e.args.length>=1?T(e.args[0],t,n):(e.name==="cond"||e.name==="if")&&e.args.length>=3?M([T(e.args[1],t,n),T(e.args[2],t,n)],e.location):e.name==="coalesce"?ni(e,t,n):e.name==="match"?Jo(e,t,n):e.name==="argmax"||e.name==="argmin"?Wo(e,t,n):e.name==="slice"&&e.args.length>=1?T(e.args[0],t,n):e.name==="split"?{kind:"arrayType",elementType:L("string",e.location),location:e.location}:e.name==="keys"?{kind:"arrayType",elementType:L("string",e.location),location:e.location}:e.name==="values"&&e.args.length>=1?ri(e,t,n):e.name==="merge"?rt(e,t,n,T,S):null}function Ve(e){let t=!1;for(let n of e){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(t=!0)}return t?"unknown":"primitive"}function M(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);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:t}}function Jo(e,t,n){if(e.args.length<3)return null;let r=[];for(let o=1;o<e.args.length-1;o+=1){let i=e.args[o];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;r.push(T(i.elements[1],t,n))}return r.push(T(e.args[e.args.length-1],t,n)),M(r,e.location)}function Wo(e,t,n){if(e.args.length<2)return null;let r=[];for(let i=0;i<e.args.length-1;i+=1){let a=e.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;r.push(T(a.elements[0],t,n))}let o=M(r,e.location);return o?Xo(e,t,n)?o:M([o,L("null",e.location)],e.location):null}var Yo=Symbol("arg-selection:other-string"),Qo=Symbol("arg-selection:other-number");function Xo(e,t,n){let r=[];for(let c=0;c<e.args.length-1;c+=1){let l=e.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(!Ae(c,t,n,o))return!1;let i=[...o.values()].map(c=>({key:c.key,values:ei(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 nr(i,0,s,()=>r.some(c=>V(c,s)===!0))}function nr(e,t,n,r){if(t>=e.length)return r();let o=e[t];for(let i of o.values)if(n.set(o.key,i),!nr(e,t+1,n,r))return n.delete(o.key),!1;return n.delete(o.key),!0}function Ae(e,t,n,r){switch(e.kind){case"literal":return e.literalType==="boolean";case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":return Zo(e,t,n,r);case"unary":return e.operator==="!"&&Ae(e.operand,t,n,r);case"binary":return e.operator==="&&"||e.operator==="||"?Ae(e.left,t,n,r)&&Ae(e.right,t,n,r):e.operator==="=="||e.operator==="!="?Qn(e.left,e.right,t,n,r):!1;case"functionCall":switch(e.name){case"and":case"or":return e.args.every(o=>Ae(o,t,n,r));case"not":return e.args.length===1&&Ae(e.args[0],t,n,r);case"eq":case"neq":return e.args.length===2&&Qn(e.args[0],e.args[1],t,n,r);case"isNull":case"isNotNull":return e.args.length===1&&zt(e.args[0],t,n,r,null);default:return!1}default:return!1}}function Zo(e,t,n,r){let o=Ue(e),i=T(e,t,n);return!o||!i||!or(i,n)||Kt(e,t,n)?!1:(r.get(o)||r.set(o,{key:o,typeExpr:i,comparedLiterals:[]}),!0)}function Qn(e,t,n,r,o){let i=qt(e),a=qt(t);return i!==void 0&&a!==void 0?!0:a!==void 0?zt(e,n,r,o,a):i!==void 0?zt(t,n,r,o,i):!1}function zt(e,t,n,r,o){let i=Ue(e),a=T(e,t,n);if(!i||!a||!ir(a,n)||Kt(e,t,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 ei(e,t){let n=[],r=!1,o=a=>{n.some(s=>Object.is(s,a))||n.push(a)},i=a=>{let s=S(a,t);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 e.comparedLiterals)typeof c=="string"&&o(c);o(Yo);return;case"number":for(let c of e.comparedLiterals)typeof c=="number"&&o(c);o(Qo);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(e.typeExpr),r||n.length===0?null:n}function V(e,t){switch(e.kind){case"literal":return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0;case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":{let n=Ue(e);return n?t.get(n):void 0}case"unary":{let n=V(e.operand,t);return e.operator==="!"&&typeof n=="boolean"?!n:void 0}case"binary":{let n=V(e.left,t),r=V(e.right,t);switch(e.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(e.name){case"and":{let n=e.args.map(r=>V(r,t));return n.every(r=>typeof r=="boolean")?n.every(Boolean):void 0}case"or":{let n=e.args.map(r=>V(r,t));return n.every(r=>typeof r=="boolean")?n.some(Boolean):void 0}case"not":{let n=e.args.length===1?V(e.args[0],t):void 0;return typeof n=="boolean"?!n:void 0}case"eq":case"neq":{if(e.args.length!==2)return;let n=V(e.args[0],t),r=V(e.args[1],t);return n===void 0||r===void 0?void 0:e.name==="eq"?Object.is(n,r):!Object.is(n,r)}case"isNull":{if(e.args.length!==1)return;let n=V(e.args[0],t);return n===void 0?void 0:n===null}case"isNotNull":{if(e.args.length!==1)return;let n=V(e.args[0],t);return n===void 0?void 0:n!==null}case"cond":case"if":{if(e.args.length!==3)return;let n=V(e.args[0],t);return typeof n!="boolean"?void 0:V(n?e.args[1]:e.args[2],t)}default:return}default:return}}function Ue(e){switch(e.kind){case"identifier":return`id:${e.name}`;case"iterationVar":return"$item";case"propertyAccess":{let t=Ue(e.object);return t?`${t}.${e.property}`:null}case"indexAccess":{let t=Ue(e.object),n=qt(e.index);return t&&n!==void 0?`${t}[${JSON.stringify(n)}]`:null}default:return null}}function Kt(e,t,n){switch(e.kind){case"propertyAccess":return Ht(T(e.object,t,n),n)||ti(e.object,e.property,t,n)||Kt(e.object,t,n);case"indexAccess":return!0;default:return!1}}function ti(e,t,n,r){return rr(T(e,n,r),t,r)}function rr(e,t,n){let r=S(e,n);if(!r)return!0;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return!o||o.optional}if(r.kind==="unionType"){let o=r.types.filter(i=>!Z(i));return o.length===0||o.some(i=>rr(i,t,n))}return!0}function or(e,t){let n=S(e,t);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=>or(r,t));default:return!1}}function ir(e,t){let n=S(e,t);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=>ir(r,t));default:return!1}}function qt(e){if(e.kind==="literal")return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0}function ni(e,t,n){let r=e.args.map(a=>T(a,t,n));if(r.some(a=>a===null))return M(r,e.location);let o=r.map(a=>sr(a,n)).filter(a=>a!==null);if(o.length===0)return M(r,e.location);let i=[...o];return r.every(a=>a!==null&&Ht(a,n))&&i.push(L("null",e.location)),M(i,e.location)}function ri(e,t,n){if(e.args.length<1)return null;let r=ar(T(e.args[0],t,n),n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}function ar(e,t){let n=S(e,t);return n?n.kind==="recordType"?n.valueType:n.kind==="objectType"?M(n.fields.map(r=>r.typeExpr),n.location):n.kind==="unionType"?M(n.types.filter(r=>!Z(r)).map(r=>ar(r,t)),n.location):null:null}function sr(e,t){let n=S(e,t);if(!n||Z(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(o=>sr(o,t)).filter(o=>o!==null);return r.length===0?null:M(r,n.location)}function Ht(e,t){let n=S(e,t);return!n||Z(n)?!0:n.kind!=="unionType"?!1:n.types.some(r=>Ht(r,t))}function oi(e,t){return{kind:"literalType",value:e,location:t}}function L(e,t){return{kind:"simpleType",name:e,location:t}}function ii(e){return e.kind==="literal"&&typeof e.value=="string"?e.value:null}function ai(e,t){let n=new Map(e);return n.set("$item",t),n}var si=new Set(["findById","existsById"]),Wt=new Set(["updateById","removeById"]),ci=new Set([...si,...Wt]);function oe(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(D(n,r,o)))}function cr(e){let t=[],n=new Set,r=ot(e.domain);ui(e.domain,r,t,n);for(let o of e.domain.members)switch(o.kind){case"computed":C(o.expression,"computed",new Map,r,t,n,0);break;case"action":{let i=it(o.params);li(o,i,r,t,n);break}case"state":case"flow":break}return t}function li(e,t,n,r,o){e.available&&C(e.available,"available",t,n,r,o,0),e.dispatchable&&C(e.dispatchable,"dispatchable",t,n,r,o,0);for(let i of e.body)di(i,t,n,r,o)}function di(e,t,n,r,o){switch(e.kind){case"when":C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"once":e.condition&&C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"onceIntent":e.condition&&C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"include":break}}function ve(e,t,n,r,o){switch(e.kind){case"when":C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"once":e.condition&&C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"onceIntent":e.condition&&C(e.condition,"guard",t,n,r,o,0);for(let i of e.body)ve(i,t,n,r,o);break;case"patch":e.value&&C(e.value,"patch",t,n,r,o,0);break;case"effect":for(let i of e.args)i.isPath||C(i.value,"action",t,n,r,o,0);break;case"fail":e.message&&C(e.message,"action",t,n,r,o,0);break;case"include":case"stop":break}}function C(e,t,n,r,o,i,a){switch(e.kind){case"functionCall":{pi(e,t,n,r,o,i,a);let s=a+(Wt.has(e.name)?1:0);for(let c of e.args)C(c,t,n,r,o,i,s);break}case"binary":C(e.left,t,n,r,o,i,a),C(e.right,t,n,r,o,i,a);break;case"unary":C(e.operand,t,n,r,o,i,a);break;case"ternary":C(e.condition,t,n,r,o,i,a),C(e.consequent,t,n,r,o,i,a),C(e.alternate,t,n,r,o,i,a);break;case"propertyAccess":C(e.object,t,n,r,o,i,a);break;case"indexAccess":C(e.object,t,n,r,o,i,a),C(e.index,t,n,r,o,i,a);break;case"objectLiteral":for(let s of e.properties)C(s.kind==="objectProperty"?s.value:s.expr,t,n,r,o,i,a);break;case"arrayLiteral":for(let s of e.elements)C(s,t,n,r,o,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function pi(e,t,n,r,o,i,a){if(!ci.has(e.name)||e.args.length===0)return;Wt.has(e.name)&&(t==="available"?oe(o,i,"E035","updateById/removeById are not allowed in available conditions.",e.location):t==="dispatchable"?oe(o,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",e.location):t==="guard"?oe(o,i,"E034","updateById/removeById are not allowed in guard conditions.",e.location):t!=="patch"&&oe(o,i,"E031","updateById/removeById are only allowed in patch RHS.",e.location),a>0&&oe(o,i,"E032","Nested transform primitives are not allowed.",e.location),t==="patch"&&!Jt(e.args[0],r)&&oe(o,i,"E033","Transform primitive collection argument must resolve to a state path.",e.args[0].location));let s=mi(e.args[0],n,r);if(!s)return;let c=dr(s,r);if(!c){oe(o,i,"E030","Collection element type must declare an 'id' field for entity primitives.",e.args[0].location);return}at(c,r)||oe(o,i,"E030a","Entity 'id' field must be string or number.",e.args[0].location)}function ui(e,t,n,r){for(let o of e.members)if(o.kind==="state")for(let i of o.fields)fi(i,t,n,r)}function fi(e,t,n,r){if(!e.initializer||e.initializer.kind!=="arrayLiteral")return;let o=X(e.typeExpr,t);if(!o)return;let i=dr(o,t);if(!i||!at(i,t))return;let a=new Map;for(let s of e.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=lr(s);if(c.kind!=="literal")continue;let l=`${typeof c.value}:${String(c.value)}`;if(a.get(l)){oe(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.location);continue}a.set(l,c.location)}}function lr(e){if(e.kind!=="objectLiteral")return{kind:"unknown"};let t={kind:"absent"};for(let n of e.properties){if(n.kind==="objectProperty"){if(n.key!=="id")continue;if(n.value.kind==="literal"&&(typeof n.value.value=="string"||typeof n.value.value=="number")){t={kind:"literal",value:n.value.value,location:n.value.location};continue}t={kind:"unknown"};continue}let r=lr(n.expr);r.kind!=="absent"&&(t=r)}return t}function mi(e,t,n){return X(T(e,t,n),n)}function dr(e,t){return he(e,"id",t)}function Jt(e,t){switch(e.kind){case"identifier":return t.stateTypes.has(e.name);case"propertyAccess":return Jt(e.object,t);case"indexAccess":return Jt(e.object,t);default:return!1}}function pr(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var hi=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function b(e,t){return{kind:"simpleType",name:e,location:t}}function ee(e,t,n){let r=S(e,n),o=S(t,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=>ee(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=ee(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:ee(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}if(a.optional&&!i.optional)return!1;let s=ee(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:ee(r.valueType,o.valueType,n):null}function I(e,t){let n=S(e,t);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name;case"literalType":return JSON.stringify(n.value);case"arrayType":return`Array<${I(n.elementType,t)}>`;case"recordType":return`Record<${I(n.keyType,t)}, ${I(n.valueType,t)}>`;case"objectType":return`{ ${n.fields.map(r=>`${r.name}${r.optional?"?":""}: ${I(r.typeExpr,t)}`).join("; ")} }`;case"unionType":return n.types.map(r=>I(r,t)).join(" | ")}}function ct(e,t){let n=S(e,t);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=ct(o,t);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)r.add(a)}return r}}}function Yt(e,t){let n=ct(e,t);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 fr(e,t,n){let r=ct(e,n),o=ct(t,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 mr(e,t){let n=S(e,t);if(!n||Z(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(a=>mr(a,t)).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 Qt(e,t,n){if(!e||!t)return null;let r=ee(e,t,n);if(r===!0)return!0;let o=ee(t,e,n);if(o===!0)return!0;let i=fr(e,t,n);return i!==null?i:r===!1&&o===!1?!1:null}function Xt(e,t,n){let r=S(e,n),o=S(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=!1;for(let a of o.types){if(Z(a))continue;let s=Xt(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=Xt(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=ee(i.typeExpr,a.typeExpr,n);if(s!==!0)return s}return!0}function hr(e,t){let n=S(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>hr(o,t));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"}function yr(e,t){let n=S(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>yr(o,t));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 yi(e,t){let n=new Map(e);return n.set("$item",t),n}function ur(e){let t=lt(e);if(typeof t=="number")return t;if(e.kind==="literal")return e.literalType==="null"?null:typeof e.value=="string"||typeof e.value=="number"||typeof e.value=="boolean"?e.value:void 0}function lt(e){if(e.kind==="literal"&&e.literalType==="number"&&typeof e.value=="number")return e.value;if(e.kind==="unary"&&e.operator==="-"){let t=lt(e.operand);return typeof t=="number"?-t:void 0}}function gi(e,t){let[n,...r]=e.segments;if(!n||n.kind!=="propertySegment")return null;let o=t.stateTypes.get(n.name)??null;for(let i of r){if(!o)return null;o=i.kind==="propertySegment"?he(o,i.name,t):ze(o,t)}return o}function Ei(e){let t="";for(let[n,r]of e.segments.entries()){if(r.kind==="propertySegment"){t+=n===0?r.name:`.${r.name}`;continue}r.index.kind==="literal"?t+=`[${JSON.stringify(r.index.value)}]`:t+="[*]"}return t}var Zt=class{ctx=pr();symbols=null;validate(t){return this.ctx=pr(),this.symbols=ot(t.domain),this.validateDomain(t.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(t){t.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",t.location,"E_RESERVED_NAME");for(let n of t.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(t){let n=new Map;for(let r of t.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(t){this.checkAnonymousObjectType(t.typeExpr,t.location),t.initializer&&this.validateStateInitializer(t.initializer)}validateStateInitializer(t){switch(t.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",t.location,"E042");return;case"systemIdent":t.path[0]==="system"?this.error("$system.* cannot be used in state initializers",t.location,"E002"):this.error("State initializers must be compile-time constants",t.location,"E042");return;case"objectLiteral":for(let n of t.properties){if(n.kind==="objectProperty"){this.validateStateInitializer(n.value);continue}let r=this.ctx.diagnostics.length;this.validateStateInitializer(n.expr),r===this.ctx.diagnostics.length&&this.requireSpreadOperand(this.inferType(n.expr,new Map),n.location,n.expr,new Map)}return;case"arrayLiteral":for(let n of t.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let r of t.args)this.validateStateInitializer(r);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.left),this.validateStateInitializer(t.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.condition),this.validateStateInitializer(t.consequent),this.validateStateInitializer(t.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(t.object),this.validateStateInitializer(t.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",t.location,"E042");return}}}checkAnonymousObjectType(t,n){switch(t.kind){case"objectType":this.ctx.diagnostics.push(qn("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",t.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let r of t.fields)this.checkAnonymousObjectType(r.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(t.elementType,n);break;case"recordType":this.checkAnonymousObjectType(t.keyType,n),this.checkAnonymousObjectType(t.valueType,n);break;case"unionType":for(let r of t.types)this.checkAnonymousObjectType(r,n);break}}validateAction(t){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=it(t.params),t.available&&this.validateAvailableExpr(t.available),t.dispatchable&&this.validateDispatchableExpr(t.dispatchable);for(let n of t.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(t){switch(t.kind){case"identifier":this.ctx.currentActionParamTypes.has(t.name)&&this.error("Action parameters cannot be used in available condition",t.location,"E005");break;case"systemIdent":t.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",t.location,"E005"),t.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",t.location,"E005"),t.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",t.location,"E005");break;case"functionCall":for(let n of t.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(t.left),this.validateAvailableExpr(t.right);break;case"unary":this.validateAvailableExpr(t.operand);break;case"ternary":this.validateAvailableExpr(t.condition),this.validateAvailableExpr(t.consequent),this.validateAvailableExpr(t.alternate);break;case"propertyAccess":this.validateAvailableExpr(t.object);break;case"indexAccess":this.validateAvailableExpr(t.object),this.validateAvailableExpr(t.index);break;case"objectLiteral":for(let n of t.properties)this.validateAvailableExpr(n.kind==="objectProperty"?n.value:n.expr);break;case"arrayLiteral":for(let n of t.elements)this.validateAvailableExpr(n);break}}validateDispatchableExpr(t){switch(t.kind){case"systemIdent":t.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",t.location,"E047"),t.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",t.location,"E047"),t.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",t.location,"E047");break;case"functionCall":for(let n of t.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(t.left),this.validateDispatchableExpr(t.right);break;case"unary":this.validateDispatchableExpr(t.operand);break;case"ternary":this.validateDispatchableExpr(t.condition),this.validateDispatchableExpr(t.consequent),this.validateDispatchableExpr(t.alternate);break;case"propertyAccess":this.validateDispatchableExpr(t.object);break;case"indexAccess":this.validateDispatchableExpr(t.object),this.validateDispatchableExpr(t.index);break;case"objectLiteral":for(let n of t.properties)this.validateDispatchableExpr(n.kind==="objectProperty"?n.value:n.expr);break;case"arrayLiteral":for(let n of t.elements)this.validateDispatchableExpr(n);break}}validateGuardedStmt(t){switch(t.kind){case"when":this.validateWhen(t);break;case"once":this.validateOnce(t);break;case"onceIntent":this.validateOnceIntent(t);break;case"patch":this.validatePatch(t);break;case"effect":this.validateEffect(t);break;case"include":break;case"fail":this.validateFail(t);break;case"stop":this.validateStop(t);break}}validateWhen(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(t.condition,"when");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,t.condition&&this.validateCondition(t.condition,"once");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(t){this.ctx.inGuard=!0,this.ctx.guardDepth++,t.condition&&this.validateCondition(t.condition,"onceIntent");for(let n of t.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(t){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",t.location,"E_UNGUARDED_PATCH"),t.value){let n=this.ctx.diagnostics.length,r=this.validateExpr(t.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let o=gi(t.path,this.symbols);if(!o||!r)return;(t.op==="merge"?Xt(r,o,this.symbols):ee(r,o,this.symbols))===!1&&this.error(`Patch value for '${Ei(t.path)}' must be assignable to ${I(o,this.symbols)}, got ${I(r,this.symbols)}`,t.value.location,"E_TYPE_MISMATCH")}}validateEffect(t){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",t.location,"E_UNGUARDED_EFFECT");for(let n of t.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(t){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",t.location,"E006"),t.message&&this.validateExpr(t.message,"action")}validateStop(t){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",t.location,"E007"),hi.test(t.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",t.location,"E008")}validateCondition(t,n){let r=this.ctx.diagnostics.length,o=this.validateExpr(t,"action");r===this.ctx.diagnostics.length&&this.requireAssignable(o,b("boolean",t.location),t.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(t,n,r=this.ctx.currentActionParamTypes){switch(t.kind){case"functionCall":return this.validateFunctionCall(t,n,r),this.inferType(t,r);case"binary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.left,n,r),a=this.validateExpr(t.right,n,r);if(!(o!==this.ctx.diagnostics.length))switch(t.operator){case"==":case"!=":this.validatePrimitiveEquality(t.left,t.right,i,a,t.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,b("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,b("number",t.right.location),t.right.location,`Operator '${t.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,b("boolean",t.left.location),t.left.location,`Operator '${t.operator}' requires a boolean left operand`),this.requireAssignable(a,b("boolean",t.right.location),t.right.location,`Operator '${t.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,b("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,b("number",t.right.location),t.right.location,`Operator '${t.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],t.location);break}return this.inferType(t,r)}case"unary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.operand,n,r);return o===this.ctx.diagnostics.length&&this.requireAssignable(i,b(t.operator==="!"?"boolean":"number",t.operand.location),t.operand.location,t.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(t,r)}case"ternary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(t.condition,n,r);return this.validateExpr(t.consequent,n,r),this.validateExpr(t.alternate,n,r),o===this.ctx.diagnostics.length&&this.requireAssignable(i,b("boolean",t.condition.location),t.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(t,r)}case"propertyAccess":return this.validateExpr(t.object,n,r),this.inferType(t,r);case"indexAccess":return this.validateExpr(t.object,n,r),this.validateExpr(t.index,n,r),this.inferType(t,r);case"objectLiteral":for(let o of t.properties){if(o.kind==="objectProperty"){this.validateExpr(o.value,n,r);continue}let i=this.validateExpr(o.expr,n,r);this.symbols&&this.requireSpreadOperand(i,o.location,o.expr,r)}return this.inferType(t,r);case"arrayLiteral":for(let o of t.elements)this.validateExpr(o,n,r);return this.inferType(t,r);case"systemIdent":return this.inferType(t,r);case"literal":case"identifier":case"iterationVar":return this.inferType(t,r)}}validateFunctionCall(t,n,r){let{name:o,args:i,location:a}=t;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=X(c,this.symbols);d&&(l=yi(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],b("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],b("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],b("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],b("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],b("boolean",l.location),l.location,`Function '${o}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],b("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],b("number",i[0].location),i[0].location,`Function '${o}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],b("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],b("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],b("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=lt(i[1]),l=lt(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],b("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],b("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],b("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],b("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],b("string",i[1].location),i[1].location,`Function '${o}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],b("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],b("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],b("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],b("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],b("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],b("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],b("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"merge":for(let[c,l]of i.entries())this.requireSpreadOperand(s[c],l.location,l,r);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],b("boolean",i[0].location),i[0].location,`Function '${o}' expects a boolean condition`);break}}validatePrimitiveEquality(t,n,r,o,i){if(!this.symbols)return;if(t.kind==="objectLiteral"||t.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}fr(r,o,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${I(r,this.symbols)} and ${I(o,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(t,n){return this.symbols?T(t,n,this.symbols):null}requireAssignable(t,n,r,o){if(!this.symbols||!t)return;ee(t,n,this.symbols)===!1&&this.error(`${o}, got ${I(t,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(t,n,r){if(!this.symbols||!t)return;hr(t,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${I(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(t,n){if(!this.symbols||!t)return;yr(t,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${I(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireSpreadOperand(t,n,r,o=new Map){if(!this.symbols)return;let i=t===null?"unknown":st(t,this.symbols);(Y(r,{env:o,symbols:this.symbols,inferExprType:T,resolveType:S})?"invalid":i)==="invalid"&&this.error(`Object spread operands must be object-shaped or T | null where T is object-shaped, got ${I(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(t,n){if(!this.symbols)return;let r=t.map(o=>mr(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(Qt(r[o],r[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${I(r[o],this.symbols)} and ${I(r[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(t,n,r,o){if(!this.symbols||t.length<3)return;let i=n[0],a=Yt(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${I(i,this.symbols)}`,t[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<t.length-1;l+=1){let d=t[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[u,f]=d.elements,g=ur(u);if(g==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",u.location,"E050");else{let z=`${typeof g}:${String(g)}`;s.has(z)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(g)}`,u.location,"E051"):s.add(z)}let A=this.inferType(u,o),O=Yt(A,this.symbols);(O==="invalid"||a!==null&&O!==null&&a!==O)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${I(i,this.symbols)} and ${I(A,this.symbols)}`,u.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(Qt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${I(c[l],this.symbols)} and ${I(c[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(t,n,r,o){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=ur(i);a!=="first"&&a!=="last"&&this.error(`Function '${t}' 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 '${t}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[u,f,g]=d.elements,A=this.inferType(u,o),O=Yt(A,this.symbols);O==="invalid"?this.error(`Function '${t}' requires labels with exactly one primitive scalar type, got ${I(A,this.symbols)}`,u.location,"E_TYPE_MISMATCH"):c===null?c=O:O!==null&&O!==c&&this.error(`Function '${t}' candidate labels must share one primitive scalar type, got ${c} and ${O}`,u.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(f,o),b("boolean",f.location),f.location,`Function '${t}' expects a boolean eligible value`),this.requireAssignable(this.inferType(g,o),b("number",g.location),g.location,`Function '${t}' 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(Qt(s[l],s[d],this.symbols)===!1){this.error(`Function '${t}' candidate labels must have compatible scalar types, got ${I(s[l],this.symbols)} and ${I(s[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}error(t,n,r){this.ctx.diagnostics.push({severity:"error",code:r,message:t,location:n})}warn(t,n,r){this.ctx.diagnostics.push({severity:"warning",code:r,message:t,location:n})}};function gr(e){let n=new Zt().validate(e),r=cr(e),o=[...n.diagnostics,...r];return{valid:!o.some(i=>i.severity==="error"),diagnostics:o}}var en={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},tn={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},nn={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},rn={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Ti={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var W=class extends Error{code;path;details;constructor(t,n,r){super(n),this.name="LoweringError",this.code=t,this.path=r?.path,this.details=r?.details}};function dt(e,t,n){return new W("INVALID_KIND_FOR_CONTEXT",`Node kind '${e}' is not allowed in ${t} context`,{path:n,details:{kind:e,context:t}})}function N(e,t){return new W("UNKNOWN_CALL_FN",`Unknown function '${e}' in call expression`,{path:t,details:{fn:e}})}function pt(e,t){return new W("INVALID_SYS_PATH",`System path '${e.join(".")}' is not allowed in Translator path`,{path:t,details:{sysPath:e}})}function on(e,t){return new W("UNSUPPORTED_BASE",`Unsupported base expression kind '${e}'. Only var(item) is supported.`,{path:t,details:{baseKind:e}})}function ki(e,t){return new W("INVALID_SHAPE",`Invalid node shape: ${e}`,{path:t,details:{description:e}})}function an(e,t){return new W("UNKNOWN_NODE_KIND",`Unknown expression node kind '${e}'`,{path:t,details:{kind:e}})}function ye(e,t){let n=Array.from(e),r=Array.from(t),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 Er(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{let r=ye(t.item.key,n.item.key);return r!==0?r:t.index-n.index}).map(({item:t})=>t)}function h(e,t){switch(e.kind){case"lit":return Ni(e);case"var":return bi(e,t);case"sys":return Si(e,t);case"get":return Ai(e,t);case"field":return Tr(e,t);case"call":return vi(e,t);case"obj":return xi(e,t);case"arr":return Oi(e,t);default:throw an(e.kind)}}function Ni(e){return{kind:"lit",value:e.value}}function bi(e,t){if(!t.allowItem)throw dt("var",t.mode);return{kind:"get",path:"$item"}}function Si(e,t){if(e.path.length===0)throw pt(e.path);let n=e.path[0];if(!(t.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw pt(e.path);return{kind:"get",path:e.path.join(".")}}function Ai(e,t){let n=e.path.map(r=>r.name).join(".");if(e.base===void 0)return{kind:"get",path:n};if(e.base.kind==="var"&&e.base.name==="item"){if(!t.allowItem)throw dt("var",t.mode);return{kind:"get",path:`$item.${n}`}}throw on(e.base.kind)}function Tr(e,t){if(e.object.kind==="get"&&e.object.base===void 0){let n=e.object.path.map(r=>r.name).join(".");return{kind:"get",path:n?`${n}.${e.property}`:e.property}}return{kind:"field",object:h(e.object,t),property:e.property}}function vi(e,t){let{fn:n,args:r}=e;if(n==="absDiff"){if(r.length!==2)throw N(n);return{kind:"abs",arg:{kind:"sub",left:h(r[0],t),right:h(r[1],t)}}}if(n==="clamp"){if(r.length!==3)throw N(n);return{kind:"min",args:[{kind:"max",args:[h(r[0],t),h(r[1],t)]},h(r[2],t)]}}if(n==="idiv"){if(r.length!==2)throw N(n);return{kind:"floor",arg:{kind:"div",left:h(r[0],t),right:h(r[1],t)}}}if(n==="streak"){if(r.length!==2)throw N(n);return{kind:"if",cond:h(r[1],t),then:{kind:"add",left:h(r[0],t),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return wi(r,t);if(n==="argmax"||n==="argmin")return Ci(n,r,t);if(Ri(n)){if(r.length!==2)throw N(n);let[o,i]=r;return{kind:n,left:h(o,t),right:h(i,t)}}if(n==="isNotNull"){if(r.length!==1)throw N(n);return{kind:"not",arg:{kind:"isNull",arg:h(r[0],t)}}}if(kr(n)){if(r.length!==1)throw N(n);return{kind:Li(n),arg:h(r[0],t)}}if(n==="trim"){if(r.length!==1)throw N(n);return{kind:"trim",str:h(r[0],t)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw N(n);return{kind:"toLowerCase",str:h(r[0],t)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw N(n);return{kind:"toUpperCase",str:h(r[0],t)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw N(n);return{kind:"strLen",str:h(r[0],t)}}if(_i(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:h(r[0],t)}:{kind:n,args:r.map(o=>h(o,t))};if(n==="sum"){if(r.length!==1)throw N(n);return{kind:"sumArray",array:h(r[0],t)}}if(n==="pow"){if(r.length!==2)throw N(n);return{kind:"pow",base:h(r[0],t),exponent:h(r[1],t)}}if(Fi(n))return{kind:n,args:r.map(o=>h(o,t))};if(n==="if"||n==="cond"){if(r.length!==3)throw N(n);return{kind:"if",cond:h(r[0],t),then:h(r[1],t),else:h(r[2],t)}}if(n==="field"){if(r.length!==2)throw N(n);let o=h(r[0],t),i=r[1];if(i.kind!=="lit"||typeof i.value!="string")throw N(n);return Tr({kind:"field",object:r[0],property:i.value},t)}if(ji(n)){if(r.length!==1)throw N(n);return{kind:n,array:h(r[0],t)}}if($i(n)){if(r.length!==1)throw N(n);return{kind:n,obj:h(r[0],t)}}if(n==="at"){if(r.length!==2)throw N(n);return{kind:"at",array:h(r[0],t),index:h(r[1],t)}}if(n==="includes"){if(r.length!==2)throw N(n);return{kind:"includes",array:h(r[0],t),item:h(r[1],t)}}if(Gi(n)){if(r.length!==2)throw N(n);let o={...t,allowItem:!0};return n==="map"?{kind:"map",array:h(r[0],t),mapper:h(r[1],o)}:{kind:n,array:h(r[0],t),predicate:h(r[1],o)}}if(n==="slice"){if(r.length<2||r.length>3)throw N(n);let o={kind:"slice",array:h(r[0],t),start:h(r[1],t)};return r.length===3&&(o.end=h(r[2],t)),o}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw N(n);let o={kind:"substring",str:h(r[0],t),start:h(r[1],t)};return r.length===3&&(o.end=h(r[2],t)),o}if(n==="append"){if(r.length<1)throw N(n);return{kind:"append",array:h(r[0],t),items:r.slice(1).map(o=>h(o,t))}}if(n==="merge")return{kind:"merge",objects:r.map(o=>h(o,t))};throw N(n)}function xi(e,t){let n={};for(let r of Er(e.fields))n[r.key]=h(r.value,t);return{kind:"object",fields:n}}function Oi(e,t){if(e.elements.every(o=>o.kind==="lit"))return{kind:"lit",value:e.elements.map(i=>i.value)};let r=e.elements.map(o=>h(o,t));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function wi(e,t){if(e.length<3)throw N("match");let n=h(e[0],t),r=h(e[e.length-1],t);for(let o=e.length-2;o>=1;o-=1){let i=e[o];if(i.kind!=="arr"||i.elements.length!==2)throw N("match");r={kind:"if",cond:{kind:"eq",left:n,right:h(i.elements[0],t)},then:h(i.elements[1],t),else:r}}return r}function Ci(e,t,n){if(t.length<2)throw N(e);let r=t[t.length-1];if(r.kind!=="lit"||r.value!=="first"&&r.value!=="last")throw N(e);let o=t.slice(0,-1).map(i=>Ii(i,n,e));if(o.length===0)throw N(e);return Pi(e,o,r.value)}function Ii(e,t,n){if(e.kind!=="arr"||e.elements.length!==3)throw N(n);return{label:h(e.elements[0],t),eligible:h(e.elements[1],t),score:h(e.elements[2],t)}}function Pi(e,t,n){let r={kind:"lit",value:null};for(let o=t.length-1;o>=0;o-=1)r={kind:"if",cond:Mi(e,t,n,o),then:t[o].label,else:r};return r}function Mi(e,t,n,r){let o=t[r],i=[];for(let a=0;a<t.length;a+=1){if(a===r)continue;let s=t[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:Di(e,n,r,a),left:o.score,right:s.score}]})}return i.length===0?o.eligible:{kind:"and",args:[o.eligible,...i]}}function Di(e,t,n,r){let o=t==="first"?n<r:n>r;return e==="argmax"?o?"gte":"gt":o?"lte":"lt"}function Ri(e){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(e)}function kr(e){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(e)}function Li(e){if(e==="isNotNull")throw N(e);if(!kr(e))throw N(e);return e}function _i(e){return e==="min"||e==="max"}function Fi(e){return["and","or","concat","coalesce"].includes(e)}function ji(e){return["first","last"].includes(e)}function $i(e){return["keys","values","entries"].includes(e)}function Gi(e){return["filter","find","every","some","map"].includes(e)}function Bi(e,t){return e.map(n=>Vi(n,t))}function Vi(e,t){let n=e.condition?h(e.condition,ut(t,"action")):void 0,r=Ui(e.op,t);return{fragmentId:e.fragmentId,condition:n,op:r,confidence:e.confidence}}function Ui(e,t){switch(e.kind){case"addType":return{kind:"addType",typeName:e.typeName,typeExpr:xe(e.typeExpr)};case"addField":return{kind:"addField",typeName:e.typeName,field:{name:e.field.name,type:xe(e.field.type),optional:e.field.optional,defaultValue:e.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:e.path,typeExpr:xe(e.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:e.path,value:e.value};case"addConstraint":return{kind:"addConstraint",targetPath:e.targetPath,rule:h(e.rule,ut(t,"schema")),message:e.message};case"addComputed":return{kind:"addComputed",name:e.name,expr:h(e.expr,ut(t,"schema")),deps:e.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:e.actionName,expr:h(e.expr,ut(t,"schema"))}}}function xe(e){switch(e.kind){case"primitive":return{kind:"primitive",name:e.name};case"array":return{kind:"array",element:xe(e.element)};case"object":return{kind:"object",fields:e.fields.map(t=>({name:t.name,type:xe(t.type),optional:t.optional}))};case"union":return{kind:"union",members:e.members.map(xe)};case"literal":return{kind:"literal",value:e.value};case"ref":return{kind:"ref",name:e.name}}}function ut(e,t){return{mode:t,allowSysPaths:e.allowSysPaths,fnTableVersion:e.fnTableVersion,actionName:e.actionName,allowItem:!1}}function zi(e,t){return e.map(n=>ft(n,t))}function ft(e,t){let n=e.condition?h(e.condition,t):void 0,r=e.value?h(e.value,t):void 0;return{condition:n,op:e.op,path:qi(e.path,t),value:r}}function qi(e,t){return e.map(n=>n.kind==="prop"?n:{kind:"expr",expr:h(n.expr,t)})}function R(e,t={}){switch(e.kind){case"literal":return{kind:"lit",value:Wi(e.value,e.literalType)};case"identifier":return t.resolveIdentifier?.(e.name)??te(e.name);case"systemIdent":return Hi(e,t);case"iterationVar":return{kind:"var",name:e.name};case"propertyAccess":return Ji(e.object,e.property,t);case"indexAccess":return{kind:"call",fn:"at",args:[R(e.object,t),R(e.index,t)]};case"functionCall":return{kind:"call",fn:e.name,args:e.args.map(n=>R(n,t))};case"unary":return{kind:"call",fn:e.operator==="!"?"not":"neg",args:[R(e.operand,t)]};case"binary":return{kind:"call",fn:Yi(e.operator),args:[R(e.left,t),R(e.right,t)]};case"ternary":return{kind:"call",fn:"cond",args:[R(e.condition,t),R(e.consequent,t),R(e.alternate,t)]};case"objectLiteral":return Ki(e,t);case"arrayLiteral":return{kind:"arr",elements:e.elements.map(n=>R(n,t))}}}function Ki(e,t){if(!e.properties.some(a=>a.kind==="objectSpread"))return{kind:"obj",fields:e.properties.map(a=>{if(a.kind!=="objectProperty")throw new Error("Unexpected non-property in non-spread object literal");return{key:a.key,value:R(a.value,t)}})};let r=[],o=[],i=()=>{o.length!==0&&(r.push({kind:"obj",fields:o}),o=[])};for(let a of e.properties){if(a.kind==="objectProperty"){o.push({key:a.key,value:R(a.value,t)});continue}i(),r.push(R(a.expr,t))}return i(),{kind:"call",fn:"merge",args:r}}function te(...e){return{kind:"get",path:Nr(...e)}}function sn(e,...t){return{kind:"get",base:e,path:Nr(...t)}}function qe(...e){return{kind:"sys",path:e}}function mt(e){return{kind:"obj",fields:Object.entries(e).map(([t,n])=>({key:t,value:n}))}}function Nr(...e){return e.map(t=>({kind:"prop",name:t}))}function Hi(e,t){return t.resolveSystemIdent?.(e.path)??qe(...e.path)}function Ji(e,t,n){let r=R(e,n);return r.kind==="get"?{kind:"get",...r.base?{base:r.base}:void 0,path:[...r.path,{kind:"prop",name:t}]}:r.kind==="var"&&r.name==="item"?sn(r,t):{kind:"field",object:r,property:t}}function Wi(e,t){if(t==="null")return null;if(t==="number"){if(typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(typeof e=="string"&&e.length>0){let n=Number(e);if(!Number.isNaN(n))return n}throw new Error("Invalid number literal")}if(t==="string"){if(typeof e=="string")return e;throw new Error("Invalid string literal")}if(t==="boolean"){if(typeof e=="boolean")return e;throw new Error("Invalid boolean literal")}throw new Error("Unsupported literal type")}function Yi(e){switch(e){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 na,semanticPathToPatchPath as ra,sha256Sync as oa}from"@manifesto-ai/core";var Qi=new Set(["findById","existsById","updateById","removeById"]);function br(e){return{...e,computed:{fields:Object.fromEntries(Object.entries(e.computed.fields).map(([t,n])=>[t,Xi(n)]))},actions:Object.fromEntries(Object.entries(e.actions).map(([t,n])=>[t,Zi(n)]))}}function Xi(e){return{...e,expr:Sr(e.expr)}}function Zi(e){return{...e,flow:ht(e.flow),available:e.available?Sr(e.available):void 0,dispatchable:e.dispatchable?ea(e.dispatchable):void 0}}function ht(e){switch(e.kind){case"seq":return{kind:"seq",steps:e.steps.map(t=>ht(t))};case"if":return{kind:"if",cond:cn(e.cond),then:ht(e.then),else:e.else?ht(e.else):void 0};case"patch":return{kind:"patch",op:e.op,path:e.path,value:e.value?cn(e.value):void 0};case"effect":return{kind:"effect",type:e.type,params:Object.fromEntries(Object.entries(e.params).map(([t,n])=>[t,ta(n)]))};case"fail":return{kind:"fail",code:e.code,message:e.message?cn(e.message):void 0};case"call":case"halt":return e}}function Sr(e){return h(B(e),en)}function cn(e){return h(B(e),tn)}function ea(e){return h(B(e),nn)}function ta(e){return h(B(e),rn)}function B(e){switch(e.kind){case"lit":case"var":return e;case"sys":return e.path[0]==="system"?te("$system",...e.path.slice(1)):e;case"get":return{kind:"get",...e.base?{base:B(e.base)}:void 0,path:e.path};case"field":return{kind:"field",object:B(e.object),property:e.property};case"obj":return{kind:"obj",fields:e.fields.map(t=>({key:t.key,value:B(t.value)}))};case"arr":return{kind:"arr",elements:e.elements.map(t=>B(t))};case"call":return Qi.has(e.fn)?B(Ar(e.fn,e.args)):{kind:"call",fn:e.fn,args:e.args.map(t=>B(t))}}}function Ar(e,t){let[n,r,o]=t,i=B(n),a=r?B(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=sn(s,"id");switch(e){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:[Ar("findById",t)]}]};case"updateById":{let l=o?B(o):mt({});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:e,args:t.map(l=>B(l))}}}function ia(e){return{domainName:e,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 aa(e){let t=ia(e.domain.name);sa(e.domain,t);let n=ca(e.domain,t),r=la(e.domain,t),o=ma(e.domain,t),i=Ta(e.domain,t);if(t.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:t.diagnostics};let a={id:`mel:${e.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:r,computed:o,actions:i,meta:{name:e.domain.name}},s=Pa(a);return{schema:{...a,hash:s},diagnostics:t.diagnostics}}function vr(e){let t=aa(e);return t.schema?{schema:br(t.schema),diagnostics:t.diagnostics}:{schema:null,diagnostics:t.diagnostics}}function sa(e,t){for(let n of e.types)t.typeDefs.set(n.name,n);for(let n of e.members)if(n.kind==="state")for(let r of n.fields)t.stateFields.add(r.name);else n.kind==="computed"?t.computedFields.add(n.name):n.kind}function ca(e,t){let n={};for(let r of e.types){let o=ie(r.typeExpr);t.typeDefinitions.set(r.name,o),n[r.name]={name:r.name,definition:o}}return n}function ie(e){switch(e.kind){case"simpleType":return["string","number","boolean","null","object","array"].includes(e.name)?{kind:"primitive",type:e.name}:{kind:"ref",name:e.name};case"arrayType":return{kind:"array",element:ie(e.elementType)};case"recordType":return{kind:"record",key:ie(e.keyType),value:ie(e.valueType)};case"objectType":let t={};for(let r of e.fields)t[r.name]={type:ie(r.typeExpr),optional:r.optional};return{kind:"object",fields:t};case"unionType":return{kind:"union",types:e.types.map(ie)};case"literalType":return{kind:"literal",value:e.value};default:let n=e;throw new Error(`Unknown type expression kind: ${e.kind}`)}}function la(e,t){let n={},r={};for(let o of e.members)if(o.kind==="state")for(let i of o.fields){let a=ie(i.typeExpr);r[i.name]=a,t.stateFieldTypes.set(i.name,a);let s=Ee(i.typeExpr,t);s&&t.stateFieldSpecs.set(i.name,s);let c=da(i,t);c&&(n[i.name]=c)}return{fields:n,fieldTypes:r}}function da(e,t){let n=Ee(e.typeExpr,t);if(!n)return null;let r=e.initializer?Je(e.initializer,t):void 0;return r!==void 0&&He(r,ie(e.typeExpr),e.name,e.location,t),{...n,required:!0,default:r}}function Ee(e,t,n=[]){switch(e.kind){case"simpleType":switch(e.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=t.typeDefs.get(e.name);return r?n.includes(e.name)?(ln(t,"E044",`Recursive type '${e.name}' cannot be lowered to FieldSpec in a schema position`,e.location),null):Ee(r.typeExpr,t,[...n,e.name]):{type:"object",required:!0}}}case"unionType":{let r=e.types.filter(s=>!pa(s,t,n)),o=r.length!==e.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?Ee(r[0],t,n):(ln(t,"E043",`Union type '${Oe(e)}' cannot be soundly lowered to FieldSpec`,e.location),null)}case"arrayType":{let r=Ee(e.elementType,t,n);return r?{type:"array",required:!0,items:r}:null}case"recordType":return{type:"object",required:!0};case"literalType":return typeof e.value=="string"?{type:"string",required:!0}:typeof e.value=="number"?{type:"number",required:!0}:typeof e.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let r={};for(let o of e.fields){let i=Ee(o.typeExpr,t,n);if(!i)return null;r[o.name]={...i,required:!o.optional}}return{type:"object",required:!0,fields:r}}}}function xr(e,t,n=[]){if(e.kind!=="simpleType")return e;let r=t.typeDefs.get(e.name);return r?n.includes(e.name)?null:xr(r.typeExpr,t,[...n,e.name]):e}function pa(e,t,n=[]){let r=xr(e,t,n);return r?.kind==="simpleType"&&r.name==="null"||r?.kind==="literalType"&&r.value===null}function ln(e,t,n,r){e.diagnostics.push({severity:"error",code:t,message:n,location:r})}function Oe(e){switch(e.kind){case"simpleType":return e.name;case"unionType":return e.types.map(t=>Oe(t)).join(" | ");case"arrayType":return`Array<${Oe(e.elementType)}>`;case"recordType":return`Record<${Oe(e.keyType)}, ${Oe(e.valueType)}>`;case"literalType":return JSON.stringify(e.value);case"objectType":return`{ ${e.fields.map(t=>`${t.name}${t.optional?"?":""}: ${Oe(t.typeExpr)}`).join("; ")} }`}}function Te(e,t,n=[]){if(e.kind!=="ref")return e;if(n.includes(e.name))return null;let r=t.typeDefinitions.get(e.name);return r?Te(r,t,[...n,e.name]):null}function ua(e){return e?.kind==="primitive"&&e.type==="null"||e?.kind==="literal"&&e.value===null}function Or(e,t){let n=Te(e,t);if(!n||n.kind!=="union")return null;let r=n.types.filter(o=>{let i=Te(o,t);return!ua(i)});return r.length===1?r[0]:null}function fa(e,t,n){if(t===null||Array.isArray(t)||typeof t!="object")return e;let r=Or(e,n);return r&&Te(r,n)?.kind==="object"?r:e}function ae(e){switch(e.kind){case"primitive":return e.type;case"array":return`Array<${ae(e.element)}>`;case"record":return`Record<${ae(e.key)}, ${ae(e.value)}>`;case"object":return`{ ${Object.entries(e.fields).map(([t,n])=>`${t}${n.optional?"?":""}: ${ae(n.type)}`).join("; ")} }`;case"union":return e.types.map(t=>ae(t)).join(" | ");case"literal":return JSON.stringify(e.value);case"ref":return e.name}}function Ke(e,t,n){let r=Te(t,n);if(!r)return!1;switch(r.kind){case"primitive":switch(r.type){case"null":return e===null;case"string":return typeof e=="string";case"number":return typeof e=="number";case"boolean":return typeof e=="boolean";case"object":return e!==null&&!Array.isArray(e)&&typeof e=="object";case"array":return Array.isArray(e);default:return!1}case"literal":return Object.is(e,r.value);case"array":return Array.isArray(e)&&e.every(o=>Ke(o,r.element,n));case"record":return e!==null&&!Array.isArray(e)&&typeof e=="object"&&Object.values(e).every(o=>Ke(o,r.value,n));case"object":if(e===null||Array.isArray(e)||typeof e!="object")return!1;for(let o of Object.keys(e))if(!(o in r.fields))return!1;for(let[o,i]of Object.entries(r.fields)){if(!(o in e)){if(!i.optional)return!1;continue}if(!Ke(e[o],i.type,n))return!1}return!0;case"union":return r.types.some(o=>Ke(e,o,n));case"ref":return!1}}function He(e,t,n,r,o){if(e===void 0)return;let i=Te(t,o);if(!i){o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${ae(t)}, got ${JSON.stringify(e)}`,location:r});return}if(i.kind==="union"){if(Ke(e,i,o))return;o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${ae(i)}, got ${JSON.stringify(e)}`,location:r});return}switch(i.kind){case"primitive":{let a=Array.isArray(e)?"array":e===null?"null":typeof e;switch(i.type){case"null":e!==null&&ge(o,n,"null",a,r);return;case"string":case"number":case"boolean":typeof e!==i.type&&ge(o,n,i.type,a,r);return;case"object":(e===null||Array.isArray(e)||typeof e!="object")&&ge(o,n,"object",a,r);return;case"array":Array.isArray(e)||ge(o,n,"array",a,r);return}return}case"literal":Object.is(e,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(e)}`,location:r});return;case"array":if(!Array.isArray(e)){ge(o,n,"array",e===null?"null":typeof e=="object"?"object":typeof e,r);return}for(let a=0;a<e.length;a+=1)He(e[a],i.element,`${n}[${a}]`,r,o);return;case"record":if(e===null||Array.isArray(e)||typeof e!="object"){let a=Array.isArray(e)?"array":e===null?"null":typeof e;ge(o,n,"object",a,r);return}for(let[a,s]of Object.entries(e))He(s,i.value,`${n}.${a}`,r,o);return;case"object":if(e===null||Array.isArray(e)||typeof e!="object"){let a=Array.isArray(e)?"array":e===null?"null":typeof e;ge(o,n,"object",a,r);return}for(let a of Object.keys(e))a in i.fields||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${ae(i)}`,location:r});for(let[a,s]of Object.entries(i.fields)){if(!(a in e)){s.optional||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:r});continue}He(e[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 ${ae(t)}, got ${JSON.stringify(e)}`,location:r});return}}function ge(e,t,n,r,o){e.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${t}' expects ${n}, got ${r}`,location:o})}function Je(e,t){switch(e.kind){case"literal":return e.value;case"arrayLiteral":return e.elements.map(n=>Je(n,t));case"objectLiteral":{let n={};for(let r of e.properties){if(r.kind==="objectProperty"){n[r.key]=Je(r.value,t);continue}let o=Je(r.expr,t);o!==null&&!Array.isArray(o)&&typeof o=="object"&&Object.assign(n,o)}return n}default:return}}function ma(e,t){let n=[],r=0;for(let i of e.members)if(i.kind==="computed"){let a=ne(i.expression,t),s=Ea(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:r}),r+=1}let o={};for(let i of ha(n,t))o[i.name]={deps:i.deps,expr:i.expr};return{fields:o}}function ha(e,t){if(e.length<=1)return[...e];let n=new Map(e.map(c=>[c.name,c])),r=new Map,o=new Map,i=new Map;for(let c of e)o.set(c.name,[]),i.set(c.name,0);for(let c of e){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=e.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&&ya(a,l,n)}}if(s.length!==e.length){let c=new Set(s.map(f=>f.name)),l=e.filter(f=>!c.has(f.name)),d=ga(l[0].name,r),u=d?d.join(" -> "):l.map(f=>f.name).join(", ");return ln(t,"E040",`Circular computed dependency: ${u}`,(d?n.get(d[0]):l[0]).location),[...e]}return s}function ya(e,t,n){let r=n.get(t)?.order??Number.MAX_SAFE_INTEGER,o=e.length;for(let i=0;i<e.length;i+=1){let a=n.get(e[i])?.order??Number.MAX_SAFE_INTEGER;if(r<a){o=i;break}}e.splice(o,0,t)}function ga(e,t){let n=new Set,r=[],o=new Set;function i(a){n.add(a),r.push(a),o.add(a);for(let s of t.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(e)}function Ea(e){let t=new Set;function n(r){switch(r.kind){case"lit":case"sys":case"var":return;case"get":r.base===void 0?t.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(e),Array.from(t)}function Ta(e,t){let n={};for(let r of e.members)if(r.kind==="action"){t.currentAction=r.name,t.onceIntentCounters.set(r.name,0);let o=new Set;for(let u of r.params)o.add(u.name);t.actionParams.set(r.name,o);let i=r.params.map(u=>u.name),a=wr(r.body,t),s,c;if(r.params.length>0){let u={},f={};for(let g of r.params){let A=Ee(g.typeExpr,t);A&&(u[g.name]=structuredClone(A),f[g.name]={type:ie(g.typeExpr),optional:!1})}s={type:"object",required:!0,fields:u},c={kind:"object",fields:f}}let l;r.available&&(l=ne(r.available,t));let d;r.dispatchable&&(d=ne(r.dispatchable,t,{preferActionParams:!0})),n[r.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},t.currentAction=null}return n}function wr(e,t){return e.length===0?{kind:"seq",steps:[]}:e.length===1?gt(e[0],t):{kind:"seq",steps:e.map(n=>gt(n,t))}}function gt(e,t){switch(e.kind){case"when":return ka(e,t);case"once":return Na(e,t);case"onceIntent":return ba(e,t);case"patch":return Sa(e,t);case"effect":return Aa(e,t);case"fail":return xa(e,t);case"stop":return Oa(e,t);case"include":return{kind:"seq",steps:[]}}}function ka(e,t){let n=ne(e.condition,t),r=wr(e.body,t);return{kind:"if",cond:n,then:r}}function Na(e,t){let n=dn(e.marker,t),r=qe("meta","intentId"),o=Et("neq",[te(...Cr(n)),r]);if(e.condition){let s=ne(e.condition,t);o=Et("and",[o,s])}let i={kind:"patch",op:"set",path:pn(n),value:r},a=e.body.map(s=>gt(s,t));return{kind:"if",cond:o,then:{kind:"seq",steps:[i,...a]}}}function ba(e,t){let n=t.currentAction??"unknown",r=t.onceIntentCounters.get(n)??0;t.onceIntentCounters.set(n,r+1);let o=oa(`${n}:${r}:intent`),i=`$mel.guards.intent.${o}`,a=qe("meta","intentId"),s=Et("neq",[te(...Cr(i)),a]);if(e.condition){let d=ne(e.condition,t);s=Et("and",[s,d])}let c={kind:"patch",op:"merge",path:pn("$mel.guards.intent"),value:mt({[o]:a})},l=e.body.map(d=>gt(d,t));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function Sa(e,t){let n=dn(e.path,t),r={kind:"patch",op:e.op,path:pn(n)};if(e.value){let o=ne(e.value,t);if(r.value=o,e.op==="set"){let i=e.path.segments[0];if(i.kind==="propertySegment"){let a=t.stateFieldTypes.get(i.name);if(a){let s=a,c=e.path.segments;for(let l=1;l<c.length;l++){let d=c[l],u=s?Te(s,t):null;if(!u){s=null;break}if(u.kind==="union"){let f=Or(s,t);if(!f){s=null;break}s=f,l-=1;continue}if(d.kind==="propertySegment"&&u.kind==="object"&&u.fields[d.name])s=u.fields[d.name].type;else if(d.kind==="propertySegment"&&u.kind==="record")s=u.value;else if(d.kind==="indexSegment"&&u.kind==="array")s=u.element;else{s=null;break}}if(s){let l=va(e.value,t);if(l!==void 0){let d=e.path.segments.map(f=>f.kind==="propertySegment"?f.name:"[*]").join("."),u=fa(s,l,t);He(l,u,d,e.location,t)}}}}}}return r}function Aa(e,t){let n={};for(let r of e.args)r.isPath?n[r.name]={kind:"lit",value:dn(r.value,t)}:n[r.name]=ne(r.value,t);return{kind:"effect",type:e.effectType,params:n}}function va(e,t){return Je(e,t)}function xa(e,t){let n={kind:"fail",code:e.code};return e.message&&(n.message=ne(e.message,t)),n}function Oa(e,t){return{kind:"halt",reason:e.reason}}function wa(e){return e.replaceAll("\\","\\\\").replaceAll(".","\\.")}function yt(...e){return e.map(wa).join(".")}function dn(e,t){let n=[];for(let o of e.segments)if(o.kind==="propertySegment")n.push(o.name);else{let i=ne(o.index,t);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let r=n[0];return t.stateFields.has(r)?yt(...n):t.computedFields.has(r)?yt(...n):t.currentAction&&t.actionParams.get(t.currentAction)?.has(r)?`input.${yt(...n)}`:yt(...n)}function pn(e){return ra(e)}function Et(e,t){return{kind:"call",fn:e,args:t}}function Cr(e){return e.split(/(?<!\\)\./g).map(t=>t.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function ne(e,t,n={}){return R(e,{resolveIdentifier:r=>Ca(r,t,n),resolveSystemIdent:r=>Ia(r,t)})}function Ca(e,t,n={}){return n.preferActionParams&&t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?te("input",e):t.stateFields.has(e)||t.computedFields.has(e)?te(e):t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?te("input",e):(t.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${e}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),te(e))}function Ia(e,t){let[n,...r]=e;switch(n){case"system":case"meta":case"input":return qe(n,...r);default:return t.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 Pa(e){return na(e)}var Ma="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",Da="Action-parameter annotations are not part of the current MEL syntax.",un="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",Ir="Annotation payload nesting exceeds the current MEL limit of 2 levels.",Ra="Annotation target does not map to the emitted DomainSchema.",Pr=2;function Mr(e,t){let n=[],r=new Map,o=e.domain;we(o.annotations,`domain:${o.name}`,n,r);for(let a of o.types)we(a.annotations,`type:${a.name}`,n,r),Ce(a.typeExpr,a.name,0,n,r);for(let a of o.members)switch(a.kind){case"state":for(let s of a.fields)we(s.annotations,`state_field:${s.name}`,n,r),ke(s.typeExpr,n);break;case"computed":we(a.annotations,`computed:${a.name}`,n,r);break;case"action":we(a.annotations,`action:${a.name}`,n,r),La(a,n);for(let s of a.params)ke(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...r.keys()].sort()){if(!ja(t,a)){n.push(D("E057",Ra,$a(e,a)??o.location));continue}let s=r.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>Fa(c))))}return{annotations:Object.freeze({schemaHash:t.hash,entries:Object.freeze(i)}),diagnostics:n}}function we(e,t,n,r){if(!e||e.length===0)return;let o=[];for(let a of e){let s=a.payload===void 0?{ok:!0,value:void 0}:fn(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(t);if(i){i.push(...o);return}r.set(t,o)}function Ce(e,t,n,r,o){switch(e.kind){case"objectType":for(let i of e.fields)i.annotations?.length&&(n===0?we(i.annotations,`type_field:${t}.${i.name}`,r,o):Dr(i.annotations,r)),Ce(i.typeExpr,t,n+1,r,o);return;case"arrayType":Ce(e.elementType,t,n,r,o);return;case"recordType":Ce(e.keyType,t,n,r,o),Ce(e.valueType,t,n,r,o);return;case"unionType":for(let i of e.types)Ce(i,t,n,r,o);return;case"simpleType":case"literalType":return}}function ke(e,t){switch(e.kind){case"objectType":for(let n of e.fields)Dr(n.annotations,t),ke(n.typeExpr,t);return;case"arrayType":ke(e.elementType,t);return;case"recordType":ke(e.keyType,t),ke(e.valueType,t);return;case"unionType":for(let n of e.types)ke(n,t);return;case"simpleType":case"literalType":return}}function La(e,t){for(let n of e.params)_a(n,t)}function _a(e,t){if(e.annotations)for(let n of e.annotations)t.push(D("E054",Da,n.location))}function Dr(e,t){if(e)for(let n of e)t.push(D("E053",Ma,n.location))}function fn(e,t,n){switch(e.kind){case"literal":return e.literalType==="string"||e.literalType==="number"||e.literalType==="boolean"||e.literalType==="null"?{ok:!0,value:e.value}:(n.push(D("E055",un,e.location)),{ok:!1});case"arrayLiteral":{if(t+1>Pr)return n.push(D("E056",Ir,e.location)),{ok:!1};let r=[];for(let o of e.elements){let i=fn(o,t+1,n);if(!i.ok)return{ok:!1};r.push(i.value)}return{ok:!0,value:r}}case"objectLiteral":{if(t+1>Pr)return n.push(D("E056",Ir,e.location)),{ok:!1};let r={};for(let o of e.properties){if(o.kind!=="objectProperty")return n.push(D("E055",un,o.location)),{ok:!1};let i=fn(o.value,t+1,n);if(!i.ok)return{ok:!1};r[o.key]=i.value}return{ok:!0,value:r}}default:return n.push(D("E055",un,e.location)),{ok:!1}}}function Fa(e){return e.payload===void 0?Object.freeze({tag:e.tag}):Object.freeze({tag:e.tag,payload:mn(e.payload)})}function mn(e){if(Array.isArray(e))return Object.freeze(e.map(t=>mn(t)));if(e!==null&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=mn(r);return Object.freeze(t)}return e}function ja(e,t){let n=t.indexOf(":");if(n<0)return!1;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.meta?.name===o||e.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(e.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=e.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(e.state.fields,o);case"computed":return Object.hasOwn(e.computed.fields,o);case"action":return Object.hasOwn(e.actions,o);default:return!1}}function $a(e,t){let n=t.indexOf(":");if(n<0)return null;let r=t.slice(0,n),o=t.slice(n+1),i=e.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 hn=16;function v(e){return structuredClone(e)}function _(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(D(n,r,o)))}function Ga(e){let t=new Map,n=new Set,r=new Map,o=new Set,i=new Map;for(let a of e.types)r.set(a.name,a);for(let a of e.members)switch(a.kind){case"state":for(let s of a.fields)t.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:t,computedNames:n,typeDefs:r,actionNames:o,flows:i}}function Ba(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function Va(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function Ua(e,t,n,r){let o=new Map;for(let i of t.flows.values()){o.set(i.name,[]),t.actionNames.has(i.name)&&_(n,r,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(t.stateTypes.has(s.name)||t.computedNames.has(s.name)||t.typeDefs.has(s.name))&&_(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Ba(i);for(let s of i.body)qa(s,i.name,a,t,n,r,o.get(i.name))}for(let i of e.members)if(i.kind==="action"){let a=Va(i);for(let s of i.body)za(s,a,t,n,r)}return o}function za(e,t,n,r,o){switch(e.kind){case"include":kt(e,t,n,r,o);break;case"when":for(let i of e.body)Me(i,t,n,r,o);break;case"once":for(let i of e.body)Me(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Me(i,t,n,r,o);break;case"fail":case"stop":break}}function Me(e,t,n,r,o){switch(e.kind){case"include":_(r,o,"E016","include is only allowed at action or flow body top-level.",e.location),kt(e,t,n,r,o);break;case"when":for(let i of e.body)Me(i,t,n,r,o);break;case"once":for(let i of e.body)Me(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Me(i,t,n,r,o);break;case"patch":case"effect":case"fail":case"stop":break}}function qa(e,t,n,r,o,i,a){switch(e.kind){case"include":kt(e,n,r,o,i)&&a.push({target:e.flowName,location:e.location});break;case"when":for(let s of e.body)Tt(s,t,n,r,o,i);break;case"once":_(o,i,"E017","once() is not allowed in flow bodies.",e.location);break;case"onceIntent":_(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);break;case"patch":_(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":_(o,i,"E020","effect is not allowed in flow bodies.",e.location);break}}function Tt(e,t,n,r,o,i){switch(e.kind){case"include":_(o,i,"E016","include is only allowed at action or flow body top-level.",e.location),kt(e,n,r,o,i);break;case"when":for(let a of e.body)Tt(a,t,n,r,o,i);break;case"once":_(o,i,"E017","once() is not allowed in flow bodies.",e.location);for(let a of e.body)Tt(a,t,n,r,o,i);break;case"onceIntent":_(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);for(let a of e.body)Tt(a,t,n,r,o,i);break;case"patch":_(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":_(o,i,"E020","effect is not allowed in flow bodies.",e.location);break;case"fail":case"stop":break}}function kt(e,t,n,r,o){let i=n.flows.get(e.flowName);if(!i)return _(r,o,"E015",`'${e.flowName}' is not a declared flow.`,e.location),!1;if(e.args.length!==i.params.length)return _(r,o,"E023",`include '${e.flowName}' expected ${i.params.length} argument(s), got ${e.args.length}.`,e.location),!0;for(let a=0;a<e.args.length;a+=1){let s=e.args[a],c=i.params[a],l=Ie(s,t,n);if(!l)continue;Pe(l,c.typeExpr,n)===!1&&_(r,o,"E024",`include '${e.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function Ka(e,t,n,r){function o(i,a,s){s.add(i);for(let c of e.get(i)??[]){if(a+1>hn){_(n,r,"E014",`Include expansion depth exceeds limit (${hn}).`,c.location);continue}if(s.has(c.target)){_(n,r,"E013","Circular include detected.",c.location);continue}o(c.target,a+1,new Set(s))}}for(let i of t.flows.keys())o(i,1,new Set)}function $(e,t){switch(e.kind){case"identifier":return t.has(e.name)?v(t.get(e.name)):v(e);case"systemIdent":case"literal":case"iterationVar":return v(e);case"functionCall":return{...v(e),args:e.args.map(n=>$(n,t))};case"binary":return{...v(e),left:$(e.left,t),right:$(e.right,t)};case"unary":return{...v(e),operand:$(e.operand,t)};case"ternary":return{...v(e),condition:$(e.condition,t),consequent:$(e.consequent,t),alternate:$(e.alternate,t)};case"propertyAccess":return{...v(e),object:$(e.object,t)};case"indexAccess":return{...v(e),object:$(e.object,t),index:$(e.index,t)};case"objectLiteral":return{...v(e),properties:e.properties.map(n=>({...v(n),...n.kind==="objectProperty"?{value:$(n.value,t)}:{expr:$(n.expr,t)}}))};case"arrayLiteral":return{...v(e),elements:e.elements.map(n=>$(n,t))}}}function Ha(e,t){switch(e.kind){case"when":return[Rr(e,t)];case"fail":return[{...v(e),message:e.message?$(e.message,t):void 0}];case"stop":return[v(e)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function Rr(e,t){return{...v(e),condition:$(e.condition,t),body:e.body.flatMap(n=>Ha(n,t))}}function Ja(e,t,n){let r=new Map;for(let o=0;o<e.params.length;o+=1)r.set(e.params[o].name,$(t.args[o],n));return r}function Wa(e,t,n,r,o){switch(e.kind){case"when":return[Rr(e,n)];case"include":return Lr(e,t,n,r,o);case"once":case"onceIntent":case"patch":case"effect":return[]}}function Lr(e,t,n,r,o){let i=t.flows.get(e.flowName);if(!i||e.args.length!==i.params.length||r>hn||o.includes(e.flowName))return[];let a=Ja(i,e,n),s=[...o,e.flowName];return i.body.flatMap(c=>Wa(c,t,a,r+1,s))}function De(e){switch(e.kind){case"when":return[{...v(e),body:e.body.flatMap(t=>De(t))}];case"once":return[{...v(e),body:e.body.flatMap(t=>De(t))}];case"onceIntent":return[{...v(e),body:e.body.flatMap(t=>De(t))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[v(e)]}}function Ya(e,t,n){switch(e.kind){case"include":return Lr(e,t,new Map,n,[]);case"when":return[{...v(e),body:e.body.flatMap(r=>De(r))}];case"once":return[{...v(e),body:e.body.flatMap(r=>De(r))}];case"onceIntent":return[{...v(e),body:e.body.flatMap(r=>De(r))}];case"fail":case"stop":return[v(e)]}}function Qa(e,t){let n=[];for(let r of e.domain.members)switch(r.kind){case"state":case"computed":n.push(v(r));break;case"action":n.push({...v(r),body:r.body.flatMap(o=>Ya(o,t,1))});break;case"flow":break}return{...v(e),domain:{...v(e.domain),types:e.domain.types.map(r=>v(r)),members:n}}}function Ie(e,t,n){switch(e.kind){case"literal":return{kind:"literalType",value:e.value,location:e.location};case"identifier":return t.get(e.name)??n.stateTypes.get(e.name)??null;case"propertyAccess":{let r=Ie(e.object,t,n);return _r(r,e.property,n)}case"indexAccess":{let r=Ie(e.object,t,n);return Fr(r,n)}case"objectLiteral":return nt(e,t,n,Ie,Ne);case"arrayLiteral":{if(e.elements.length===0)return null;let r=Ie(e.elements[0],t,n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"functionCall":return e.name==="merge"?rt(e,t,n,Ie,Ne):null;case"systemIdent":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function Ne(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),Ne(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function _r(e,t,n){let r=Ne(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?yn([o.typeExpr,{kind:"simpleType",name:"null",location:o.location}],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!jr(i)).map(i=>_r(i,t,n)).filter(i=>i!==null);return yn(o,r.location)}return null}function Fr(e,t){let n=Ne(e,t);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=>!jr(o)).map(o=>Fr(o,t)).filter(o=>o!==null);return yn(r,n.location)}return null}function Pe(e,t,n){let r=Ne(e,n),o=Ne(t,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}if(a.optional&&!i.optional)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 jr(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function yn(e,t){let n=e.filter(i=>i!==null).flatMap(i=>i.kind==="unionType"?i.types:[i]);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:t}}function $r(e){let t=Ga(e.domain),n=[],r=new Set,o=Ua(e.domain,t,n,r);return Ka(o,t,n,r),{program:Qa(e,t),diagnostics:n}}var Xa=new Set(["$item","$index","$array"]);function Vr(e){let t=Object.keys(e.state.fields).filter(d=>!d.startsWith("$")),n=Za(e),r=new Set(n),o=new Set(t),i=Object.keys(e.actions),a=[...t.map(d=>({id:gn(d),kind:"state",name:d})),...n.map(d=>({id:En(d),kind:"computed",name:d})),...i.map(d=>({id:Br(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,u,f)=>{if(!d||!u)return;let g=`${d}|${f}|${u}`;s.has(g)||(s.add(g),c.push({from:d,to:u,relation:f}))};for(let d of n){let u=e.computed.fields[d];if(u)for(let f of u.deps)l(Gr(f,e,r,o),En(d),"feeds")}for(let d of i){let u=e.actions[d],f=Br(d);for(let g of es(u.flow,e))o.has(g)&&l(f,gn(g),"mutates");if(u.available)for(let g of Hr(u.available))l(Gr(g,e,r,o),f,"unlocks")}return rs({nodes:a,edges:c})}function Za(e){let t=e.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=t[o];if(!s)return i.delete(o),n.set(o,!0),!0;for(let c of Hr(s.expr)){if(Kr(c))return i.delete(o),n.set(o,!1),!1;let l=Ur(c,t);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(t).filter(o=>r(o,new Set))}function es(e,t){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=ts(o.path);a&&n.add(a);return}case"effect":{let a=ns(o.params.into);a&&n.add(a);return}case"call":{if(i.has(o.flow))return;let a=t.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(e,new Set),[...n]}function ts(e){let[t]=e;return!t||t.kind!=="prop"||t.name.startsWith("$")?null:t.name}function ns(e){return typeof e!="object"||e===null||e.kind!=="lit"||typeof e.value!="string"?null:zr(e.value)}function Gr(e,t,n,r){let o=Ur(e,t.computed.fields);if(o!==null&&n.has(o))return En(o);if(Kr(e))return null;let i=zr(e);return!i||!r.has(i)?null:gn(i)}function Ur(e,t){if(Object.prototype.hasOwnProperty.call(t,e))return e;if(!e.startsWith("computed."))return null;let n=e.slice(9);return Object.prototype.hasOwnProperty.call(t,n)?n:null}function zr(e){let t=qr(e),n=t.startsWith("data.")?t.slice(5):t,r=/^([^.[\]]+)/.exec(n);if(!r)return null;let[o]=r.slice(1);return!o||o.startsWith("$")?null:o}function qr(e){return e.startsWith("/")?e.slice(1).replace(/\//g,"."):e}function Kr(e){let t=qr(e),n=t.startsWith("data.")?t.slice(5):t,o=/^([^.[\]]+)/.exec(n)?.[1]??"";return o.startsWith("$")?!Xa.has(o):!1}function Hr(e){let t=[],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"){t.push(i.path);return}for(let a of Object.values(i))r(a)}};return r(e),t}function gn(e){return`state:${e}`}function En(e){return`computed:${e}`}function Br(e){return`action:${e}`}function rs(e){return Object.freeze({nodes:Object.freeze(e.nodes.map(t=>Object.freeze(t))),edges:Object.freeze([...e.edges].sort(os).map(t=>Object.freeze(t)))})}function os(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)||e.relation.localeCompare(t.relation)}var is="Source-map target does not map to the emitted DomainSchema.",as="Source-map entry missing for emitted DomainSchema target.",ss=new TextEncoder;function Qr(e){return Object.freeze({coordinateUnit:"utf16",compilerVersion:e,emissionOptionsFingerprint:"default"})}function Xr(e,t,n,r){let o=[],i=new Map,a=e.domain,s=ds(t,r.coordinateUnit);i.set(`domain:${a.name}`,_e({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,_e({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),Re(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}`,_e({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,_e({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,_e({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(!ls(n,l)){o.push(D("E058",is,Jr(e,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of cs(e,n))Object.hasOwn(c,l)||o.push(D("E058",as,Jr(e,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:Fe(t),format:"manifesto/source-map-v1",coordinateUnit:r.coordinateUnit,emissionFingerprint:Fe(`${r.coordinateUnit}\0${r.compilerVersion}\0${r.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:o}}function Re(e,t,n,r,o){switch(e.kind){case"objectType":for(let i of e.fields)n===0&&r.set(`type_field:${t}.${i.name}`,_e({target:{kind:"type_field",type:{name:t},field:{name:i.name}},span:o(i.location)})),Re(i.typeExpr,t,n+1,r,o);return;case"arrayType":Re(e.elementType,t,n+1,r,o);return;case"recordType":Re(e.keyType,t,n+1,r,o),Re(e.valueType,t,n+1,r,o);return;case"unionType":for(let i of e.types)Re(i,t,n+1,r,o);return;case"simpleType":case"literalType":return}}function cs(e,t){let n=new Set;n.add(`domain:${e.domain.name}`);for(let[r,o]of Object.entries(t.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(t.state.fields))n.add(`state_field:${r}`);for(let r of Object.keys(t.computed.fields))n.add(`computed:${r}`);for(let r of Object.keys(t.actions))n.add(`action:${r}`);return[...n].sort()}function ls(e,t){let n=t.indexOf(":");if(n<0)return!1;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.meta?.name===o||e.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(e.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=e.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(e.state.fields,o);case"computed":return Object.hasOwn(e.computed.fields,o);case"action":return Object.hasOwn(e.actions,o);default:return!1}}function Jr(e,t){let n=t.indexOf(":");if(n<0)return null;let r=t.slice(0,n),o=t.slice(n+1);switch(r){case"domain":return e.domain.name===o?e.domain.location:null;case"type":return e.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=e.domain.types.find(l=>l.name===a);return c?Le(c.typeExpr,s,0):null}case"state_field":for(let i of e.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 e.domain.members.find(i=>i.kind==="computed"&&i.name===o)?.location??null;case"action":return e.domain.members.find(i=>i.kind==="action"&&i.name===o)?.location??null;default:return null}}function Le(e,t,n){switch(e.kind){case"objectType":for(let r of e.fields){if(n===0&&r.name===t)return r.location;let o=Le(r.typeExpr,t,n+1);if(o)return o}return null;case"arrayType":return Le(e.elementType,t,n+1);case"recordType":return Le(e.keyType,t,n+1)??Le(e.valueType,t,n+1);case"unionType":for(let r of e.types){let o=Le(r,t,n+1);if(o)return o}return null;case"simpleType":case"literalType":return null}}function ds(e,t){return t==="utf16"?n=>ps(n):n=>us(n,e)}function ps(e){return Object.freeze({start:Object.freeze({line:e.start.line,column:e.start.column}),end:Object.freeze({line:e.end.line,column:e.end.column})})}function us(e,t){return Object.freeze({start:Wr(e.start,t),end:Wr(e.end,t)})}function Wr(e,t){let n=Yr(t.slice(0,e.offset)),r=e.offset-(e.column-1),o=Yr(t.slice(0,r));return Object.freeze({line:e.line,column:n-o+1})}function _e(e){return Object.freeze({target:fs(e.target),span:Object.freeze({start:Object.freeze({...e.span.start}),end:Object.freeze({...e.span.end})})})}function fs(e){switch(e.kind){case"domain":return Object.freeze({kind:e.kind,domain:Object.freeze({...e.domain})});case"type":return Object.freeze({kind:e.kind,type:Object.freeze({...e.type})});case"type_field":return Object.freeze({kind:e.kind,type:Object.freeze({...e.type}),field:Object.freeze({...e.field})});case"state_field":return Object.freeze({kind:e.kind,field:Object.freeze({...e.field})});case"computed":return Object.freeze({kind:e.kind,computed:Object.freeze({...e.computed})});case"action":return Object.freeze({kind:e.kind,action:Object.freeze({...e.action})})}}function Fe(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return`fnv1a32:${t.toString(16).padStart(8,"0")}`}function Yr(e){return ss.encode(e).length}import{sha256Sync as Nt}from"@manifesto-ai/core";function Zr(e){return e.kind==="literal"&&e.literalType==="boolean"&&e.value===!0}function je(e){return R(e)}var bt=class{constructor(t){this.deps=t;this.exprValidator=new kn(t.mapLocation)}conditionComposer=new Tn;exprValidator;collect(t,n,r,o){return this.collectPatchStatements(t,n,r,o)}collectPatchStatements(t,n,r,o){let i=[];for(let a of t){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=Nt(`${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),u=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},...u,{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,u={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{u=this.conditionComposer.and(u,this.deps.toMelExpr(a.condition))??u}catch(z){n.push({severity:"error",code:"E_LOWER",message:z.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(o,u);let f=Nt(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let g={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(g),O=this.collectPatchStatements(a.body,n,r,A);i.push({patch:{kind:"patch",op:"set",path:g,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},...O,{patch:{kind:"patch",op:"unset",path:g,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Nt(`${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=Nt(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let u=a.location,g={kind:"call",fn:"neq",args:[We({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:u},{kind:"propertySegment",name:"guards",location:u},{kind:"propertySegment",name:"intent",location:u},{kind:"propertySegment",name:d,location:u}],location:u}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{g=this.conditionComposer.and(g,this.deps.toMelExpr(a.condition))??g}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,g),O={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:u},{kind:"propertySegment",name:"guards",location:u},{kind:"propertySegment",name:"intent",location:u}],location:u},z=this.collectPatchStatements(a.body,n,r,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:u},location:u},condition:A},{patch:{kind:"patch",op:"merge",path:O,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:u},location:u}],location:u},location:u},condition:l},...z,{patch:{kind:"patch",op:"unset",path:c,location:u},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 eo(e){return{op:e.patch.op,path:ms(e.patch.path),...e.condition?{condition:e.condition}:void 0,...e.patch.value?{value:je(e.patch.value)}:void 0}}function We(e){let t=e.segments,n;for(let r of t){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,je(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function ms(e){return e.segments.map(t=>t.kind==="propertySegment"?{kind:"prop",name:t.name}:{kind:"expr",expr:je(t.index)})}var Tn=class{and(t,n){return t?n?{kind:"call",fn:"and",args:[t,n]}:t:n}},kn=class{constructor(t){this.mapLocation=t}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(t,n){for(let r of t.segments)r.kind==="indexSegment"&&this.validateExpr(r.index,n)}validateExpr(t,n){switch(t.kind){case"functionCall":(t.name==="eq"||t.name==="neq")&&t.args.length>=2&&this.validatePrimitiveEquality(t.args[0],t.args[1],t.location,n);for(let r of t.args)this.validateExpr(r,n);if(t.name==="merge")for(let r of t.args)this.validateSpreadOperand(r,r.location,n);return;case"binary":(t.operator==="=="||t.operator==="!=")&&this.validatePrimitiveEquality(t.left,t.right,t.location,n),this.validateExpr(t.left,n),this.validateExpr(t.right,n);return;case"unary":this.validateExpr(t.operand,n);return;case"ternary":this.validateExpr(t.condition,n),this.validateExpr(t.consequent,n),this.validateExpr(t.alternate,n);return;case"propertyAccess":this.validateExpr(t.object,n);return;case"indexAccess":this.validateExpr(t.object,n),this.validateExpr(t.index,n);return;case"objectLiteral":for(let r of t.properties){if(r.kind==="objectProperty"){this.validateExpr(r.value,n);continue}this.validateExpr(r.expr,n),this.validateSpreadOperand(r.expr,r.location,n)}return;case"arrayLiteral":for(let r of t.elements)this.validateExpr(r,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(t,n,r,o){let i=Q(t,new Map,this.symbols),a=Q(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)})}validateSpreadOperand(t,n,r){let o=T(t,new Map,this.symbols),i=Y(t,{env:new Map,symbols:this.symbols,inferExprType:T,resolveType:S});!o&&!i||(i?"invalid":o?st(o,this.symbols):"unknown")!=="invalid"||r.push({severity:"error",code:"E_TYPE_MISMATCH",message:"Object spread operands must be object-shaped or T | null where T is object-shaped",location:this.mapLocation(n)})}};function no(e){let t=[],n=0;for(let r of e)t.push(n),n+=r.length+1;return t}function ro(e,t){return n=>oo(n,e,t)}function Nn(e,t,n){return e.map(r=>hs(r,t,n))}function hs(e,t,n){return{...e,location:oo(e.location,t,n)}}function oo(e,t,n){return{...e,start:to(e.start,t,n),end:to(e.end,t,n)}}function to(e,t,n){let r=e.line-3,o=t.length,i=Math.min(Math.max(r,1),o),a=n[i-1]??0,s=t[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(e.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var Ye="__compileMelPatch",gs="__patchDomain",Es=" ";function io(e,t){let n=[],r=[],o=[],i=e.split(`
9
+ `),a=no(i),s=ro(i,a),c=Ts(e,Ye),l=performance.now(),d;try{let w=j(c);d=w.tokens;let P=Nn(w.diagnostics.filter(fe=>fe.severity==="error"),i,a);if(P.length>0)return o.push(...P),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:o}}catch(w){return o.push({severity:"error",code:"E_LEX",message:w.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 u=performance.now(),f;try{let w=me(d),P=Nn(w.diagnostics,i,a),fe=P.filter(_t=>_t.severity==="error"),J=P.filter(_t=>_t.severity!=="error");if(fe.length>0)return o.push(...fe),r.push(...J),n.push({phase:"parse",durationMs:performance.now()-u}),{ops:[],trace:n,warnings:r,errors:o};if(!w.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()-u}),{ops:[],trace:n,warnings:r,errors:o};f=w.program,r.push(...J)}catch(w){return o.push({severity:"error",code:"E_PARSE",message:w.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-u}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-u});let g=performance.now(),A={actionName:t.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},O=f.domain.members.find(w=>w.kind==="action"&&w.name===Ye);if(!O)return o.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${Ye}' 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()-g}),{ops:[],trace:n,warnings:r,errors:o};let z=i.length+3+2;if(O.location.end.line!==z)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ye}'.`,location:s(O.location)}),n.push({phase:"analyze",durationMs:performance.now()-g}),{ops:[],trace:n,warnings:r,errors:o};let[H]=O.body;if(!H||H.kind!=="when"||!Zr(H.condition)||O.body.length!==1)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ye}'.`,location:s(O.location)}),n.push({phase:"analyze",durationMs:performance.now()-g}),{ops:[],trace:n,warnings:r,errors:o};let p=new bt({mapLocation:s,toMelExpr:je}).collect(H.body,o,A,void 0);if(o.length===0&&e.trim()!==""&&p.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()-g,details:{count:p.length}}),o.length>0)return{ops:[],trace:n,warnings:r,errors:o};let y=performance.now(),E={mode:"action",allowSysPaths:t.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:t.fnTableVersion??"1.0",actionName:t.actionName},F=[];for(let w of p)try{let P=eo(w);F.push(ft(P,E))}catch(P){P instanceof W?o.push({severity:"error",code:P.code,message:P.message,location:s(w.patch.location)}):P instanceof Error?o.push({severity:"error",code:"E_LOWER",message:P.message,location:s(w.patch.location)}):o.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(w.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-y,details:{count:F.length}}),o.length>0?{ops:[],trace:n,warnings:r,errors:o}:{ops:F,trace:n,warnings:r,errors:o}}function Ts(e,t){let n=e.split(`
10
+ `).map(r=>`${Es}${r}`).join(`
11
+ `);return[`domain ${gs} {`,` action ${t}() {`," when true {",n," }"," }","}"].join(`
12
+ `)}var ks="3.5.0";function Ns(e,t){let n=ao(e,t);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function St(e,t){let n=ao(e,t);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:bs(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function ao(e,t){let n=[],r=[],o=[],i=performance.now(),a;try{let p=j(e);a=p.tokens;let y=p.diagnostics.filter(F=>F.severity==="error");if(y.length>0)return o.push(...y),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 E=p.diagnostics.filter(F=>F.severity==="warning");r.push(...E)}catch(p){let y=p;return o.push({severity:"error",code:"E_LEX",message:y.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 p=me(a),y=p.diagnostics.filter(E=>E.severity==="error");if(y.length>0)return o.push(...y),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:$e(o)};c=p.program}catch(p){let y=p;return o.push({severity:"error",code:"E_PARSE",message:y.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=$r(c),u=d.diagnostics.filter(p=>p.severity==="error"),f=d.diagnostics.filter(p=>p.severity==="warning"),g=zn(d.program),A=gr(d.program),O=[...u,...g.diagnostics.filter(p=>p.severity==="error"),...A.diagnostics.filter(p=>p.severity==="error")],z=[...f,...g.diagnostics.filter(p=>p.severity==="warning"),...A.diagnostics.filter(p=>p.severity==="warning")];if(r.push(...z),n.push({phase:"analyze",durationMs:performance.now()-l}),O.length>0)return o.push(...O),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:$e(o)};let H=performance.now(),de=vr(d.program);n.push({phase:"generate",durationMs:performance.now()-H});for(let p of de.diagnostics)p.severity==="warning"?r.push(p):o.push(p);if(de.schema){let p=Mr(d.program,de.schema),y=p.diagnostics.filter(J=>J.severity==="warning"),E=p.diagnostics.filter(J=>J.severity==="error");if(r.push(...y),o.push(...E),E.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:$e(o)};let F=Qr(ks),w=Xr(d.program,e,de.schema,F),P=w.diagnostics.filter(J=>J.severity==="warning"),fe=w.diagnostics.filter(J=>J.severity==="error");return r.push(...P),o.push(...fe),fe.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:$e(o)}:{program:d.program,schema:de.schema,annotations:p.annotations,sourceMap:w.sourceMap,trace:n,warnings:r,errors:$e(o)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:$e(o)}}function bs(e,t,n){return Object.freeze({schema:e,graph:Sn(Vr(e)),annotations:t,sourceMap:n})}function Sn(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let t of e)Sn(t);return Object.freeze(e)}for(let t of Object.values(e))Sn(t);return Object.freeze(e)}var bn=10;function $e(e){if(e.length<=bn)return e;let t=e.slice(0,bn);return t.push({severity:"error",code:"E_TOO_MANY",message:`... and ${e.length-bn} more error(s). Fix the errors above first.`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),t}function Ss(e,t){return io(e,t)}var so=1e4,lo={start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}};function m(e,t,n=lo){return D(e,t,n)}function An(e){return[...e.warnings,...e.errors]}function po(e){let t=j(e),n=t.diagnostics.filter(i=>i.severity==="error");if(n.length>0)return{program:null,diagnostics:n};let r=me(t.tokens),o=r.diagnostics.filter(i=>i.severity==="error");return{program:r.program,diagnostics:o}}function Ge(e){return typeof e!="string"?[m("E_FRAGMENT_SCOPE_VIOLATION","expression fragment must be source text.")]:Ot(xt(`domain __Fragment { computed __fragment = ${e} }`),"expression")}function At(e){return typeof e!="string"?[m("E_FRAGMENT_SCOPE_VIOLATION","type fragment must be source text.")]:Ot(xt(`domain __Fragment { type __FragmentType = ${e} }`),"type")}function uo(e,t){return typeof e!="string"?[m("E_FRAGMENT_SCOPE_VIOLATION","state field type fragment must be source text.")]:Ot(xt(`domain __Fragment { state { __field: ${e} = ${t} } }`),"state field")}function vn(e){if(typeof e!="string")return[m("E_FRAGMENT_SCOPE_VIOLATION","action body fragment must be source text.")];let n=j(e).tokens.find(r=>["DOMAIN","STATE","COMPUTED","ACTION","TYPE","IMPORT","EXPORT"].includes(r.kind));return n?[m("E_FRAGMENT_SCOPE_VIOLATION","Action body fragments cannot contain top-level declarations.",n.location)]:Ot(xt(`domain __Fragment { action __fragment() { ${e} } }`),"action body")}function se(e,t){if(typeof e!="string")return[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be source text.`)];let n=j(e),r=n.diagnostics.filter(i=>i.severity==="error"),o=n.tokens.filter(i=>i.kind!=="EOF");return r.length>0||o.length!==1||o[0]?.kind!=="IDENTIFIER"||o[0].lexeme!==e?[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be one MEL identifier and cannot contain raw source syntax.`,o[0]?.location??lo)]:[]}function fo(e){let t=ho(e,"action params must be inspectable JSON data.");if(!t.ok)return{ok:!1,diagnostics:[t.diagnostic]};if(t.value===null)return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION","action params must be an array.")]};let n=As(t.value,"action params");if(!n.ok)return{ok:!1,diagnostics:[n.diagnostic]};let r=vs(t.value,n.value,"action params");if(r)return{ok:!1,diagnostics:[r]};let o=[],i=[];for(let a=0;a<n.value;a+=1){let s=Os(t.value,a,"action params");if(!s.ok){o.push(s.diagnostic);continue}let c=s.value;if(c===null||typeof c!="object"){o.push(m("E_FRAGMENT_SCOPE_VIOLATION",`action parameter ${a} must be an object.`));continue}let l=co(c,"name",`action parameter ${a}.name`),d=co(c,"type",`action parameter ${a}.type`),u=null,f=null,g=!0;if(!l.ok)o.push(l.diagnostic),g=!1;else{let A=se(l.value,"action parameter name");o.push(...A),g=g&&A.length===0,typeof l.value=="string"&&(u=l.value)}if(!d.ok)o.push(d.diagnostic),g=!1;else{let A=At(d.value);o.push(...A),g=g&&A.length===0,typeof d.value=="string"&&(f=d.value)}g&&u!==null&&f!==null&&i.push({name:u,type:f})}return o.length===0?{ok:!0,value:i,diagnostics:o}:{ok:!1,diagnostics:o}}function mo(e){if(e===null||typeof e!="object")return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","compileFragmentInContext() requires one object edit operation.")};let t=ho(e,"Source edit operation must be inspectable.");if(!t.ok)return{ok:!1,diagnostic:t.diagnostic};if(t.value!==null)return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","compileFragmentInContext() accepts exactly one edit operation.")};let n;try{n=e.kind}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","Source edit operation kind must be inspectable.")}}return typeof n!="string"?{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","Source edit operation kind must be source text.")}:{ok:!0,value:n}}function ho(e,t){try{return{ok:!0,value:Array.isArray(e)?e:null}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",t)}}}function As(e,t){try{return{ok:!0,value:e.length}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be inspectable JSON data.`)}}}function vs(e,t,n){if(t>so)return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must contain at most ${so} items.`);let r;try{r=Object.getOwnPropertyDescriptors(e)}catch{return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}let o=0;for(let i of Reflect.ownKeys(r)){if(typeof i=="symbol"||i!=="length"&&!xs(i,t))return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} keys must be JSON array indexes.`);if(i==="length")continue;let a;try{a=Object.getOwnPropertyDescriptor(e,i)}catch{return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}if(!a||!("value"in a))return m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${i}] must be a JSON data property.`);if(!a.enumerable)return m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${i}] must be enumerable JSON data.`);o+=1}return o!==t?m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be dense JSON array data.`):null}function xs(e,t){let n=Number(e);return Number.isInteger(n)&&n>=0&&n<t&&String(n)===e}function Os(e,t,n){try{if(!Object.hasOwn(e,t))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${t}] must be present JSON data.`)}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}return ws(e,String(t),`${n}[${t}]`)}function co(e,t,n){let r;try{r=Object.getOwnPropertyDescriptor(e,t)}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}if(!r)return{ok:!0,value:void 0};if(!("value"in r))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be a JSON data property.`)};try{return{ok:!0,value:e[t]}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}}function ws(e,t,n){let r;try{r=Object.getOwnPropertyDescriptor(e,t)}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}if(!r)return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be present JSON data.`)};if(!("value"in r))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be a JSON data property.`)};try{return{ok:!0,value:e[t]}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}}function ce(e,t,n){if(typeof t!="string")return m("E_FRAGMENT_SCOPE_VIOLATION","Target must be a source-map target key.");if(!Object.hasOwn(e.sourceMap.entries,t))return re(t);let r=vt(t);return!r||!n.includes(r)?m("E_TARGET_KIND_MISMATCH",`Target ${t} is not valid for this operation.`):null}function re(e){return m("E_TARGET_NOT_FOUND",`Target ${e} does not exist.`)}function vt(e){let t=e.indexOf(":");return t>0?e.slice(0,t):null}function xt(e){let t=j(e),n=t.diagnostics.filter(o=>o.severity==="error");return n.length>0?n:me(t.tokens).diagnostics.filter(o=>o.severity==="error")}function Ot(e,t){return e.map(n=>m("E_FRAGMENT_PARSE_FAILED",`Invalid ${t} fragment: ${n.message}`,n.location))}function Be(e,t){let n=e.domain.members.find(r=>r.kind==="action"&&r.name===t);return n?.kind==="action"?n:null}function wt(e,t){let n=e.domain.members.find(r=>r.kind==="computed"&&r.name===t);return n?.kind==="computed"?n:null}function Ct(e,t){for(let n of e.domain.members)if(n.kind==="state"){let r=n.fields.find(o=>o.name===t);if(r)return r}return null}function Xe(e,t){return e.domain.types.find(n=>n.name===t)??null}function It(e,t,n){let r=Xe(e,t);return!r||r.typeExpr.kind!=="objectType"?null:r.typeExpr.fields.find(o=>o.name===n)??null}function Pt(e){let t=e.slice(11),n=t.indexOf(".");return n<=0||n!==t.lastIndexOf(".")?null:{typeName:t.slice(0,n),fieldName:t.slice(n+1)}}function On(e,t){let n=j(e).tokens.filter(o=>o.location.start.offset>=t.location.start.offset&&o.location.end.offset<=t.location.end.offset&&o.kind!=="EOF"),r=[];for(let o of n)if(o.kind==="LBRACE")r.push(o);else if(o.kind==="RBRACE"){let i=r.pop();if(i&&o.location.end.offset===t.location.end.offset)return{open:i,close:o}}return null}function wn(e,t,n){return j(e).tokens.find(r=>r.kind===n&&r.location.start.offset>=t.location.start.offset&&r.location.end.offset<=t.location.end.offset)??null}function Cn(e,t,n){let r=Ao(e,t),o=e.slice(r,t);if(/^[ \t]*$/.test(o)&&r>0)return U(e,r,r,`${n}
13
+ `);let i=o.match(/^[ \t]*/)?.[0]??"";return U(e,t,t,`
14
+ ${n}
15
+ ${i}`)}function U(e,t,n,r){return Object.freeze({range:Cs(e,t,n),replacement:r})}function To(e,t){let n=[...t].sort((o,i)=>G(o.range.start)-G(i.range.start)),r=e;for(let o of n.reverse())r=`${r.slice(0,G(o.range.start))}${o.replacement}${r.slice(G(o.range.end))}`;return r}function G(e){if(e.offset===void 0)throw new Error("MelTextEdit range is missing offset.");return e.offset}function Mt(e,t){let n=Ao(e,t);return e.slice(n,t).match(/^[ \t]*/)?.[0]??""}function Dt(e,t){return e.split(/\r?\n/).map(n=>n.length>0?`${t}${n}`:n).join(`
16
+ `)}function ko(e){let t=e.params.map(r=>`${r.name}: ${r.type}`).join(", "),n=Dt(e.body.trim()," ");return n.length===0?`action ${e.name}(${t}) {
17
+ }`:`action ${e.name}(${t}) {
18
+ ${n}
19
+ }`}function No(e,t,n){let r=e.trim();return r.length===0?"":`
20
+ ${Dt(r,t)}
21
+ ${n}`}function Qe(e){if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return`[${e.map(n=>Qe(n)).join(", ")}]`;let t=e;return`{ ${Object.keys(t).sort(ye).map(n=>`${n}: ${Qe(t[n])}`).join(", ")} }`}function bo(e,t){let n=go(e),r=go(t),o=le([...new Set([...Object.keys(n),...Object.keys(r)])]),i=[],a=[],s=[];for(let c of o){let l=n[c],d=r[c];if(l===void 0&&d!==void 0)i.push(c);else if(l!==void 0&&d===void 0)a.push(c);else if(l!==void 0&&d!==void 0){let u=Eo(l),f=Eo(d);u!==f&&s.push({target:c,beforeHash:u,afterHash:f,before:l,after:d})}}return{addedTargets:i,removedTargets:a,modifiedTargets:s}}function le(e){return[...new Set(e)].sort(ye)}function So(e){try{return JSON.stringify(e)}catch{return String(e)}}function Cs(e,t,n){return Object.freeze({start:Object.freeze(yo(e,t)),end:Object.freeze(yo(e,n))})}function yo(e,t){let n=1,r=0;for(let o=0;o<t;o+=1)e[o]===`
22
+ `&&(n+=1,r=o+1);return{line:n,column:t-r+1,offset:t}}function Ao(e,t){return e.lastIndexOf(`
23
+ `,Math.max(0,t-1))+1}function go(e){let t={};for(let[n,r]of Object.entries(e.types))if(t[`type:${n}`]=r,r.definition.kind==="object")for(let[o,i]of Object.entries(r.definition.fields))t[`type_field:${n}.${o}`]=i;for(let[n,r]of Object.entries(e.state.fields))t[`state_field:${n}`]=r;for(let[n,r]of Object.entries(e.computed.fields))t[`computed:${n}`]=r;for(let[n,r]of Object.entries(e.actions))t[`action:${n}`]=r;return t}function Eo(e){return Fe(xn(e))}function xn(e){return e===void 0?"undefined":e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>xn(n)).join(",")}]`:`{${Object.entries(e).sort(([n],[r])=>ye(n,r)).map(([n,r])=>`${JSON.stringify(n)}:${xn(r)}`).join(",")}}`}var vo=1e4;function Ze(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return{ok:!0,value:e,diagnostics:[]};if(typeof e=="number")return Number.isFinite(e)?{ok:!0,value:e,diagnostics:[]}:{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be a finite JSON number.`)]};if(typeof e!="object")return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be a JSON literal.`)]};let n=Ms(e,`${t} must be inspectable JSON data.`);return n.ok?n.value!==null?Is(n.value,t):Ps(e,t):{ok:!1,diagnostics:[n.diagnostic]}}function Is(e,t){let n=Ds(e,`${t} array`);if(!n.ok)return{ok:!1,diagnostics:[n.diagnostic]};let r=Rs(e,n.value,`${t} array`);if(r)return{ok:!1,diagnostics:[r]};let o=[],i=[];for(let a=0;a<n.value;a+=1){let s=_s(e,a,`${t} array`);if(!s.ok){o.push(s.diagnostic);continue}let c=Ze(s.value,`${t}[${a}]`);o.push(...c.diagnostics),c.ok&&i.push(c.value)}return o.length===0?{ok:!0,value:i,diagnostics:o}:{ok:!1,diagnostics:o}}function Ps(e,t){let n;try{n=Object.getPrototypeOf(e)}catch{return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} object must be inspectable JSON data.`)]}}if(n!==Object.prototype&&n!==null)return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} object must be a plain JSON object.`)]};let r;try{r=Object.getOwnPropertyDescriptors(e)}catch{return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} object must be inspectable JSON data.`)]}}let o=[];for(let s of Reflect.ownKeys(r)){if(typeof s=="symbol")return{ok:!1,diagnostics:[m("E_FRAGMENT_SCOPE_VIOLATION",`${t} object keys must be JSON object keys.`)]};o.push(s)}let i=[],a=Object.create(null);for(let s of o.sort(ye)){let c=r[s];if(!("value"in c)){i.push(m("E_FRAGMENT_SCOPE_VIOLATION",`${t}.${s} must be a JSON data property.`));continue}if(!c.enumerable){i.push(m("E_FRAGMENT_SCOPE_VIOLATION",`${t}.${s} must be enumerable JSON data.`));continue}let l=se(s,`${t} object key`);i.push(...l);let d=xo(e,s,`${t}.${s}`);if(!d.ok){i.push(d.diagnostic);continue}let u=Ze(d.value,`${t}.${s}`);i.push(...u.diagnostics),l.length===0&&u.ok&&(a[s]=u.value)}return i.length===0?{ok:!0,value:a,diagnostics:i}:{ok:!1,diagnostics:i}}function Ms(e,t){try{return{ok:!0,value:Array.isArray(e)?e:null}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",t)}}}function Ds(e,t){try{return{ok:!0,value:e.length}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${t} must be inspectable JSON data.`)}}}function Rs(e,t,n){if(t>vo)return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must contain at most ${vo} items.`);let r;try{r=Object.getOwnPropertyDescriptors(e)}catch{return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}let o=0;for(let i of Reflect.ownKeys(r)){if(typeof i=="symbol"||i!=="length"&&!Ls(i,t))return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} keys must be JSON array indexes.`);if(i==="length")continue;let a;try{a=Object.getOwnPropertyDescriptor(e,i)}catch{return m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}if(!a||!("value"in a))return m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${i}] must be a JSON data property.`);if(!a.enumerable)return m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${i}] must be enumerable JSON data.`);o+=1}return o!==t?m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be dense JSON array data.`):null}function Ls(e,t){let n=Number(e);return Number.isInteger(n)&&n>=0&&n<t&&String(n)===e}function _s(e,t,n){try{if(!Object.hasOwn(e,t))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n}[${t}] must be present JSON data.`)}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}return xo(e,String(t),`${n}[${t}]`)}function xo(e,t,n){let r;try{r=Object.getOwnPropertyDescriptor(e,t)}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}if(!r)return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be present JSON data.`)};if(!("value"in r))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be a JSON data property.`)};try{return{ok:!0,value:e[t]}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}}function In(e,t,n,r){let o=[],i=null,a=(p,y)=>{let E=Rt(p);r&&wo(r,E)||o.push({range:E,location:p,rewrite:y})},s=(p,y,E)=>{let F=js(c(),p,y)??Rt(p);r&&wo(r,F)||o.push({range:F,location:p,rewrite:E})},c=()=>(i??=j(e).tokens.filter(p=>p.kind==="IDENTIFIER"),i),l=p=>{switch(p.kind){case"simpleType":n.kind==="type"&&p.name===n.name&&a(p.location,!0);return;case"unionType":p.types.forEach(l);return;case"arrayType":l(p.elementType);return;case"recordType":l(p.keyType),l(p.valueType);return;case"objectType":for(let y of p.fields)l(y.typeExpr);return;case"literalType":return}},d=(p,y={})=>{switch(p.kind){case"identifier":(n.kind==="state_field"&&p.name===n.name&&!Oo(p.name,y)||n.kind==="computed"&&p.name===n.name&&!Oo(p.name,y))&&a(p.location,!0);return;case"propertyAccess":d(p.object,y),n.kind==="type_field"&&p.property===n.fieldName&&s(p.location,p.property,!1);return;case"indexAccess":d(p.object,y),d(p.index,y);return;case"functionCall":p.args.forEach(E=>d(E,y));return;case"unary":d(p.operand,y);return;case"binary":d(p.left,y),d(p.right,y);return;case"ternary":d(p.condition,y),d(p.consequent,y),d(p.alternate,y);return;case"objectLiteral":for(let E of p.properties)E.kind==="objectProperty"?(n.kind==="type_field"&&E.key===n.fieldName&&s(E.location,E.key,!1),d(E.value,y)):d(E.expr,y);return;case"arrayLiteral":p.elements.forEach(E=>d(E,y));return;case"literal":case"systemIdent":case"iterationVar":return}},u=(p,y,E={})=>{let[F,...w]=p.segments;F?.kind==="propertySegment"&&n.kind==="state_field"&&F.name===n.name&&a(F.location,y);for(let P of w)P.kind==="propertySegment"?n.kind==="type_field"&&P.name===n.fieldName&&a(P.location,!1):d(P.index,E)},f=(p,y)=>{p.isPath?u(p.value,!0,y):d(p.value,y)},g=(p,y)=>{switch(p.kind){case"when":d(p.condition,y),p.body.forEach(E=>g(E,y));return;case"once":u(p.marker,!0,y),p.condition&&d(p.condition,y),p.body.forEach(E=>g(E,y));return;case"onceIntent":p.condition&&d(p.condition,y),p.body.forEach(E=>g(E,y));return;case"include":p.args.forEach(E=>d(E,y));return;case"patch":u(p.path,!0,y),p.value&&d(p.value,y);return;case"effect":p.args.forEach(E=>f(E,y));return;case"fail":p.message&&d(p.message,y);return;case"stop":return}},A=(p,y)=>{g(p,y)},O=(p,y)=>{g(p,y)},z=p=>{let y=new Set(p.params.map(E=>E.name));p.params.forEach(E=>H(E)),p.available&&d(p.available,{localParams:y}),p.dispatchable&&d(p.dispatchable,{localParams:y,preferLocalParams:!0}),p.body.forEach(E=>A(E,{localParams:y,preferLocalParams:!0}))},H=p=>{l(p.typeExpr)},de=p=>{let y=new Set(p.params.map(E=>E.name));p.params.forEach(E=>l(E.typeExpr)),p.body.forEach(E=>O(E,{localParams:y,preferLocalParams:!0}))};for(let p of t.imports);for(let p of t.domain.types)l(p.typeExpr);for(let p of t.domain.members)Fs(p,l,d,z,de);return $s(o)}function Fs(e,t,n,r,o){switch(e.kind){case"state":for(let i of e.fields)t(i.typeExpr),i.initializer&&n(i.initializer);return;case"computed":n(e.expression);return;case"action":r(e);return;case"flow":o(e);return}}function Oo(e,t){return t.preferLocalParams===!0&&t.localParams?.has(e)===!0}function js(e,t,n){let r=Rt(t),o=e.filter(a=>a.location.start.offset>=r.start&&a.location.end.offset<=r.end&&a.lexeme===n),i=o[o.length-1];return i?Rt(i.location):null}function Rt(e){return{start:G(e.start),end:G(e.end)}}function wo(e,t){return t.start>=e.start&&t.end<=e.end}function $s(e){let t=new Map;for(let n of e){let r=`${n.range.start}:${n.range.end}`,o=t.get(r);(!o||o.rewrite&&!n.rewrite)&&t.set(r,n)}return[...t.values()].sort((n,r)=>n.range.start-r.range.start||n.range.end-r.range.end)}function Io(e,t,n){let r=Mo(e,t,n);if(!r)return Do(t,"E_TARGET_NOT_FOUND",`Target ${n} does not exist.`);let o=qs(e,r.range,r.info.kind==="type_field"),i=In(e,t,r.info,o);return i.length>0?Rn(i[0].location,"E_REMOVE_BLOCKED_BY_REFERENCES","removeDeclaration is blocked because references to the target remain."):{ok:!0,edits:[U(e,o.start,o.end,"")],changedTargets:r.affectedTargets}}function Po(e,t,n,r){let o=Mo(e,t,n);if(!o)return Do(t,"E_TARGET_NOT_FOUND",`Target ${n} does not exist.`);if(Us(o.info)===r)return Rn(o.node.location,"E_FRAGMENT_SCOPE_VIOLATION","renameDeclaration newName must differ from the current declaration name.");let a=In(e,t,o.info),s=a.filter(l=>!l.rewrite);return s.length>0?Rn(s[0].location,"E_UNSAFE_RENAME_AMBIGUOUS","renameDeclaration is blocked because at least one reference cannot be rewritten safely."):{ok:!0,edits:Ks([o.nameRange,...a.map(l=>l.range)]).map(l=>U(e,l.start,l.end,r)),changedTargets:Bs(t,o,r)}}function Mo(e,t,n){let r=vt(n);if(r==="type"){let o=n.slice(5),i=Xe(t,o);return i?et(e,t,{kind:r,name:o},i,i.annotations,Pn(e,i.location,"TYPE",o)):null}if(r==="state_field"){let o=n.slice(12),i=Ct(t,o);return i?et(e,t,{kind:r,name:o},i,i.annotations,Co(i.location,o)):null}if(r==="computed"){let o=n.slice(9),i=wt(t,o);return i?et(e,t,{kind:r,name:o},i,i.annotations,Pn(e,i.location,"COMPUTED",o)):null}if(r==="action"){let o=n.slice(7),i=Be(t,o);return i?et(e,t,{kind:r,name:o},i,i.annotations,Pn(e,i.location,"ACTION",o)):null}if(r==="type_field"){let o=Pt(n);if(!o)return null;let i=It(t,o.typeName,o.fieldName);return i?et(e,t,{kind:r,typeName:o.typeName,fieldName:o.fieldName},i,i.annotations,Co(i.location,o.fieldName)):null}return null}function et(e,t,n,r,o,i){if(!i)return null;let a=zs(Dn(r.location),o);return{info:n,node:r,range:a,nameRange:i,affectedTargets:Gs(t,n)}}function Gs(e,t){if(t.kind==="type_field")return le([`type:${t.typeName}`,Mn(t)]);if(t.kind!=="type")return[Mn(t)];let n=[`type:${t.name}`],r=Xe(e,t.name);if(r?.typeExpr.kind==="objectType")for(let o of r.typeExpr.fields)n.push(`type_field:${t.name}.${o.name}`);return le(n)}function Bs(e,t,n){if(t.info.kind==="type"){let r=[`type:${t.info.name}`,`type:${n}`],o=Xe(e,t.info.name);if(o?.typeExpr.kind==="objectType")for(let i of o.typeExpr.fields)r.push(`type_field:${t.info.name}.${i.name}`),r.push(`type_field:${n}.${i.name}`);return le(r)}return t.info.kind==="type_field"?le([`type:${t.info.typeName}`,`type_field:${t.info.typeName}.${t.info.fieldName}`,`type_field:${t.info.typeName}.${n}`]):le([Mn(t.info),Vs(t.info,n)])}function Mn(e){switch(e.kind){case"type":return`type:${e.name}`;case"state_field":return`state_field:${e.name}`;case"computed":return`computed:${e.name}`;case"action":return`action:${e.name}`;case"type_field":return`type_field:${e.typeName}.${e.fieldName}`}}function Vs(e,t){switch(e.kind){case"type":return`type:${t}`;case"state_field":return`state_field:${t}`;case"computed":return`computed:${t}`;case"action":return`action:${t}`}}function Us(e){return e.kind==="type_field"?e.fieldName:e.name}function Pn(e,t,n,r){let o=Dn(t),i=j(e).tokens.filter(c=>c.location.start.offset>=o.start&&c.location.end.offset<=o.end&&c.kind!=="EOF"),a=i.findIndex(c=>c.kind===n);if(a<0)return null;let s=i.slice(a+1).find(c=>c.kind==="IDENTIFIER"&&c.lexeme===r);return s?Dn(s.location):null}function Co(e,t){let n=G(e.start);return{start:n,end:n+t.length}}function zs(e,t){if(!t||t.length===0)return e;let n=Math.min(...t.map(r=>G(r.location.start)));return{start:Math.min(e.start,n),end:e.end}}function qs(e,t,n){let r=t.start,o=t.end;for(;o<e.length&&/[ \t]/.test(e[o]);)o+=1;if(n&&e[o]===",")for(o+=1;o<e.length&&/[ \t]/.test(e[o]);)o+=1;else if(n){let l=r-1;for(;l>=0&&/[ \t]/.test(e[l]);)l-=1;if(e[l]===",")for(r=l;r>0&&/[ \t]/.test(e[r-1]);)r-=1}let i=Hs(e,r),a=Js(e,o),s=e.slice(i,r),c=e.slice(o,a);return/^[ \t]*$/.test(s)&&/^[ \t,]*$/.test(c)?{start:i,end:a<e.length?a+1:a}:{start:r,end:o}}function Dn(e){return{start:G(e.start),end:G(e.end)}}function Ks(e){let t=new Set;return[...e].sort((n,r)=>n.start-r.start||n.end-r.end).filter(n=>{let r=`${n.start}:${n.end}`;return t.has(r)?!1:(t.add(r),!0)})}function Hs(e,t){return e.lastIndexOf(`
24
+ `,Math.max(0,t-1))+1}function Js(e,t){let n=e.indexOf(`
25
+ `,t);return n===-1?e.length:n}function Do(e,t,n){return{ok:!1,code:t,message:n,location:e.domain.location}}function Rn(e,t,n){return{ok:!1,code:t,message:n,location:e}}function _o(e){if(e===void 0)return{ok:!0,value:Ws()};if(e===null||typeof e!="object")return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","compileFragmentInContext() options must be an object.")};let t=Ro(e,"includeModule");if(!t.ok)return{ok:!1,diagnostic:t.diagnostic};let n=Ro(e,"includeSchemaDiff");if(!n.ok)return{ok:!1,diagnostic:n.diagnostic};let r=Ln(e,"baseModule","options.baseModule");if(!r.ok)return{ok:!1,diagnostic:r.diagnostic};if(r.value===void 0)return{ok:!0,value:{baseModuleSourceHash:null,includeModule:t.value,includeSchemaDiff:n.value}};let o=Ys(r.value);return o.ok?{ok:!0,value:{baseModuleSourceHash:o.value,includeModule:t.value,includeSchemaDiff:n.value}}:{ok:!1,diagnostic:o.diagnostic}}function Ws(){return{baseModuleSourceHash:null,includeModule:!1,includeSchemaDiff:!1}}function Ro(e,t){let n=Ln(e,t,`options.${t}`);return n.ok?n.value===void 0?{ok:!0,value:!1}:typeof n.value!="boolean"?{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`options.${t} must be a boolean.`)}:{ok:!0,value:n.value}:{ok:!1,diagnostic:n.diagnostic}}function Ys(e){if(e===null||typeof e!="object")return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","options.baseModule must be an object.")};let t=Lo(e,"sourceMap","options.baseModule.sourceMap");if(!t.ok)return{ok:!1,diagnostic:t.diagnostic};if(t.value===null||typeof t.value!="object")return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","options.baseModule.sourceMap must be an object.")};let n=Lo(t.value,"sourceHash","options.baseModule.sourceMap.sourceHash");return n.ok?typeof n.value!="string"?{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION","options.baseModule.sourceMap.sourceHash must be source text.")}:{ok:!0,value:n.value}:{ok:!1,diagnostic:n.diagnostic}}function Ln(e,t,n){let r;try{r=Object.getOwnPropertyDescriptor(e,t)}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}if(!r)return{ok:!0,value:void 0};if(!("value"in r))return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be a JSON data property.`)};try{return{ok:!0,value:e[t]}}catch{return{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be inspectable JSON data.`)}}}function Lo(e,t,n){let r=Ln(e,t,n);return r.ok&&r.value===void 0?{ok:!1,diagnostic:m("E_FRAGMENT_SCOPE_VIOLATION",`${n} must be present JSON data.`)}:r}function q(e,t){return e.length>0?{edits:[],changedTargets:[],diagnostics:e}:t()}function ue(e,t){return{ok:!1,newSource:e,diagnostics:t,changedTargets:[],edits:[]}}function K(e,t){return{edits:[...e].sort((n,r)=>G(n.range.start)-G(r.range.start)),changedTargets:t,diagnostics:[]}}function x(...e){return{edits:[],changedTargets:[],diagnostics:e}}function Qs(e,t,n={}){let r=_o(n);if(!r.ok)return ue(e,[r.diagnostic]);let o=mo(t);if(!o.ok)return ue(e,[o.diagnostic]);if(r.value.baseModuleSourceHash!==null&&r.value.baseModuleSourceHash!==Fe(e))return ue(e,[m("E_STALE_MODULE","baseModule.sourceMap.sourceHash does not match baseSource.")]);let i=St(e,{mode:"module"}),a=An(i);if(i.errors.length>0||!i.module)return ue(e,a);let s=po(e);if(!s.program)return ue(e,s.diagnostics);let c;try{c=Xs(e,s.program,i.module,t,o.value)}catch{return ue(e,[m("E_FRAGMENT_SCOPE_VIOLATION","Source edit operation must be inspectable.")])}if(c.diagnostics.length>0||c.edits.length===0)return ue(e,c.diagnostics);let l=To(e,c.edits),d=St(l,{mode:"module"}),u=An(d),f=d.errors.length===0,g={ok:f,newSource:l,diagnostics:u,changedTargets:le(c.changedTargets),edits:c.edits};return f&&r.value.includeModule&&d.module&&(g.module=d.module),f&&r.value.includeSchemaDiff&&d.module&&(g.schemaDiff=bo(i.module.schema,d.module.schema)),g}function Xs(e,t,n,r,o){switch(o){case"addType":{let i=r,{name:a,expr:s}=i;return q([...se(a,"type name"),...At(s)],()=>Lt(e,t,`type ${a} = ${s}`,[`type:${a}`]))}case"addStateField":{let i=r,{name:a,type:s,defaultValue:c}=i,l=Ze(c,"state default"),d=[...se(a,"state field name"),...l.diagnostics];if(d.length>0||!l.ok)return x(...d);let u=Qe(l.value);return q(uo(s,u),()=>ic(e,t,`${a}: ${s} = ${u}`,`state_field:${a}`))}case"addComputed":{let i=r,{name:a,expr:s}=i;return q([...se(a,"computed name"),...Ge(s)],()=>Lt(e,t,`computed ${a} = ${s}`,[`computed:${a}`]))}case"addAction":{let i=r,{name:a,params:s,body:c}=i,l=fo(s);return q([...se(a,"action name"),...l.diagnostics,...vn(c)],()=>typeof a!="string"||typeof c!="string"||!l.ok?x(m("E_FRAGMENT_SCOPE_VIOLATION","Source edit operation must be inspectable.")):Lt(e,t,ko({kind:"addAction",name:a,params:l.value,body:c}),[`action:${a}`]))}case"addAvailable":{let i=r;return _n(e,t,n,i.target,"available",i.expr)}case"addDispatchable":{let i=r;return _n(e,t,n,i.target,"dispatchable",i.expr)}case"replaceActionBody":return Zs(e,t,n,r);case"replaceComputedExpr":return ec(e,t,n,r);case"replaceAvailable":{let i=r;return Fo(e,t,n,i.target,"available",i.expr)}case"replaceDispatchable":{let i=r;return Fo(e,t,n,i.target,"dispatchable",i.expr)}case"replaceStateDefault":return tc(e,t,n,r);case"replaceTypeField":return nc(e,t,n,r);case"removeDeclaration":return rc(e,t,n,r.target);case"renameDeclaration":{let i=r,{target:a,newName:s}=i;return q(se(s,"rename target name"),()=>oc(e,t,n,a,s))}default:return x(m("E_FRAGMENT_SCOPE_VIOLATION",`Unknown source edit operation: ${So(r)}`))}}function _n(e,t,n,r,o,i){let a=ce(n,r,["action"]);if(a)return x(a);let s=Be(t,r.slice(7));return s?o==="available"&&s.available||o==="dispatchable"&&s.dispatchable?x(m("E_FRAGMENT_SCOPE_VIOLATION",`Action already has ${o} guard.`,s.location)):q(Ge(i),()=>{let c=On(e,s);if(!c)return x(m("E_TARGET_NOT_FOUND","Action body range was not found.",s.location));let l=o==="available"&&s.dispatchable?wn(e,s,"DISPATCHABLE")?.location.start.offset??c.open.location.start.offset:c.open.location.start.offset,d=U(e,l,l,` ${o} when ${i} `);return K([d],[r])}):x(re(r))}function Fo(e,t,n,r,o,i){let a=ce(n,r,["action"]);if(a)return x(a);let s=Be(t,r.slice(7));if(!s)return x(re(r));let c=o==="available"?s.available:s.dispatchable;if(!c)return i===null?x(m("E_TARGET_NOT_FOUND",`Action does not have ${o} guard.`,s.location)):_n(e,t,n,r,o,i);if(i===null){let l=wn(e,s,o==="available"?"AVAILABLE":"DISPATCHABLE");return l?K([U(e,l.location.start.offset,c.location.end.offset,"")],[r]):x(re(r))}return q(Ge(i),()=>K([U(e,c.location.start.offset,c.location.end.offset,i)],[r]))}function Zs(e,t,n,r){let{target:o,body:i}=r,a=ce(n,o,["action"]);if(a)return x(a);let s=Be(t,o.slice(7));return s?q(vn(i),()=>{let c=On(e,s);if(!c)return x(re(o));let l=Mt(e,s.location.start.offset),d=No(i,`${l} `,l);return K([U(e,c.open.location.end.offset,c.close.location.start.offset,d)],[o])}):x(re(o))}function ec(e,t,n,r){let{target:o,expr:i}=r,a=ce(n,o,["computed"]);if(a)return x(a);let s=wt(t,o.slice(9));return s?q(Ge(i),()=>K([U(e,s.expression.location.start.offset,s.expression.location.end.offset,i)],[o])):x(re(o))}function tc(e,t,n,r){let{target:o,value:i}=r,a=ce(n,o,["state_field"]);if(a)return x(a);let s=Ct(t,o.slice(12));if(!s)return x(re(o));let c=Ze(i,"state default");if(c.diagnostics.length>0||!c.ok)return x(...c.diagnostics);let l=Qe(c.value);return q(Ge(l),()=>{let d=s.initializer?.location.start.offset??s.typeExpr.location.end.offset,u=s.initializer?.location.end.offset??s.typeExpr.location.end.offset,f=s.initializer?l:` = ${l}`;return K([U(e,d,u,f)],[o])})}function nc(e,t,n,r){let{target:o,type:i}=r,a=ce(n,o,["type_field"]);if(a)return x(a);let s=Pt(o),c=s?It(t,s.typeName,s.fieldName):null;return!s||!c?x(re(o)):q(At(i),()=>K([U(e,c.typeExpr.location.start.offset,c.typeExpr.location.end.offset,i)],[`type:${s.typeName}`,o]))}function rc(e,t,n,r){let o=ce(n,r,["type","type_field","state_field","computed","action"]);if(o)return x(o);let i=Io(e,t,r);return i.ok?K(i.edits,i.changedTargets):x(m(i.code,i.message,i.location))}function oc(e,t,n,r,o){let i=ce(n,r,["type","type_field","state_field","computed","action"]);if(i)return x(i);let a=Po(e,t,r,o);return a.ok?K(a.edits,a.changedTargets):x(m(a.code,a.message,a.location))}function Lt(e,t,n,r){let o=t.domain.location.end.offset-1,a=`${Mt(e,o)} `,s=Dt(n,a);return K([Cn(e,o,s)],r)}function ic(e,t,n,r){let o=t.domain.members.find(c=>c.kind==="state");if(!o||o.kind!=="state")return Lt(e,t,`state {
26
+ ${n}
27
+ }`,[r]);let i=o.location.end.offset-1,s=`${Mt(e,i)} `;return K([Cn(e,i,`${s}${n}`)],[r])}export{Ft as a,jo as b,ac as c,Fn as d,jn as e,jt as f,$n as g,Gn as h,cc as i,k as j,$t as k,j as l,gc as m,Ec as n,Bn as o,Gt as p,Vn as q,kc as r,Nc as s,Un as t,Bt as u,me as v,tt as w,Vt as x,zn as y,D as z,qn as A,Pc as B,$o as C,Mc as D,Dc as E,Zt as F,gr as G,en as H,tn as I,nn as J,rn as K,Ti as L,W as M,dt as N,N as O,pt as P,on as Q,ki as R,an as S,ye as T,h as U,Bi as V,zi as W,ft as X,aa as Y,vr as Z,Mr as _,$r as $,Vr as aa,Qr as ba,Xr as ca,Ns as da,St as ea,Ss as fa,Qs as ga};
@@ -1,4 +1,4 @@
1
- import{da as t}from"./chunk-PEO2YZ2Y.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-53553ZHJ.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};
@@ -1,3 +1,3 @@
1
- import{a as f,b as g}from"./chunk-M3P5RIDR.js";import{da as d}from"./chunk-PEO2YZ2Y.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-5MK25QWV.js";import{da as d}from"./chunk-53553ZHJ.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-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};
1
+ import{a as e}from"./chunk-PGOH34S3.js";import"./chunk-5MK25QWV.js";import"./chunk-53553ZHJ.js";var t=e.esbuild,n=t;export{n as default,t as melPlugin};