@manifesto-ai/compiler 3.7.1 → 3.8.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.
- package/dist/analyzer/expr-type-surface.d.ts +4 -0
- package/dist/analyzer/object-contribution-types.d.ts +19 -0
- package/dist/analyzer/validator.d.ts +1 -0
- package/dist/{chunk-2ZRNXFBQ.js → chunk-M3P5RIDR.js} +1 -1
- package/dist/{chunk-Q56VWGSA.js → chunk-MB43CHXV.js} +1 -1
- package/dist/chunk-PEO2YZ2Y.js +12 -0
- package/dist/esbuild.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lexer/tokens.d.ts +1 -1
- package/dist/node-loader.js +1 -1
- package/dist/parser/ast.d.ts +6 -1
- package/dist/rollup.js +1 -1
- package/dist/rspack.js +1 -1
- package/dist/vite.js +1 -1
- package/dist/webpack.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-O654OLQV.js +0 -12
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { ComputedNode, DomainNode, ExprNode, ParamNode, TypeDeclNode, TypeExprNode } from "../parser/ast.js";
|
|
2
|
+
import type { SpreadOperandClassification } from "./object-contribution-types.js";
|
|
3
|
+
export type { SpreadOperandClassification, } from "./object-contribution-types.js";
|
|
4
|
+
export { mayYieldArrayExpr } from "./object-contribution-types.js";
|
|
2
5
|
export type TypeEnv = Map<string, TypeExprNode>;
|
|
3
6
|
export type ComparableSurfaceClass = "primitive" | "nonprimitive" | "unknown";
|
|
4
7
|
export interface DomainTypeSymbols {
|
|
@@ -19,3 +22,4 @@ export declare function getIndexType(typeExpr: TypeExprNode | null, symbols: Dom
|
|
|
19
22
|
export declare function getArrayElementType(typeExpr: TypeExprNode | null, symbols: DomainTypeSymbols): TypeExprNode | null;
|
|
20
23
|
export declare function isPrimitiveEntityIdType(typeExpr: TypeExprNode, symbols: DomainTypeSymbols): boolean;
|
|
21
24
|
export declare function isNullType(typeExpr: TypeExprNode): boolean;
|
|
25
|
+
export declare function classifySpreadOperandType(typeExpr: TypeExprNode | null, symbols: DomainTypeSymbols): SpreadOperandClassification;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ExprNode, TypeExprNode } from "../parser/ast.js";
|
|
2
|
+
export type SpreadOperandClassification = "object" | "nullable-object" | "invalid" | "unknown";
|
|
3
|
+
type InferExprType<Env, Symbols> = (expr: ExprNode, env: Env, symbols: Symbols) => TypeExprNode | null;
|
|
4
|
+
type ResolveType<Symbols> = (typeExpr: TypeExprNode | null, symbols: Symbols) => TypeExprNode | null;
|
|
5
|
+
type ExprTypeContext<Env, Symbols> = {
|
|
6
|
+
env: Env;
|
|
7
|
+
symbols: Symbols;
|
|
8
|
+
inferExprType: InferExprType<Env, Symbols>;
|
|
9
|
+
resolveType: ResolveType<Symbols>;
|
|
10
|
+
};
|
|
11
|
+
export declare function inferObjectLiteralContributionType<Env, Symbols>(expr: Extract<ExprNode, {
|
|
12
|
+
kind: "objectLiteral";
|
|
13
|
+
}>, env: Env, symbols: Symbols, inferExprType: InferExprType<Env, Symbols>, resolveType: ResolveType<Symbols>): TypeExprNode | null;
|
|
14
|
+
export declare function inferMergeContributionType<Env, Symbols>(expr: Extract<ExprNode, {
|
|
15
|
+
kind: "functionCall";
|
|
16
|
+
}>, env: Env, symbols: Symbols, inferExprType: InferExprType<Env, Symbols>, resolveType: ResolveType<Symbols>): TypeExprNode | null;
|
|
17
|
+
export declare function classifySpreadOperandType<Symbols>(typeExpr: TypeExprNode | null, symbols: Symbols, resolveType: ResolveType<Symbols>): SpreadOperandClassification;
|
|
18
|
+
export declare function mayYieldArrayExpr<Env, Symbols>(expr: ExprNode | undefined, context?: ExprTypeContext<Env, Symbols>): boolean;
|
|
19
|
+
export {};
|
|
@@ -64,6 +64,7 @@ export declare class SemanticValidator {
|
|
|
64
64
|
private requireAssignable;
|
|
65
65
|
private requireArrayCompatible;
|
|
66
66
|
private requireLenCompatible;
|
|
67
|
+
private requireSpreadOperand;
|
|
67
68
|
private validateCoalesceTypes;
|
|
68
69
|
private validateMatchCall;
|
|
69
70
|
private validateArgSelectionCall;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{da as t}from"./chunk-
|
|
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)};
|
|
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-
|
|
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(`
|
|
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};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var it={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"},gr=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 aa(e){return e in it}function Vt(e){return gr.has(e)}function Ht(e){return Object.hasOwn(it,e)?it[e]:void 0}function at(e,t,n,r){return{kind:e,lexeme:t,location:n,value:r}}function Kt(e,t,n){return{line:e,column:t,offset:n}}function Wt(e,t,n){return{start:e,end:t,source:n}}function ca(e,t){return{start:e,end:e,source:t}}function y(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 st=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(at("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(Vt(t)){this.error(`'${t}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ht(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 Wt(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 Kt(n,t-r+1,t)}addToken(t,n){let r=this.source.slice(this.start,this.current);this.tokens.push(at(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 Le(e,t){return new st(e,t).tokenize()}function ga(e){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(e.kind)}function Ea(e){return["when","once","onceIntent","patch","effect","fail","stop"].includes(e.kind)}var Yt=(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))(Yt||{});function ct(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 Qt(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 ka(e){return ct(e)!==0}function ba(e){return e==="BANG"||e==="MINUS"}function Jt(e){return e==="QUESTION"||e==="QUESTION_QUESTION"}var lt=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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(i.location,s.location)}),this.match("COMMA")}let r=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:y(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=ct(this.peek().kind);if(r<=t)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let o=Qt(this.peek().kind);if(!o)break;this.advance();let i=Jt(this.previous().kind)?r-1:r,a=this.parseExpression(i);n={kind:"binary",operator:o,left:n,right:a,location:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(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:y(i.location,a)})}else break;let o=t[t.length-1];return{kind:"path",segments:t,location:y(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:y(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 Re(e){return new lt(e).parse()}var je=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)}},dt=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 je("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 je("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 Xt(e){return new dt().analyze(e)}function M(e,t,n,r){return{severity:"error",code:e,message:t,location:n,...r}}function Zt(e,t,n,r){return{severity:"warning",code:e,message:t,location:n,...r}}function Ma(e,t,n){return{severity:"info",code:e,message:t,location:n}}function Er(e){return e.severity==="error"}function Da(e){return e.some(Er)}function Oa(e,t){return e.filter(n=>n.severity===t)}function Fe(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}:on(i,e.location,n,o)}function _e(e,t,n,r,o){let i=e.args.map(a=>r(a,t,n));return i.some(a=>a===null)?null:on(i,e.location,n,o)}function en(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=>!Z(s));return o.some(s=>Z(s))&&i.length===1&&i[0].kind==="objectType"?"nullable-object":"invalid"}function G(e,t){if(!e)return!1;if(tn(pt(e,t),t)||e.kind==="arrayLiteral")return!0;if(e.kind==="ternary")return G(e.consequent,t)||G(e.alternate,t);if(e.kind!=="functionCall")return!1;if(e.name==="coalesce"){for(let n of e.args)if(!ce(n,t)){if(G(n,t))return!0;if(le(n,t))return!1}return!1}return(e.name==="cond"||e.name==="if")&&e.args.length>=3?G(e.args[1],t)||G(e.args[2],t):!1}function ce(e,t){let n=pt(e,t);return n&&nn(n,t)?!0:e.kind==="literal"?e.value===null:e.kind==="ternary"?ce(e.consequent,t)&&ce(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.length>0&&e.args.every(r=>ce(r,t)):(e.name==="cond"||e.name==="if")&&e.args.length>=3?ce(e.args[1],t)&&ce(e.args[2],t):!1}function le(e,t){let n=pt(e,t);return n&&rn(n,t)?!0:e.kind==="literal"?e.value!==null:e.kind==="arrayLiteral"||e.kind==="objectLiteral"?!0:e.kind==="ternary"?le(e.consequent,t)&&le(e.alternate,t):e.kind!=="functionCall"?!1:e.name==="coalesce"?e.args.some(r=>le(r,t)):e.name==="merge"?!0:(e.name==="cond"||e.name==="if")&&e.args.length>=3?le(e.args[1],t)&&le(e.args[2],t):!1}function pt(e,t){return t?t.resolveType(t.inferExprType(e,t.env,t.symbols),t.symbols):null}function tn(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=>tn(r,t)):!1:!1}function nn(e,t){if(!t)return Z(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>nn(r,t)):Z(n):!1}function rn(e,t){if(!t)return!Z(e);let n=t.resolveType(e,t.symbols);return n?n.kind==="unionType"?n.types.length>0&&n.types.every(r=>rn(r,t)):!Z(n):!1}function on(e,t,n,r){let o=new Map;for(let i of e){let a=Tr(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=kr([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 Tr(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=>!Z(c));if(!o.some(c=>Z(c))||i.length!==1)return null;let s=i[0];return s.kind!=="objectType"?null:s.fields.map(c=>({...c,optional:!0}))}function Z(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function kr(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 sn=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),cn=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),ln=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),br=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),Nr=new Set(["updateById","removeById"]);function $e(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 Ge(e){let t=new Map;for(let n of e)t.set(n.name,n.typeExpr);return t}function m(e,t,n){switch(e.kind){case"literal":return Fr(e.value,e.location);case"identifier":return t.get(e.name)??n.stateTypes.get(e.name)??Sr(e.name,n);case"propertyAccess":return te(m(e.object,t,n),e.property,n);case"indexAccess":return we(m(e.object,t,n),n);case"objectLiteral":return Fe(e,t,n,m,k);case"arrayLiteral":{let r=w(e.elements.map(o=>m(o,t,n)),e.location);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"unary":return vr(e);case"binary":return xr(e,t,n);case"ternary":return w([m(e.consequent,t,n),m(e.alternate,t,n)],e.location);case"functionCall":return Ar(e,t,n);case"systemIdent":return null;case"iterationVar":return t.get("$item")??null}}function B(e,t,n){let r=m(e,t,n);if(r)return dn(r,n);switch(e.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return e.operator==="??"?xe([B(e.left,t,n),B(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 xe([B(e.consequent,t,n),B(e.alternate,t,n)]);case"functionCall":return br.has(e.name)?"nonprimitive":sn.has(e.name)||cn.has(e.name)||ln.has(e.name)||e.name==="toBoolean"?"primitive":(e.name==="cond"||e.name==="if")&&e.args.length>=3?xe([B(e.args[1],t,n),B(e.args[2],t,n)]):e.name==="coalesce"?xe(e.args.map(o=>B(o,t,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function dn(e,t){let n=k(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 xe(n.types.map(r=>dn(r,t)))}}function k(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),k(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function te(e,t,n){let r=k(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?w([o.typeExpr,P("null",o.location)],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!q(i)).map(i=>te(i,t,n)).filter(i=>i!==null);return w(o,r.location)}return null}function we(e,t){let n=k(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=>!q(o)).map(o=>we(o,t)).filter(o=>o!==null);return w(r,n.location)}return null}function U(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(o=>!q(o)).map(o=>U(o,t)).filter(o=>o!==null);return w(r,n.location)}return null}function Be(e,t){let n=k(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=>Be(r,t));default:return!1}}function q(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function Ue(e,t){return en(e,t,k)}function Sr(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=m(n.expression,new Map,t);return t.computedTypeInFlight.delete(e),t.computedTypeCache.set(e,r),r}function vr(e){return e.operator==="!"?P("boolean",e.location):P("number",e.location)}function xr(e,t,n){switch(e.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return P("boolean",e.location);case"+":case"-":case"*":case"/":case"%":return P("number",e.location);case"??":return w([m(e.left,t,n),m(e.right,t,n)],e.location)}}function Ar(e,t,n){if(sn.has(e.name))return P("boolean",e.location);if(cn.has(e.name))return P("number",e.location);if(e.name==="idiv")return w([P("number",e.location),P("null",e.location)],e.location);if(ln.has(e.name))return P("string",e.location);if(e.name==="toBoolean")return P("boolean",e.location);if(e.name==="findById"&&e.args.length>=1){let r=U(m(e.args[0],t,n),n);return r?w([r,P("null",e.location)],e.location):null}if(e.name==="find"&&e.args.length>=1){let r=U(m(e.args[0],t,n),n);return r?w([r,P("null",e.location)],e.location):null}if(e.name==="filter"&&e.args.length>=1)return m(e.args[0],t,n);if(e.name==="map"&&e.args.length>=2){let r=m(e.args[0],t,n),o=U(r,n);if(!o)return null;let i=m(e.args[1],$r(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 U(m(e.args[0],t,n),n);if(e.name==="at"&&e.args.length>=1)return we(m(e.args[0],t,n),n);if(e.name==="field"&&e.args.length>=2){let r=_r(e.args[1]);return r?te(m(e.args[0],t,n),r,n):null}return Nr.has(e.name)&&e.args.length>=1?m(e.args[0],t,n):(e.name==="cond"||e.name==="if")&&e.args.length>=3?w([m(e.args[1],t,n),m(e.args[2],t,n)],e.location):e.name==="coalesce"?Rr(e,t,n):e.name==="match"?wr(e,t,n):e.name==="argmax"||e.name==="argmin"?Cr(e,t,n):e.name==="slice"&&e.args.length>=1?m(e.args[0],t,n):e.name==="split"?{kind:"arrayType",elementType:P("string",e.location),location:e.location}:e.name==="keys"?{kind:"arrayType",elementType:P("string",e.location),location:e.location}:e.name==="values"&&e.args.length>=1?jr(e,t,n):e.name==="merge"?_e(e,t,n,m,k):null}function xe(e){let t=!1;for(let n of e){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(t=!0)}return t?"unknown":"primitive"}function w(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 wr(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(m(i.elements[1],t,n))}return r.push(m(e.args[e.args.length-1],t,n)),w(r,e.location)}function Cr(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(m(a.elements[0],t,n))}let o=w(r,e.location);return o?Mr(e,t,n)?o:w([o,P("null",e.location)],e.location):null}var Pr=Symbol("arg-selection:other-string"),Ir=Symbol("arg-selection:other-number");function Mr(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(!de(c,t,n,o))return!1;let i=[...o.values()].map(c=>({key:c.key,values:Or(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 pn(i,0,s,()=>r.some(c=>j(c,s)===!0))}function pn(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),!pn(e,t+1,n,r))return n.delete(o.key),!1;return n.delete(o.key),!0}function de(e,t,n,r){switch(e.kind){case"literal":return e.literalType==="boolean";case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":return Dr(e,t,n,r);case"unary":return e.operator==="!"&&de(e.operand,t,n,r);case"binary":return e.operator==="&&"||e.operator==="||"?de(e.left,t,n,r)&&de(e.right,t,n,r):e.operator==="=="||e.operator==="!="?an(e.left,e.right,t,n,r):!1;case"functionCall":switch(e.name){case"and":case"or":return e.args.every(o=>de(o,t,n,r));case"not":return e.args.length===1&&de(e.args[0],t,n,r);case"eq":case"neq":return e.args.length===2&&an(e.args[0],e.args[1],t,n,r);case"isNull":case"isNotNull":return e.args.length===1&&ut(e.args[0],t,n,r,null);default:return!1}default:return!1}}function Dr(e,t,n,r){let o=Ae(e),i=m(e,t,n);return!o||!i||!fn(i,n)||mt(e,t,n)?!1:(r.get(o)||r.set(o,{key:o,typeExpr:i,comparedLiterals:[]}),!0)}function an(e,t,n,r,o){let i=ft(e),a=ft(t);return i!==void 0&&a!==void 0?!0:a!==void 0?ut(e,n,r,o,a):i!==void 0?ut(t,n,r,o,i):!1}function ut(e,t,n,r,o){let i=Ae(e),a=m(e,t,n);if(!i||!a||!mn(a,n)||mt(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 Or(e,t){let n=[],r=!1,o=a=>{n.some(s=>Object.is(s,a))||n.push(a)},i=a=>{let s=k(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(Pr);return;case"number":for(let c of e.comparedLiterals)typeof c=="number"&&o(c);o(Ir);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 j(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=Ae(e);return n?t.get(n):void 0}case"unary":{let n=j(e.operand,t);return e.operator==="!"&&typeof n=="boolean"?!n:void 0}case"binary":{let n=j(e.left,t),r=j(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=>j(r,t));return n.every(r=>typeof r=="boolean")?n.every(Boolean):void 0}case"or":{let n=e.args.map(r=>j(r,t));return n.every(r=>typeof r=="boolean")?n.some(Boolean):void 0}case"not":{let n=e.args.length===1?j(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=j(e.args[0],t),r=j(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=j(e.args[0],t);return n===void 0?void 0:n===null}case"isNotNull":{if(e.args.length!==1)return;let n=j(e.args[0],t);return n===void 0?void 0:n!==null}case"cond":case"if":{if(e.args.length!==3)return;let n=j(e.args[0],t);return typeof n!="boolean"?void 0:j(n?e.args[1]:e.args[2],t)}default:return}default:return}}function Ae(e){switch(e.kind){case"identifier":return`id:${e.name}`;case"iterationVar":return"$item";case"propertyAccess":{let t=Ae(e.object);return t?`${t}.${e.property}`:null}case"indexAccess":{let t=Ae(e.object),n=ft(e.index);return t&&n!==void 0?`${t}[${JSON.stringify(n)}]`:null}default:return null}}function mt(e,t,n){switch(e.kind){case"propertyAccess":return ht(m(e.object,t,n),n)||Lr(e.object,e.property,t,n)||mt(e.object,t,n);case"indexAccess":return!0;default:return!1}}function Lr(e,t,n,r){return un(m(e,n,r),t,r)}function un(e,t,n){let r=k(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=>!q(i));return o.length===0||o.some(i=>un(i,t,n))}return!0}function fn(e,t){let n=k(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=>fn(r,t));default:return!1}}function mn(e,t){let n=k(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=>mn(r,t));default:return!1}}function ft(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 Rr(e,t,n){let r=e.args.map(a=>m(a,t,n));if(r.some(a=>a===null))return w(r,e.location);let o=r.map(a=>yn(a,n)).filter(a=>a!==null);if(o.length===0)return w(r,e.location);let i=[...o];return r.every(a=>a!==null&&ht(a,n))&&i.push(P("null",e.location)),w(i,e.location)}function jr(e,t,n){if(e.args.length<1)return null;let r=hn(m(e.args[0],t,n),n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}function hn(e,t){let n=k(e,t);return n?n.kind==="recordType"?n.valueType:n.kind==="objectType"?w(n.fields.map(r=>r.typeExpr),n.location):n.kind==="unionType"?w(n.types.filter(r=>!q(r)).map(r=>hn(r,t)),n.location):null:null}function yn(e,t){let n=k(e,t);if(!n||q(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(o=>yn(o,t)).filter(o=>o!==null);return r.length===0?null:w(r,n.location)}function ht(e,t){let n=k(e,t);return!n||q(n)?!0:n.kind!=="unionType"?!1:n.types.some(r=>ht(r,t))}function Fr(e,t){return{kind:"literalType",value:e,location:t}}function P(e,t){return{kind:"simpleType",name:e,location:t}}function _r(e){return e.kind==="literal"&&typeof e.value=="string"?e.value:null}function $r(e,t){let n=new Map(e);return n.set("$item",t),n}var Gr=new Set(["findById","existsById"]),gt=new Set(["updateById","removeById"]),Br=new Set([...Gr,...gt]);function Y(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(M(n,r,o)))}function gn(e){let t=[],n=new Set,r=$e(e.domain);Vr(e.domain,r,t,n);for(let o of e.domain.members)switch(o.kind){case"computed":N(o.expression,"computed",new Map,r,t,n,0);break;case"action":{let i=Ge(o.params);Ur(o,i,r,t,n);break}case"state":case"flow":break}return t}function Ur(e,t,n,r,o){e.available&&N(e.available,"available",t,n,r,o,0),e.dispatchable&&N(e.dispatchable,"dispatchable",t,n,r,o,0);for(let i of e.body)qr(i,t,n,r,o)}function qr(e,t,n,r,o){switch(e.kind){case"when":N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"once":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"onceIntent":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"include":break}}function pe(e,t,n,r,o){switch(e.kind){case"when":N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"once":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"onceIntent":e.condition&&N(e.condition,"guard",t,n,r,o,0);for(let i of e.body)pe(i,t,n,r,o);break;case"patch":e.value&&N(e.value,"patch",t,n,r,o,0);break;case"effect":for(let i of e.args)i.isPath||N(i.value,"action",t,n,r,o,0);break;case"fail":e.message&&N(e.message,"action",t,n,r,o,0);break;case"include":case"stop":break}}function N(e,t,n,r,o,i,a){switch(e.kind){case"functionCall":{zr(e,t,n,r,o,i,a);let s=a+(gt.has(e.name)?1:0);for(let c of e.args)N(c,t,n,r,o,i,s);break}case"binary":N(e.left,t,n,r,o,i,a),N(e.right,t,n,r,o,i,a);break;case"unary":N(e.operand,t,n,r,o,i,a);break;case"ternary":N(e.condition,t,n,r,o,i,a),N(e.consequent,t,n,r,o,i,a),N(e.alternate,t,n,r,o,i,a);break;case"propertyAccess":N(e.object,t,n,r,o,i,a);break;case"indexAccess":N(e.object,t,n,r,o,i,a),N(e.index,t,n,r,o,i,a);break;case"objectLiteral":for(let s of e.properties)N(s.kind==="objectProperty"?s.value:s.expr,t,n,r,o,i,a);break;case"arrayLiteral":for(let s of e.elements)N(s,t,n,r,o,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function zr(e,t,n,r,o,i,a){if(!Br.has(e.name)||e.args.length===0)return;gt.has(e.name)&&(t==="available"?Y(o,i,"E035","updateById/removeById are not allowed in available conditions.",e.location):t==="dispatchable"?Y(o,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",e.location):t==="guard"?Y(o,i,"E034","updateById/removeById are not allowed in guard conditions.",e.location):t!=="patch"&&Y(o,i,"E031","updateById/removeById are only allowed in patch RHS.",e.location),a>0&&Y(o,i,"E032","Nested transform primitives are not allowed.",e.location),t==="patch"&&!yt(e.args[0],r)&&Y(o,i,"E033","Transform primitive collection argument must resolve to a state path.",e.args[0].location));let s=Kr(e.args[0],n,r);if(!s)return;let c=Tn(s,r);if(!c){Y(o,i,"E030","Collection element type must declare an 'id' field for entity primitives.",e.args[0].location);return}Be(c,r)||Y(o,i,"E030a","Entity 'id' field must be string or number.",e.args[0].location)}function Vr(e,t,n,r){for(let o of e.members)if(o.kind==="state")for(let i of o.fields)Hr(i,t,n,r)}function Hr(e,t,n,r){if(!e.initializer||e.initializer.kind!=="arrayLiteral")return;let o=U(e.typeExpr,t);if(!o)return;let i=Tn(o,t);if(!i||!Be(i,t))return;let a=new Map;for(let s of e.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=En(s);if(c.kind!=="literal")continue;let l=`${typeof c.value}:${String(c.value)}`;if(a.get(l)){Y(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.location);continue}a.set(l,c.location)}}function En(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=En(n.expr);r.kind!=="absent"&&(t=r)}return t}function Kr(e,t,n){return U(m(e,t,n),n)}function Tn(e,t){return te(e,"id",t)}function yt(e,t){switch(e.kind){case"identifier":return t.stateTypes.has(e.name);case"propertyAccess":return yt(e.object,t);case"indexAccess":return yt(e.object,t);default:return!1}}function kn(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Wr=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function T(e,t){return{kind:"simpleType",name:e,location:t}}function z(e,t,n){let r=k(e,n),o=k(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=>z(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=z(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:z(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=z(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:z(r.valueType,o.valueType,n):null}function v(e,t){let n=k(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<${v(n.elementType,t)}>`;case"recordType":return`Record<${v(n.keyType,t)}, ${v(n.valueType,t)}>`;case"objectType":return`{ ${n.fields.map(r=>`${r.name}${r.optional?"?":""}: ${v(r.typeExpr,t)}`).join("; ")} }`;case"unionType":return n.types.map(r=>v(r,t)).join(" | ")}}function qe(e,t){let n=k(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=qe(o,t);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)r.add(a)}return r}}}function Et(e,t){let n=qe(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 Nn(e,t,n){let r=qe(e,n),o=qe(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 Sn(e,t){let n=k(e,t);if(!n||q(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(a=>Sn(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 Tt(e,t,n){if(!e||!t)return null;let r=z(e,t,n);if(r===!0)return!0;let o=z(t,e,n);if(o===!0)return!0;let i=Nn(e,t,n);return i!==null?i:r===!1&&o===!1?!1:null}function kt(e,t,n){let r=k(e,n),o=k(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=!1;for(let a of o.types){if(q(a))continue;let s=kt(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=kt(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=z(i.typeExpr,a.typeExpr,n);if(s!==!0)return s}return!0}function vn(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>vn(o,t));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"}function xn(e,t){let n=k(e,t);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>xn(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 Yr(e,t){let n=new Map(e);return n.set("$item",t),n}function bn(e){let t=ze(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 ze(e){if(e.kind==="literal"&&e.literalType==="number"&&typeof e.value=="number")return e.value;if(e.kind==="unary"&&e.operator==="-"){let t=ze(e.operand);return typeof t=="number"?-t:void 0}}function Qr(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"?te(o,i.name,t):we(o,t)}return o}function Jr(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 bt=class{ctx=kn();symbols=null;validate(t){return this.ctx=kn(),this.symbols=$e(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(Zt("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=Ge(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=Qr(t.path,this.symbols);if(!o||!r)return;(t.op==="merge"?kt(r,o,this.symbols):z(r,o,this.symbols))===!1&&this.error(`Patch value for '${Jr(t.path)}' must be assignable to ${v(o,this.symbols)}, got ${v(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"),Wr.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,T("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,T("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",t.right.location),t.right.location,`Operator '${t.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,T("boolean",t.left.location),t.left.location,`Operator '${t.operator}' requires a boolean left operand`),this.requireAssignable(a,T("boolean",t.right.location),t.right.location,`Operator '${t.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,T("number",t.left.location),t.left.location,`Operator '${t.operator}' requires a numeric left operand`),this.requireAssignable(a,T("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,T(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,T("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=U(c,this.symbols);d&&(l=Yr(r,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:r))}else for(let c of i)s.push(this.validateExpr(c,n,r));if(this.symbols)switch(o){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],T("boolean",l.location),l.location,`Function '${o}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],T("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=ze(i[1]),l=ze(i[2]);typeof c=="number"&&typeof l=="number"&&c>l&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,`Function '${o}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],T("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],T("number",i[2].location),i[2].location,`Function '${o}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,o),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,`Function '${o}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,o);break;case"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],T("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}Nn(r,o,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(r,this.symbols)} and ${v(o,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(t,n){return this.symbols?m(t,n,this.symbols):null}requireAssignable(t,n,r,o){if(!this.symbols||!t)return;z(t,n,this.symbols)===!1&&this.error(`${o}, got ${v(t,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(t,n,r){if(!this.symbols||!t)return;vn(t,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(t,n){if(!this.symbols||!t)return;xn(t,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireSpreadOperand(t,n,r,o=new Map){if(!this.symbols)return;let i=t===null?"unknown":Ue(t,this.symbols);(G(r,{env:o,symbols:this.symbols,inferExprType:m,resolveType:k})?"invalid":i)==="invalid"&&this.error(`Object spread operands must be object-shaped or T | null where T is object-shaped, got ${v(t,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(t,n){if(!this.symbols)return;let r=t.map(o=>Sn(o,this.symbols)).filter(o=>o!==null);for(let o=0;o<r.length;o+=1)for(let i=o+1;i<r.length;i+=1)if(Tt(r[o],r[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(r[o],this.symbols)} and ${v(r[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(t,n,r,o){if(!this.symbols||t.length<3)return;let i=n[0],a=Et(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(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[p,f]=d.elements,h=bn(p);if(h==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let $=`${typeof h}:${String(h)}`;s.has($)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(h)}`,p.location,"E051"):s.add($)}let A=this.inferType(p,o),S=Et(A,this.symbols);(S==="invalid"||a!==null&&S!==null&&a!==S)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${v(i,this.symbols)} and ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(f,o))}c.push(n[n.length-1]);for(let l=0;l<c.length;l+=1)for(let d=l+1;d<c.length;d+=1)if(Tt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(t,n,r,o){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=bn(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[p,f,h]=d.elements,A=this.inferType(p,o),S=Et(A,this.symbols);S==="invalid"?this.error(`Function '${t}' requires labels with exactly one primitive scalar type, got ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=S:S!==null&&S!==c&&this.error(`Function '${t}' candidate labels must share one primitive scalar type, got ${c} and ${S}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(f,o),T("boolean",f.location),f.location,`Function '${t}' expects a boolean eligible value`),this.requireAssignable(this.inferType(h,o),T("number",h.location),h.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(Tt(s[l],s[d],this.symbols)===!1){this.error(`Function '${t}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}error(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 An(e){let n=new bt().validate(e),r=gn(e),o=[...n.diagnostics,...r];return{valid:!o.some(i=>i.severity==="error"),diagnostics:o}}var Nt={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},St={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},vt={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},xt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Xr={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var _=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 Ve(e,t,n){return new _("INVALID_KIND_FOR_CONTEXT",`Node kind '${e}' is not allowed in ${t} context`,{path:n,details:{kind:e,context:t}})}function g(e,t){return new _("UNKNOWN_CALL_FN",`Unknown function '${e}' in call expression`,{path:t,details:{fn:e}})}function He(e,t){return new _("INVALID_SYS_PATH",`System path '${e.join(".")}' is not allowed in Translator path`,{path:t,details:{sysPath:e}})}function At(e,t){return new _("UNSUPPORTED_BASE",`Unsupported base expression kind '${e}'. Only var(item) is supported.`,{path:t,details:{baseKind:e}})}function Zr(e,t){return new _("INVALID_SHAPE",`Invalid node shape: ${e}`,{path:t,details:{description:e}})}function wt(e,t){return new _("UNKNOWN_NODE_KIND",`Unknown expression node kind '${e}'`,{path:t,details:{kind:e}})}function eo(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 wn(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>{let r=eo(t.item.key,n.item.key);return r!==0?r:t.index-n.index}).map(({item:t})=>t)}function u(e,t){switch(e.kind){case"lit":return to(e);case"var":return no(e,t);case"sys":return ro(e,t);case"get":return oo(e,t);case"field":return Cn(e,t);case"call":return io(e,t);case"obj":return ao(e,t);case"arr":return so(e,t);default:throw wt(e.kind)}}function to(e){return{kind:"lit",value:e.value}}function no(e,t){if(!t.allowItem)throw Ve("var",t.mode);return{kind:"get",path:"$item"}}function ro(e,t){if(e.path.length===0)throw He(e.path);let n=e.path[0];if(!(t.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw He(e.path);return{kind:"get",path:e.path.join(".")}}function oo(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 Ve("var",t.mode);return{kind:"get",path:`$item.${n}`}}throw At(e.base.kind)}function Cn(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:u(e.object,t),property:e.property}}function io(e,t){let{fn:n,args:r}=e;if(n==="absDiff"){if(r.length!==2)throw g(n);return{kind:"abs",arg:{kind:"sub",left:u(r[0],t),right:u(r[1],t)}}}if(n==="clamp"){if(r.length!==3)throw g(n);return{kind:"min",args:[{kind:"max",args:[u(r[0],t),u(r[1],t)]},u(r[2],t)]}}if(n==="idiv"){if(r.length!==2)throw g(n);return{kind:"floor",arg:{kind:"div",left:u(r[0],t),right:u(r[1],t)}}}if(n==="streak"){if(r.length!==2)throw g(n);return{kind:"if",cond:u(r[1],t),then:{kind:"add",left:u(r[0],t),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return co(r,t);if(n==="argmax"||n==="argmin")return lo(n,r,t);if(ho(n)){if(r.length!==2)throw g(n);let[o,i]=r;return{kind:n,left:u(o,t),right:u(i,t)}}if(n==="isNotNull"){if(r.length!==1)throw g(n);return{kind:"not",arg:{kind:"isNull",arg:u(r[0],t)}}}if(Pn(n)){if(r.length!==1)throw g(n);return{kind:yo(n),arg:u(r[0],t)}}if(n==="trim"){if(r.length!==1)throw g(n);return{kind:"trim",str:u(r[0],t)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw g(n);return{kind:"toLowerCase",str:u(r[0],t)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw g(n);return{kind:"toUpperCase",str:u(r[0],t)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw g(n);return{kind:"strLen",str:u(r[0],t)}}if(go(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(r[0],t)}:{kind:n,args:r.map(o=>u(o,t))};if(n==="sum"){if(r.length!==1)throw g(n);return{kind:"sumArray",array:u(r[0],t)}}if(n==="pow"){if(r.length!==2)throw g(n);return{kind:"pow",base:u(r[0],t),exponent:u(r[1],t)}}if(Eo(n))return{kind:n,args:r.map(o=>u(o,t))};if(n==="if"||n==="cond"){if(r.length!==3)throw g(n);return{kind:"if",cond:u(r[0],t),then:u(r[1],t),else:u(r[2],t)}}if(n==="field"){if(r.length!==2)throw g(n);let o=u(r[0],t),i=r[1];if(i.kind!=="lit"||typeof i.value!="string")throw g(n);return Cn({kind:"field",object:r[0],property:i.value},t)}if(To(n)){if(r.length!==1)throw g(n);return{kind:n,array:u(r[0],t)}}if(ko(n)){if(r.length!==1)throw g(n);return{kind:n,obj:u(r[0],t)}}if(n==="at"){if(r.length!==2)throw g(n);return{kind:"at",array:u(r[0],t),index:u(r[1],t)}}if(n==="includes"){if(r.length!==2)throw g(n);return{kind:"includes",array:u(r[0],t),item:u(r[1],t)}}if(bo(n)){if(r.length!==2)throw g(n);let o={...t,allowItem:!0};return n==="map"?{kind:"map",array:u(r[0],t),mapper:u(r[1],o)}:{kind:n,array:u(r[0],t),predicate:u(r[1],o)}}if(n==="slice"){if(r.length<2||r.length>3)throw g(n);let o={kind:"slice",array:u(r[0],t),start:u(r[1],t)};return r.length===3&&(o.end=u(r[2],t)),o}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw g(n);let o={kind:"substring",str:u(r[0],t),start:u(r[1],t)};return r.length===3&&(o.end=u(r[2],t)),o}if(n==="append"){if(r.length<1)throw g(n);return{kind:"append",array:u(r[0],t),items:r.slice(1).map(o=>u(o,t))}}if(n==="merge")return{kind:"merge",objects:r.map(o=>u(o,t))};throw g(n)}function ao(e,t){let n={};for(let r of wn(e.fields))n[r.key]=u(r.value,t);return{kind:"object",fields:n}}function so(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=>u(o,t));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function co(e,t){if(e.length<3)throw g("match");let n=u(e[0],t),r=u(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 g("match");r={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],t)},then:u(i.elements[1],t),else:r}}return r}function lo(e,t,n){if(t.length<2)throw g(e);let r=t[t.length-1];if(r.kind!=="lit"||r.value!=="first"&&r.value!=="last")throw g(e);let o=t.slice(0,-1).map(i=>po(i,n,e));if(o.length===0)throw g(e);return uo(e,o,r.value)}function po(e,t,n){if(e.kind!=="arr"||e.elements.length!==3)throw g(n);return{label:u(e.elements[0],t),eligible:u(e.elements[1],t),score:u(e.elements[2],t)}}function uo(e,t,n){let r={kind:"lit",value:null};for(let o=t.length-1;o>=0;o-=1)r={kind:"if",cond:fo(e,t,n,o),then:t[o].label,else:r};return r}function fo(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:mo(e,n,r,a),left:o.score,right:s.score}]})}return i.length===0?o.eligible:{kind:"and",args:[o.eligible,...i]}}function mo(e,t,n,r){let o=t==="first"?n<r:n>r;return e==="argmax"?o?"gte":"gt":o?"lte":"lt"}function ho(e){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(e)}function Pn(e){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(e)}function yo(e){if(e==="isNotNull")throw g(e);if(!Pn(e))throw g(e);return e}function go(e){return e==="min"||e==="max"}function Eo(e){return["and","or","concat","coalesce"].includes(e)}function To(e){return["first","last"].includes(e)}function ko(e){return["keys","values","entries"].includes(e)}function bo(e){return["filter","find","every","some","map"].includes(e)}function No(e,t){return e.map(n=>So(n,t))}function So(e,t){let n=e.condition?u(e.condition,Ke(t,"action")):void 0,r=vo(e.op,t);return{fragmentId:e.fragmentId,condition:n,op:r,confidence:e.confidence}}function vo(e,t){switch(e.kind){case"addType":return{kind:"addType",typeName:e.typeName,typeExpr:ue(e.typeExpr)};case"addField":return{kind:"addField",typeName:e.typeName,field:{name:e.field.name,type:ue(e.field.type),optional:e.field.optional,defaultValue:e.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:e.path,typeExpr:ue(e.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:e.path,value:e.value};case"addConstraint":return{kind:"addConstraint",targetPath:e.targetPath,rule:u(e.rule,Ke(t,"schema")),message:e.message};case"addComputed":return{kind:"addComputed",name:e.name,expr:u(e.expr,Ke(t,"schema")),deps:e.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:e.actionName,expr:u(e.expr,Ke(t,"schema"))}}}function ue(e){switch(e.kind){case"primitive":return{kind:"primitive",name:e.name};case"array":return{kind:"array",element:ue(e.element)};case"object":return{kind:"object",fields:e.fields.map(t=>({name:t.name,type:ue(t.type),optional:t.optional}))};case"union":return{kind:"union",members:e.members.map(ue)};case"literal":return{kind:"literal",value:e.value};case"ref":return{kind:"ref",name:e.name}}}function Ke(e,t){return{mode:t,allowSysPaths:e.allowSysPaths,fnTableVersion:e.fnTableVersion,actionName:e.actionName,allowItem:!1}}function xo(e,t){return e.map(n=>We(n,t))}function We(e,t){let n=e.condition?u(e.condition,t):void 0,r=e.value?u(e.value,t):void 0;return{condition:n,op:e.op,path:Ao(e.path,t),value:r}}function Ao(e,t){return e.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,t)})}function C(e,t={}){switch(e.kind){case"literal":return{kind:"lit",value:Io(e.value,e.literalType)};case"identifier":return t.resolveIdentifier?.(e.name)??V(e.name);case"systemIdent":return Co(e,t);case"iterationVar":return{kind:"var",name:e.name};case"propertyAccess":return Po(e.object,e.property,t);case"indexAccess":return{kind:"call",fn:"at",args:[C(e.object,t),C(e.index,t)]};case"functionCall":return{kind:"call",fn:e.name,args:e.args.map(n=>C(n,t))};case"unary":return{kind:"call",fn:e.operator==="!"?"not":"neg",args:[C(e.operand,t)]};case"binary":return{kind:"call",fn:Mo(e.operator),args:[C(e.left,t),C(e.right,t)]};case"ternary":return{kind:"call",fn:"cond",args:[C(e.condition,t),C(e.consequent,t),C(e.alternate,t)]};case"objectLiteral":return wo(e,t);case"arrayLiteral":return{kind:"arr",elements:e.elements.map(n=>C(n,t))}}}function wo(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:C(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:C(a.value,t)});continue}i(),r.push(C(a.expr,t))}return i(),{kind:"call",fn:"merge",args:r}}function V(...e){return{kind:"get",path:In(...e)}}function Ct(e,...t){return{kind:"get",base:e,path:In(...t)}}function Ce(...e){return{kind:"sys",path:e}}function Ye(e){return{kind:"obj",fields:Object.entries(e).map(([t,n])=>({key:t,value:n}))}}function In(...e){return e.map(t=>({kind:"prop",name:t}))}function Co(e,t){return t.resolveSystemIdent?.(e.path)??Ce(...e.path)}function Po(e,t,n){let r=C(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"?Ct(r,t):{kind:"field",object:r,property:t}}function Io(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 Mo(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 Fo,semanticPathToPatchPath as _o,sha256Sync as $o}from"@manifesto-ai/core";var Do=new Set(["findById","existsById","updateById","removeById"]);function Mn(e){return{...e,computed:{fields:Object.fromEntries(Object.entries(e.computed.fields).map(([t,n])=>[t,Oo(n)]))},actions:Object.fromEntries(Object.entries(e.actions).map(([t,n])=>[t,Lo(n)]))}}function Oo(e){return{...e,expr:Dn(e.expr)}}function Lo(e){return{...e,flow:Qe(e.flow),available:e.available?Dn(e.available):void 0,dispatchable:e.dispatchable?Ro(e.dispatchable):void 0}}function Qe(e){switch(e.kind){case"seq":return{kind:"seq",steps:e.steps.map(t=>Qe(t))};case"if":return{kind:"if",cond:Pt(e.cond),then:Qe(e.then),else:e.else?Qe(e.else):void 0};case"patch":return{kind:"patch",op:e.op,path:e.path,value:e.value?Pt(e.value):void 0};case"effect":return{kind:"effect",type:e.type,params:Object.fromEntries(Object.entries(e.params).map(([t,n])=>[t,jo(n)]))};case"fail":return{kind:"fail",code:e.code,message:e.message?Pt(e.message):void 0};case"call":case"halt":return e}}function Dn(e){return u(L(e),Nt)}function Pt(e){return u(L(e),St)}function Ro(e){return u(L(e),vt)}function jo(e){return u(L(e),xt)}function L(e){switch(e.kind){case"lit":case"var":return e;case"sys":return e.path[0]==="system"?V("$system",...e.path.slice(1)):e;case"get":return{kind:"get",...e.base?{base:L(e.base)}:void 0,path:e.path};case"field":return{kind:"field",object:L(e.object),property:e.property};case"obj":return{kind:"obj",fields:e.fields.map(t=>({key:t.key,value:L(t.value)}))};case"arr":return{kind:"arr",elements:e.elements.map(t=>L(t))};case"call":return Do.has(e.fn)?L(On(e.fn,e.args)):{kind:"call",fn:e.fn,args:e.args.map(t=>L(t))}}}function On(e,t){let[n,r,o]=t,i=L(n),a=r?L(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=Ct(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:[On("findById",t)]}]};case"updateById":{let l=o?L(o):Ye({});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=>L(l))}}}function Go(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 Bo(e){let t=Go(e.domain.name);Uo(e.domain,t);let n=qo(e.domain,t),r=zo(e.domain,t),o=Yo(e.domain,t),i=ei(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=ui(a);return{schema:{...a,hash:s},diagnostics:t.diagnostics}}function Ln(e){let t=Bo(e);return t.schema?{schema:Mn(t.schema),diagnostics:t.diagnostics}:{schema:null,diagnostics:t.diagnostics}}function Uo(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 qo(e,t){let n={};for(let r of e.types){let o=Q(r.typeExpr);t.typeDefinitions.set(r.name,o),n[r.name]={name:r.name,definition:o}}return n}function Q(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:Q(e.elementType)};case"recordType":return{kind:"record",key:Q(e.keyType),value:Q(e.valueType)};case"objectType":let t={};for(let r of e.fields)t[r.name]={type:Q(r.typeExpr),optional:r.optional};return{kind:"object",fields:t};case"unionType":return{kind:"union",types:e.types.map(Q)};case"literalType":return{kind:"literal",value:e.value};default:let n=e;throw new Error(`Unknown type expression kind: ${e.kind}`)}}function zo(e,t){let n={},r={};for(let o of e.members)if(o.kind==="state")for(let i of o.fields){let a=Q(i.typeExpr);r[i.name]=a,t.stateFieldTypes.set(i.name,a);let s=re(i.typeExpr,t);s&&t.stateFieldSpecs.set(i.name,s);let c=Vo(i,t);c&&(n[i.name]=c)}return{fields:n,fieldTypes:r}}function Vo(e,t){let n=re(e.typeExpr,t);if(!n)return null;let r=e.initializer?Me(e.initializer,t):void 0;return r!==void 0&&Ie(r,Q(e.typeExpr),e.name,e.location,t),{...n,required:!0,default:r}}function re(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)?(It(t,"E044",`Recursive type '${e.name}' cannot be lowered to FieldSpec in a schema position`,e.location),null):re(r.typeExpr,t,[...n,e.name]):{type:"object",required:!0}}}case"unionType":{let r=e.types.filter(s=>!Ho(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?re(r[0],t,n):(It(t,"E043",`Union type '${fe(e)}' cannot be soundly lowered to FieldSpec`,e.location),null)}case"arrayType":{let r=re(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=re(o.typeExpr,t,n);if(!i)return null;r[o.name]={...i,required:!o.optional}}return{type:"object",required:!0,fields:r}}}}function Rn(e,t,n=[]){if(e.kind!=="simpleType")return e;let r=t.typeDefs.get(e.name);return r?n.includes(e.name)?null:Rn(r.typeExpr,t,[...n,e.name]):e}function Ho(e,t,n=[]){let r=Rn(e,t,n);return r?.kind==="simpleType"&&r.name==="null"||r?.kind==="literalType"&&r.value===null}function It(e,t,n,r){e.diagnostics.push({severity:"error",code:t,message:n,location:r})}function fe(e){switch(e.kind){case"simpleType":return e.name;case"unionType":return e.types.map(t=>fe(t)).join(" | ");case"arrayType":return`Array<${fe(e.elementType)}>`;case"recordType":return`Record<${fe(e.keyType)}, ${fe(e.valueType)}>`;case"literalType":return JSON.stringify(e.value);case"objectType":return`{ ${e.fields.map(t=>`${t.name}${t.optional?"?":""}: ${fe(t.typeExpr)}`).join("; ")} }`}}function oe(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?oe(r,t,[...n,e.name]):null}function Ko(e){return e?.kind==="primitive"&&e.type==="null"||e?.kind==="literal"&&e.value===null}function jn(e,t){let n=oe(e,t);if(!n||n.kind!=="union")return null;let r=n.types.filter(o=>{let i=oe(o,t);return!Ko(i)});return r.length===1?r[0]:null}function Wo(e,t,n){if(t===null||Array.isArray(t)||typeof t!="object")return e;let r=jn(e,n);return r&&oe(r,n)?.kind==="object"?r:e}function J(e){switch(e.kind){case"primitive":return e.type;case"array":return`Array<${J(e.element)}>`;case"record":return`Record<${J(e.key)}, ${J(e.value)}>`;case"object":return`{ ${Object.entries(e.fields).map(([t,n])=>`${t}${n.optional?"?":""}: ${J(n.type)}`).join("; ")} }`;case"union":return e.types.map(t=>J(t)).join(" | ");case"literal":return JSON.stringify(e.value);case"ref":return e.name}}function Pe(e,t,n){let r=oe(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=>Pe(o,r.element,n));case"record":return e!==null&&!Array.isArray(e)&&typeof e=="object"&&Object.values(e).every(o=>Pe(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(!Pe(e[o],i.type,n))return!1}return!0;case"union":return r.types.some(o=>Pe(e,o,n));case"ref":return!1}}function Ie(e,t,n,r,o){if(e===void 0)return;let i=oe(t,o);if(!i){o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${J(t)}, got ${JSON.stringify(e)}`,location:r});return}if(i.kind==="union"){if(Pe(e,i,o))return;o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${J(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&&ne(o,n,"null",a,r);return;case"string":case"number":case"boolean":typeof e!==i.type&&ne(o,n,i.type,a,r);return;case"object":(e===null||Array.isArray(e)||typeof e!="object")&&ne(o,n,"object",a,r);return;case"array":Array.isArray(e)||ne(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)){ne(o,n,"array",e===null?"null":typeof e=="object"?"object":typeof e,r);return}for(let a=0;a<e.length;a+=1)Ie(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;ne(o,n,"object",a,r);return}for(let[a,s]of Object.entries(e))Ie(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;ne(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 ${J(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}Ie(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 ${J(t)}, got ${JSON.stringify(e)}`,location:r});return}}function ne(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 Me(e,t){switch(e.kind){case"literal":return e.value;case"arrayLiteral":return e.elements.map(n=>Me(n,t));case"objectLiteral":{let n={};for(let r of e.properties){if(r.kind==="objectProperty"){n[r.key]=Me(r.value,t);continue}let o=Me(r.expr,t);o!==null&&!Array.isArray(o)&&typeof o=="object"&&Object.assign(n,o)}return n}default:return}}function Yo(e,t){let n=[],r=0;for(let i of e.members)if(i.kind==="computed"){let a=H(i.expression,t),s=Zo(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:r}),r+=1}let o={};for(let i of Qo(n,t))o[i.name]={deps:i.deps,expr:i.expr};return{fields:o}}function Qo(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&&Jo(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=Xo(l[0].name,r),p=d?d.join(" -> "):l.map(f=>f.name).join(", ");return It(t,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...e]}return s}function Jo(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 Xo(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 Zo(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 ei(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 p of r.params)o.add(p.name);t.actionParams.set(r.name,o);let i=r.params.map(p=>p.name),a=Fn(r.body,t),s,c;if(r.params.length>0){let p={},f={};for(let h of r.params){let A=re(h.typeExpr,t);A&&(p[h.name]=structuredClone(A),f[h.name]={type:Q(h.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:f}}let l;r.available&&(l=H(r.available,t));let d;r.dispatchable&&(d=H(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 Fn(e,t){return e.length===0?{kind:"seq",steps:[]}:e.length===1?Xe(e[0],t):{kind:"seq",steps:e.map(n=>Xe(n,t))}}function Xe(e,t){switch(e.kind){case"when":return ti(e,t);case"once":return ni(e,t);case"onceIntent":return ri(e,t);case"patch":return oi(e,t);case"effect":return ii(e,t);case"fail":return si(e,t);case"stop":return ci(e,t);case"include":return{kind:"seq",steps:[]}}}function ti(e,t){let n=H(e.condition,t),r=Fn(e.body,t);return{kind:"if",cond:n,then:r}}function ni(e,t){let n=Mt(e.marker,t),r=Ce("meta","intentId"),o=Ze("neq",[V(..._n(n)),r]);if(e.condition){let s=H(e.condition,t);o=Ze("and",[o,s])}let i={kind:"patch",op:"set",path:Dt(n),value:r},a=e.body.map(s=>Xe(s,t));return{kind:"if",cond:o,then:{kind:"seq",steps:[i,...a]}}}function ri(e,t){let n=t.currentAction??"unknown",r=t.onceIntentCounters.get(n)??0;t.onceIntentCounters.set(n,r+1);let o=$o(`${n}:${r}:intent`),i=`$mel.guards.intent.${o}`,a=Ce("meta","intentId"),s=Ze("neq",[V(..._n(i)),a]);if(e.condition){let d=H(e.condition,t);s=Ze("and",[s,d])}let c={kind:"patch",op:"merge",path:Dt("$mel.guards.intent"),value:Ye({[o]:a})},l=e.body.map(d=>Xe(d,t));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function oi(e,t){let n=Mt(e.path,t),r={kind:"patch",op:e.op,path:Dt(n)};if(e.value){let o=H(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],p=s?oe(s,t):null;if(!p){s=null;break}if(p.kind==="union"){let f=jn(s,t);if(!f){s=null;break}s=f,l-=1;continue}if(d.kind==="propertySegment"&&p.kind==="object"&&p.fields[d.name])s=p.fields[d.name].type;else if(d.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(d.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let l=ai(e.value,t);if(l!==void 0){let d=e.path.segments.map(f=>f.kind==="propertySegment"?f.name:"[*]").join("."),p=Wo(s,l,t);Ie(l,p,d,e.location,t)}}}}}}return r}function ii(e,t){let n={};for(let r of e.args)r.isPath?n[r.name]={kind:"lit",value:Mt(r.value,t)}:n[r.name]=H(r.value,t);return{kind:"effect",type:e.effectType,params:n}}function ai(e,t){return Me(e,t)}function si(e,t){let n={kind:"fail",code:e.code};return e.message&&(n.message=H(e.message,t)),n}function ci(e,t){return{kind:"halt",reason:e.reason}}function li(e){return e.replaceAll("\\","\\\\").replaceAll(".","\\.")}function Je(...e){return e.map(li).join(".")}function Mt(e,t){let n=[];for(let o of e.segments)if(o.kind==="propertySegment")n.push(o.name);else{let i=H(o.index,t);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let r=n[0];return t.stateFields.has(r)?Je(...n):t.computedFields.has(r)?Je(...n):t.currentAction&&t.actionParams.get(t.currentAction)?.has(r)?`input.${Je(...n)}`:Je(...n)}function Dt(e){return _o(e)}function Ze(e,t){return{kind:"call",fn:e,args:t}}function _n(e){return e.split(/(?<!\\)\./g).map(t=>t.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function H(e,t,n={}){return C(e,{resolveIdentifier:r=>di(r,t,n),resolveSystemIdent:r=>pi(r,t)})}function di(e,t,n={}){return n.preferActionParams&&t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?V("input",e):t.stateFields.has(e)||t.computedFields.has(e)?V(e):t.currentAction&&t.actionParams.get(t.currentAction)?.has(e)?V("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}}}),V(e))}function pi(e,t){let[n,...r]=e;switch(n){case"system":case"meta":case"input":return Ce(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 ui(e){return Fo(e)}var fi="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",mi="Action-parameter annotations are not part of the current MEL syntax.",Ot="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",$n="Annotation payload nesting exceeds the current MEL limit of 2 levels.",hi="Annotation target does not map to the emitted DomainSchema.",Gn=2;function Bn(e,t){let n=[],r=new Map,o=e.domain;me(o.annotations,`domain:${o.name}`,n,r);for(let a of o.types)me(a.annotations,`type:${a.name}`,n,r),he(a.typeExpr,a.name,0,n,r);for(let a of o.members)switch(a.kind){case"state":for(let s of a.fields)me(s.annotations,`state_field:${s.name}`,n,r),ie(s.typeExpr,n);break;case"computed":me(a.annotations,`computed:${a.name}`,n,r);break;case"action":me(a.annotations,`action:${a.name}`,n,r),yi(a,n);for(let s of a.params)ie(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...r.keys()].sort()){if(!Ti(t,a)){n.push(M("E057",hi,ki(e,a)??o.location));continue}let s=r.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>Ei(c))))}return{annotations:Object.freeze({schemaHash:t.hash,entries:Object.freeze(i)}),diagnostics:n}}function me(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}:Lt(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 he(e,t,n,r,o){switch(e.kind){case"objectType":for(let i of e.fields)i.annotations?.length&&(n===0?me(i.annotations,`type_field:${t}.${i.name}`,r,o):Un(i.annotations,r)),he(i.typeExpr,t,n+1,r,o);return;case"arrayType":he(e.elementType,t,n,r,o);return;case"recordType":he(e.keyType,t,n,r,o),he(e.valueType,t,n,r,o);return;case"unionType":for(let i of e.types)he(i,t,n,r,o);return;case"simpleType":case"literalType":return}}function ie(e,t){switch(e.kind){case"objectType":for(let n of e.fields)Un(n.annotations,t),ie(n.typeExpr,t);return;case"arrayType":ie(e.elementType,t);return;case"recordType":ie(e.keyType,t),ie(e.valueType,t);return;case"unionType":for(let n of e.types)ie(n,t);return;case"simpleType":case"literalType":return}}function yi(e,t){for(let n of e.params)gi(n,t)}function gi(e,t){if(e.annotations)for(let n of e.annotations)t.push(M("E054",mi,n.location))}function Un(e,t){if(e)for(let n of e)t.push(M("E053",fi,n.location))}function Lt(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(M("E055",Ot,e.location)),{ok:!1});case"arrayLiteral":{if(t+1>Gn)return n.push(M("E056",$n,e.location)),{ok:!1};let r=[];for(let o of e.elements){let i=Lt(o,t+1,n);if(!i.ok)return{ok:!1};r.push(i.value)}return{ok:!0,value:r}}case"objectLiteral":{if(t+1>Gn)return n.push(M("E056",$n,e.location)),{ok:!1};let r={};for(let o of e.properties){if(o.kind!=="objectProperty")return n.push(M("E055",Ot,o.location)),{ok:!1};let i=Lt(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(M("E055",Ot,e.location)),{ok:!1}}}function Ei(e){return e.payload===void 0?Object.freeze({tag:e.tag}):Object.freeze({tag:e.tag,payload:Rt(e.payload)})}function Rt(e){if(Array.isArray(e))return Object.freeze(e.map(t=>Rt(t)));if(e!==null&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))t[n]=Rt(r);return Object.freeze(t)}return e}function Ti(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 ki(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 jt=16;function b(e){return structuredClone(e)}function I(e,t,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;t.has(i)||(t.add(i),e.push(M(n,r,o)))}function bi(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 Ni(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function Si(e){let t=new Map;for(let n of e.params)t.set(n.name,n.typeExpr);return t}function vi(e,t,n,r){let o=new Map;for(let i of t.flows.values()){o.set(i.name,[]),t.actionNames.has(i.name)&&I(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))&&I(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=Ni(i);for(let s of i.body)Ai(s,i.name,a,t,n,r,o.get(i.name))}for(let i of e.members)if(i.kind==="action"){let a=Si(i);for(let s of i.body)xi(s,a,t,n,r)}return o}function xi(e,t,n,r,o){switch(e.kind){case"include":tt(e,t,n,r,o);break;case"when":for(let i of e.body)Ee(i,t,n,r,o);break;case"once":for(let i of e.body)Ee(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Ee(i,t,n,r,o);break;case"fail":case"stop":break}}function Ee(e,t,n,r,o){switch(e.kind){case"include":I(r,o,"E016","include is only allowed at action or flow body top-level.",e.location),tt(e,t,n,r,o);break;case"when":for(let i of e.body)Ee(i,t,n,r,o);break;case"once":for(let i of e.body)Ee(i,t,n,r,o);break;case"onceIntent":for(let i of e.body)Ee(i,t,n,r,o);break;case"patch":case"effect":case"fail":case"stop":break}}function Ai(e,t,n,r,o,i,a){switch(e.kind){case"include":tt(e,n,r,o,i)&&a.push({target:e.flowName,location:e.location});break;case"when":for(let s of e.body)et(s,t,n,r,o,i);break;case"once":I(o,i,"E017","once() is not allowed in flow bodies.",e.location);break;case"onceIntent":I(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);break;case"patch":I(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":I(o,i,"E020","effect is not allowed in flow bodies.",e.location);break}}function et(e,t,n,r,o,i){switch(e.kind){case"include":I(o,i,"E016","include is only allowed at action or flow body top-level.",e.location),tt(e,n,r,o,i);break;case"when":for(let a of e.body)et(a,t,n,r,o,i);break;case"once":I(o,i,"E017","once() is not allowed in flow bodies.",e.location);for(let a of e.body)et(a,t,n,r,o,i);break;case"onceIntent":I(o,i,"E018","onceIntent is not allowed in flow bodies.",e.location);for(let a of e.body)et(a,t,n,r,o,i);break;case"patch":I(o,i,"E019","patch is not allowed in flow bodies.",e.location);break;case"effect":I(o,i,"E020","effect is not allowed in flow bodies.",e.location);break;case"fail":case"stop":break}}function tt(e,t,n,r,o){let i=n.flows.get(e.flowName);if(!i)return I(r,o,"E015",`'${e.flowName}' is not a declared flow.`,e.location),!1;if(e.args.length!==i.params.length)return I(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=ye(s,t,n);if(!l)continue;ge(l,c.typeExpr,n)===!1&&I(r,o,"E024",`include '${e.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function wi(e,t,n,r){function o(i,a,s){s.add(i);for(let c of e.get(i)??[]){if(a+1>jt){I(n,r,"E014",`Include expansion depth exceeds limit (${jt}).`,c.location);continue}if(s.has(c.target)){I(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 D(e,t){switch(e.kind){case"identifier":return t.has(e.name)?b(t.get(e.name)):b(e);case"systemIdent":case"literal":case"iterationVar":return b(e);case"functionCall":return{...b(e),args:e.args.map(n=>D(n,t))};case"binary":return{...b(e),left:D(e.left,t),right:D(e.right,t)};case"unary":return{...b(e),operand:D(e.operand,t)};case"ternary":return{...b(e),condition:D(e.condition,t),consequent:D(e.consequent,t),alternate:D(e.alternate,t)};case"propertyAccess":return{...b(e),object:D(e.object,t)};case"indexAccess":return{...b(e),object:D(e.object,t),index:D(e.index,t)};case"objectLiteral":return{...b(e),properties:e.properties.map(n=>({...b(n),...n.kind==="objectProperty"?{value:D(n.value,t)}:{expr:D(n.expr,t)}}))};case"arrayLiteral":return{...b(e),elements:e.elements.map(n=>D(n,t))}}}function Ci(e,t){switch(e.kind){case"when":return[qn(e,t)];case"fail":return[{...b(e),message:e.message?D(e.message,t):void 0}];case"stop":return[b(e)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function qn(e,t){return{...b(e),condition:D(e.condition,t),body:e.body.flatMap(n=>Ci(n,t))}}function Pi(e,t,n){let r=new Map;for(let o=0;o<e.params.length;o+=1)r.set(e.params[o].name,D(t.args[o],n));return r}function Ii(e,t,n,r,o){switch(e.kind){case"when":return[qn(e,n)];case"include":return zn(e,t,n,r,o);case"once":case"onceIntent":case"patch":case"effect":return[]}}function zn(e,t,n,r,o){let i=t.flows.get(e.flowName);if(!i||e.args.length!==i.params.length||r>jt||o.includes(e.flowName))return[];let a=Pi(i,e,n),s=[...o,e.flowName];return i.body.flatMap(c=>Ii(c,t,a,r+1,s))}function Te(e){switch(e.kind){case"when":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"once":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"onceIntent":return[{...b(e),body:e.body.flatMap(t=>Te(t))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[b(e)]}}function Mi(e,t,n){switch(e.kind){case"include":return zn(e,t,new Map,n,[]);case"when":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"once":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"onceIntent":return[{...b(e),body:e.body.flatMap(r=>Te(r))}];case"fail":case"stop":return[b(e)]}}function Di(e,t){let n=[];for(let r of e.domain.members)switch(r.kind){case"state":case"computed":n.push(b(r));break;case"action":n.push({...b(r),body:r.body.flatMap(o=>Mi(o,t,1))});break;case"flow":break}return{...b(e),domain:{...b(e.domain),types:e.domain.types.map(r=>b(r)),members:n}}}function ye(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=ye(e.object,t,n);return Vn(r,e.property,n)}case"indexAccess":{let r=ye(e.object,t,n);return Hn(r,n)}case"objectLiteral":return Fe(e,t,n,ye,ae);case"arrayLiteral":{if(e.elements.length===0)return null;let r=ye(e.elements[0],t,n);return r?{kind:"arrayType",elementType:r,location:e.location}:null}case"functionCall":return e.name==="merge"?_e(e,t,n,ye,ae):null;case"systemIdent":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function ae(e,t,n=new Set){return e?e.kind==="simpleType"&&t.typeDefs.has(e.name)?n.has(e.name)?null:(n.add(e.name),ae(t.typeDefs.get(e.name).typeExpr,t,n)):e:null}function Vn(e,t,n){let r=ae(e,n);if(!r)return null;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===t);return o?o.optional?Ft([o.typeExpr,{kind:"simpleType",name:"null",location:o.location}],o.location):o.typeExpr:null}if(r.kind==="unionType"){let o=r.types.filter(i=>!Kn(i)).map(i=>Vn(i,t,n)).filter(i=>i!==null);return Ft(o,r.location)}return null}function Hn(e,t){let n=ae(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=>!Kn(o)).map(o=>Hn(o,t)).filter(o=>o!==null);return Ft(r,n.location)}return null}function ge(e,t,n){let r=ae(e,n),o=ae(t,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=o.types.map(a=>ge(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=>ge(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:ge(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=ge(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:ge(r.valueType,o.valueType,n):null}function Kn(e){return e.kind==="simpleType"&&e.name==="null"||e.kind==="literalType"&&e.value===null}function Ft(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 Wn(e){let t=bi(e.domain),n=[],r=new Set,o=vi(e.domain,t,n,r);return wi(o,t,n,r),{program:Di(e,t),diagnostics:n}}var Oi=new Set(["$item","$index","$array"]);function Jn(e){let t=Object.keys(e.state.fields).filter(d=>!d.startsWith("$")),n=Li(e),r=new Set(n),o=new Set(t),i=Object.keys(e.actions),a=[...t.map(d=>({id:_t(d),kind:"state",name:d})),...n.map(d=>({id:$t(d),kind:"computed",name:d})),...i.map(d=>({id:Qn(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,f)=>{if(!d||!p)return;let h=`${d}|${f}|${p}`;s.has(h)||(s.add(h),c.push({from:d,to:p,relation:f}))};for(let d of n){let p=e.computed.fields[d];if(p)for(let f of p.deps)l(Yn(f,e,r,o),$t(d),"feeds")}for(let d of i){let p=e.actions[d],f=Qn(d);for(let h of Ri(p.flow,e))o.has(h)&&l(f,_t(h),"mutates");if(p.available)for(let h of nr(p.available))l(Yn(h,e,r,o),f,"unlocks")}return _i({nodes:a,edges:c})}function Li(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 nr(s.expr)){if(tr(c))return i.delete(o),n.set(o,!1),!1;let l=Xn(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 Ri(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=ji(o.path);a&&n.add(a);return}case"effect":{let a=Fi(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 ji(e){let[t]=e;return!t||t.kind!=="prop"||t.name.startsWith("$")?null:t.name}function Fi(e){return typeof e!="object"||e===null||e.kind!=="lit"||typeof e.value!="string"?null:Zn(e.value)}function Yn(e,t,n,r){let o=Xn(e,t.computed.fields);if(o!==null&&n.has(o))return $t(o);if(tr(e))return null;let i=Zn(e);return!i||!r.has(i)?null:_t(i)}function Xn(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 Zn(e){let t=er(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 er(e){return e.startsWith("/")?e.slice(1).replace(/\//g,"."):e}function tr(e){let t=er(e),n=t.startsWith("data.")?t.slice(5):t,o=/^([^.[\]]+)/.exec(n)?.[1]??"";return o.startsWith("$")?!Oi.has(o):!1}function nr(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 _t(e){return`state:${e}`}function $t(e){return`computed:${e}`}function Qn(e){return`action:${e}`}function _i(e){return Object.freeze({nodes:Object.freeze(e.nodes.map(t=>Object.freeze(t))),edges:Object.freeze([...e.edges].sort($i).map(t=>Object.freeze(t)))})}function $i(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)||e.relation.localeCompare(t.relation)}var Gi="Source-map target does not map to the emitted DomainSchema.",Bi="Source-map entry missing for emitted DomainSchema target.",Ui=new TextEncoder;function sr(e){return Object.freeze({coordinateUnit:"utf16",compilerVersion:e,emissionOptionsFingerprint:"default"})}function cr(e,t,n,r){let o=[],i=new Map,a=e.domain,s=Vi(t,r.coordinateUnit);i.set(`domain:${a.name}`,Ne({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,Ne({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),ke(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}`,Ne({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,Ne({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,Ne({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(!zi(n,l)){o.push(M("E058",Gi,rr(e,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of qi(e,n))Object.hasOwn(c,l)||o.push(M("E058",Bi,rr(e,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:ir(t),format:"manifesto/source-map-v1",coordinateUnit:r.coordinateUnit,emissionFingerprint:ir(`${r.coordinateUnit}\0${r.compilerVersion}\0${r.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:o}}function ke(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}`,Ne({target:{kind:"type_field",type:{name:t},field:{name:i.name}},span:o(i.location)})),ke(i.typeExpr,t,n+1,r,o);return;case"arrayType":ke(e.elementType,t,n+1,r,o);return;case"recordType":ke(e.keyType,t,n+1,r,o),ke(e.valueType,t,n+1,r,o);return;case"unionType":for(let i of e.types)ke(i,t,n+1,r,o);return;case"simpleType":case"literalType":return}}function qi(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 zi(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 rr(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?be(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 be(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=be(r.typeExpr,t,n+1);if(o)return o}return null;case"arrayType":return be(e.elementType,t,n+1);case"recordType":return be(e.keyType,t,n+1)??be(e.valueType,t,n+1);case"unionType":for(let r of e.types){let o=be(r,t,n+1);if(o)return o}return null;case"simpleType":case"literalType":return null}}function Vi(e,t){return t==="utf16"?n=>Hi(n):n=>Ki(n,e)}function Hi(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 Ki(e,t){return Object.freeze({start:or(e.start,t),end:or(e.end,t)})}function or(e,t){let n=ar(t.slice(0,e.offset)),r=e.offset-(e.column-1),o=ar(t.slice(0,r));return Object.freeze({line:e.line,column:n-o+1})}function Ne(e){return Object.freeze({target:Wi(e.target),span:Object.freeze({start:Object.freeze({...e.span.start}),end:Object.freeze({...e.span.end})})})}function Wi(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 ir(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 ar(e){return Ui.encode(e).length}import{sha256Sync as nt}from"@manifesto-ai/core";function lr(e){return e.kind==="literal"&&e.literalType==="boolean"&&e.value===!0}function Se(e){return C(e)}var rt=class{constructor(t){this.deps=t;this.exprValidator=new Bt(t.mapLocation)}conditionComposer=new Gt;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=De(l),p=this.collectPatchStatements(a.body,n,r,void 0).map(f=>({patch:f.patch,condition:this.conditionComposer.and(d,f.condition)}));i.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{patch:{kind:"patch",op:"unset",path:l,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=o,c=De(a.marker),l=a.marker,d=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch($){n.push({severity:"error",code:"E_LOWER",message:$.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(o,p);let f=nt(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let h={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:f,location:d}],location:d},A=De(h),S=this.collectPatchStatements(a.body,n,r,A);i.push({patch:{kind:"patch",op:"set",path:h,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},...S,{patch:{kind:"patch",op:"unset",path:h,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=De(c),d=nt(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let p=a.location,h={kind:"call",fn:"neq",args:[De({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:d,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{h=this.conditionComposer.and(h,this.deps.toMelExpr(a.condition))??h}catch(K){n.push({severity:"error",code:"E_LOWER",message:K.message,location:this.deps.mapLocation(a.condition.location)})}}let A=this.conditionComposer.and(o,h),S={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},$=this.collectPatchStatements(a.body,n,r,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:A},{patch:{kind:"patch",op:"merge",path:S,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},...$,{patch:{kind:"patch",op:"unset",path:c,location:p},condition: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 dr(e){return{op:e.patch.op,path:Yi(e.patch.path),...e.condition?{condition:e.condition}:void 0,...e.patch.value?{value:Se(e.patch.value)}:void 0}}function De(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,Se(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function Yi(e){return e.segments.map(t=>t.kind==="propertySegment"?{kind:"prop",name:t.name}:{kind:"expr",expr:Se(t.index)})}var Gt=class{and(t,n){return t?n?{kind:"call",fn:"and",args:[t,n]}:t:n}},Bt=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=B(t,new Map,this.symbols),a=B(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=m(t,new Map,this.symbols),i=G(t,{env:new Map,symbols:this.symbols,inferExprType:m,resolveType:k});!o&&!i||(i?"invalid":o?Ue(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 ur(e){let t=[],n=0;for(let r of e)t.push(n),n+=r.length+1;return t}function fr(e,t){return n=>mr(n,e,t)}function Ut(e,t,n){return e.map(r=>Qi(r,t,n))}function Qi(e,t,n){return{...e,location:mr(e.location,t,n)}}function mr(e,t,n){return{...e,start:pr(e.start,t,n),end:pr(e.end,t,n)}}function pr(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 Oe="__compileMelPatch",Xi="__patchDomain",Zi=" ";function hr(e,t){let n=[],r=[],o=[],i=e.split(`
|
|
9
|
+
`),a=ur(i),s=fr(i,a),c=ea(e,Oe),l=performance.now(),d;try{let x=Le(c);d=x.tokens;let O=Ut(x.diagnostics.filter(ee=>ee.severity==="error"),i,a);if(O.length>0)return o.push(...O),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:o}}catch(x){return o.push({severity:"error",code:"E_LEX",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-l}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),f;try{let x=Re(d),O=Ut(x.diagnostics,i,a),ee=O.filter(ot=>ot.severity==="error"),F=O.filter(ot=>ot.severity!=="error");if(ee.length>0)return o.push(...ee),r.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};if(!x.program)return o.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),r.push(...F),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};f=x.program,r.push(...F)}catch(x){return o.push({severity:"error",code:"E_PARSE",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-p});let h=performance.now(),A={actionName:t.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},S=f.domain.members.find(x=>x.kind==="action"&&x.name===Oe);if(!S)return o.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${Oe}' 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()-h}),{ops:[],trace:n,warnings:r,errors:o};let $=i.length+3+2;if(S.location.end.line!==$)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Oe}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-h}),{ops:[],trace:n,warnings:r,errors:o};let[K]=S.body;if(!K||K.kind!=="when"||!lr(K.condition)||S.body.length!==1)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Oe}'.`,location:s(S.location)}),n.push({phase:"analyze",durationMs:performance.now()-h}),{ops:[],trace:n,warnings:r,errors:o};let E=new rt({mapLocation:s,toMelExpr:Se}).collect(K.body,o,A,void 0);if(o.length===0&&e.trim()!==""&&E.length===0&&o.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(K.location)}),n.push({phase:"analyze",durationMs:performance.now()-h,details:{count:E.length}}),o.length>0)return{ops:[],trace:n,warnings:r,errors:o};let R=performance.now(),X={mode:"action",allowSysPaths:t.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:t.fnTableVersion??"1.0",actionName:t.actionName},W=[];for(let x of E)try{let O=dr(x);W.push(We(O,X))}catch(O){O instanceof _?o.push({severity:"error",code:O.code,message:O.message,location:s(x.patch.location)}):O instanceof Error?o.push({severity:"error",code:"E_LOWER",message:O.message,location:s(x.patch.location)}):o.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-R,details:{count:W.length}}),o.length>0?{ops:[],trace:n,warnings:r,errors:o}:{ops:W,trace:n,warnings:r,errors:o}}function ea(e,t){let n=e.split(`
|
|
10
|
+
`).map(r=>`${Zi}${r}`).join(`
|
|
11
|
+
`);return[`domain ${Xi} {`,` action ${t}() {`," when true {",n," }"," }","}"].join(`
|
|
12
|
+
`)}var ta="3.5.0";function na(e,t){let n=yr(e,t);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function ra(e,t){let n=yr(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:oa(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function yr(e,t){let n=[],r=[],o=[],i=performance.now(),a;try{let E=Le(e);a=E.tokens;let R=E.diagnostics.filter(W=>W.severity==="error");if(R.length>0)return o.push(...R),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o};let X=E.diagnostics.filter(W=>W.severity==="warning");r.push(...X)}catch(E){let R=E;return o.push({severity:"error",code:"E_LEX",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let E=Re(a),R=E.diagnostics.filter(X=>X.severity==="error");if(R.length>0)return o.push(...R),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};c=E.program}catch(E){let R=E;return o.push({severity:"error",code:"E_PARSE",message:R.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{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=Wn(c),p=d.diagnostics.filter(E=>E.severity==="error"),f=d.diagnostics.filter(E=>E.severity==="warning"),h=Xt(d.program),A=An(d.program),S=[...p,...h.diagnostics.filter(E=>E.severity==="error"),...A.diagnostics.filter(E=>E.severity==="error")],$=[...f,...h.diagnostics.filter(E=>E.severity==="warning"),...A.diagnostics.filter(E=>E.severity==="warning")];if(r.push(...$),n.push({phase:"analyze",durationMs:performance.now()-l}),S.length>0)return o.push(...S),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};let K=performance.now(),se=Ln(d.program);n.push({phase:"generate",durationMs:performance.now()-K});for(let E of se.diagnostics)E.severity==="warning"?r.push(E):o.push(E);if(se.schema){let E=Bn(d.program,se.schema),R=E.diagnostics.filter(F=>F.severity==="warning"),X=E.diagnostics.filter(F=>F.severity==="error");if(r.push(...R),o.push(...X),X.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)};let W=sr(ta),x=cr(d.program,e,se.schema,W),O=x.diagnostics.filter(F=>F.severity==="warning"),ee=x.diagnostics.filter(F=>F.severity==="error");return r.push(...O),o.push(...ee),ee.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)}:{program:d.program,schema:se.schema,annotations:E.annotations,sourceMap:x.sourceMap,trace:n,warnings:r,errors:ve(o)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:ve(o)}}function oa(e,t,n){return Object.freeze({schema:e,graph:zt(Jn(e)),annotations:t,sourceMap:n})}function zt(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let t of e)zt(t);return Object.freeze(e)}for(let t of Object.values(e))zt(t);return Object.freeze(e)}var qt=10;function ve(e){if(e.length<=qt)return e;let t=e.slice(0,qt);return t.push({severity:"error",code:"E_TOO_MANY",message:`... and ${e.length-qt} 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 ia(e,t){return hr(e,t)}export{it as a,gr as b,aa as c,Vt as d,Ht as e,at as f,Kt as g,Wt as h,ca as i,y as j,st as k,Le as l,ga as m,Ea as n,Yt as o,ct as p,Qt as q,ka as r,ba as s,Jt as t,lt as u,Re as v,je as w,dt as x,Xt as y,M as z,Zt as A,Ma as B,Er as C,Da as D,Oa as E,bt as F,An as G,Nt as H,St as I,vt as J,xt as K,Xr as L,_ as M,Ve as N,g as O,He as P,At as Q,Zr as R,wt as S,eo as T,u as U,No as V,xo as W,We as X,Bo as Y,Ln as Z,Bn as _,Wn as $,Jn as aa,sr as ba,cr as ca,na as da,ra as ea,ia as fa};
|
package/dist/esbuild.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
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};
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-
|
|
1
|
+
import{$ as H,A as kt,B as vt,C as bt,D as w,E as Nt,F as Ct,G as z,H as Pt,I as $t,J as At,K as St,L as xt,M as wt,N as Rt,O as Ot,P as Ft,Q as jt,R as Tt,S as Dt,T as S,U as It,V as _t,W as Mt,X as qt,Y as Lt,Z as B,_ as K,a as Xn,aa as Ut,b as Yn,ba as J,c as Qn,ca as X,d as Zn,da as Vt,e as et,ea as Wt,f as nt,fa as Gt,g as tt,h as rt,i as at,j as ot,k as it,l as _,m as st,n as ut,o as ct,p as lt,q as dt,r as pt,s as ft,t as mt,u as gt,v as M,w as yt,x as ht,y as G,z as Et}from"./chunk-PEO2YZ2Y.js";var Y={E001:{code:"E001",message:"$system.* cannot be used in computed expressions (non-deterministic)",category:"semantic"},E002:{code:"E002",message:"$system.* cannot be used in state initializers",category:"semantic"},E003:{code:"E003",message:"Invalid $system reference",category:"semantic"},E004:{code:"E004",message:"Identifier starts with reserved prefix '__sys__'",category:"syntax"},E005:{code:"E005",message:"available expression must be pure (no Effects, no $system.*)",category:"semantic"},E006:{code:"E006",message:"fail must be inside a guard (when, once, or onceIntent)",category:"semantic"},E007:{code:"E007",message:"stop must be inside a guard (when, once, or onceIntent)",category:"semantic"},E008:{code:"E008",message:"stop message suggests waiting/pending - use 'Already processed' style instead",category:"semantic"},E009:{code:"E009",message:"Primitive aggregation (sum, min, max) only allowed in computed",category:"semantic"},E010:{code:"E010",message:"Primitive aggregation does not allow composition - use direct reference only",category:"semantic"},E011:{code:"E011",message:"reduce/fold/scan is forbidden - use sum, min, max for aggregation",category:"semantic"},E013:{code:"E013",message:"Circular include detected",category:"semantic"},E014:{code:"E014",message:"Include expansion depth exceeds limit",category:"semantic"},E015:{code:"E015",message:"Include target is not a declared flow",category:"semantic"},E016:{code:"E016",message:"Include not allowed in InnerStmt position",category:"semantic"},E017:{code:"E017",message:"once() not allowed in flow",category:"semantic"},E018:{code:"E018",message:"onceIntent not allowed in flow",category:"semantic"},E019:{code:"E019",message:"patch not allowed in flow",category:"semantic"},E020:{code:"E020",message:"effect not allowed in flow",category:"semantic"},E021:{code:"E021",message:"Flow parameter name conflicts with top-level identifier",category:"semantic"},E022:{code:"E022",message:"Flow and action share the same name",category:"semantic"},E023:{code:"E023",message:"Wrong number of arguments for included flow",category:"semantic"},E024:{code:"E024",message:"Include argument type mismatch",category:"type"},E030:{code:"E030",message:"Collection element type does not have an 'id' field",category:"type"},E030a:{code:"E030a",message:"Collection element 'id' field is not a primitive type",category:"type"},E030b:{code:"E030b",message:"Duplicate '.id' values detected in state initializer",category:"type"},E031:{code:"E031",message:"updateById/removeById not allowed in this context",category:"semantic"},E032:{code:"E032",message:"Nested transform primitive",category:"semantic"},E033:{code:"E033",message:"Transform primitive collection argument is not a state path",category:"semantic"},E034:{code:"E034",message:"Transform primitive in guard condition",category:"semantic"},E035:{code:"E035",message:"Transform primitive in available condition",category:"semantic"},E040:{code:"E040",message:"Circular computed dependency",category:"semantic"},E041:{code:"E041",message:"Computed references undeclared identifier",category:"semantic"},E042:{code:"E042",message:"State initializer references non-constant value",category:"semantic"},E043:{code:"E043",message:"Non-trivial union type cannot be lowered to FieldSpec",category:"type"},E044:{code:"E044",message:"Recursive named type cannot be lowered to FieldSpec",category:"type"},E045:{code:"E045",message:"Nullable type cannot be lowered to FieldSpec",category:"type"},E046:{code:"E046",message:"Record type cannot be lowered to FieldSpec",category:"type"},E047:{code:"E047",message:"dispatchable expression must be pure (state/computed/action parameters only)",category:"semantic"},E048:{code:"E048",message:"Transform primitive in dispatchable condition",category:"semantic"},E049:{code:"E049",message:"Invalid literal clamp bounds",category:"semantic"},E050:{code:"E050",message:"Invalid match() form",category:"semantic"},E051:{code:"E051",message:"Duplicate match() key",category:"semantic"},E052:{code:"E052",message:"Invalid argmax()/argmin() form",category:"semantic"},E053:{code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations",category:"syntax"},E054:{code:"E054",message:"Action-parameter annotations are not part of the current MEL syntax",category:"syntax"},E055:{code:"E055",message:"Annotation payloads must be JSON-like literals",category:"semantic"},E056:{code:"E056",message:"Annotation payload nesting exceeds the current MEL limit of 2 levels",category:"semantic"},E057:{code:"E057",message:"Annotation target does not map to the emitted DomainSchema",category:"semantic"},E_UNDEFINED:{code:"E_UNDEFINED",message:"Undefined identifier",category:"semantic"},E_DUPLICATE:{code:"E_DUPLICATE",message:"Duplicate identifier",category:"semantic"},E_INVALID_ACCESS:{code:"E_INVALID_ACCESS",message:"Invalid access to identifier in this context",category:"semantic"},E_UNGUARDED_STMT:{code:"E_UNGUARDED_STMT",message:"Statement must be inside a guard (when or once)",category:"semantic"},E_UNGUARDED_PATCH:{code:"E_UNGUARDED_PATCH",message:"Patch must be inside a guard",category:"semantic"},E_UNGUARDED_EFFECT:{code:"E_UNGUARDED_EFFECT",message:"Effect must be inside a guard",category:"semantic"},E_ARG_COUNT:{code:"E_ARG_COUNT",message:"Wrong number of arguments",category:"type"},E_TYPE_MISMATCH:{code:"E_TYPE_MISMATCH",message:"Type mismatch",category:"type"},W_NON_BOOL_COND:{code:"W_NON_BOOL_COND",message:"Condition may not be boolean",category:"semantic"},W_UNUSED:{code:"W_UNUSED",message:"Unused identifier",category:"semantic"},W012:{code:"W012",message:"Anonymous object type in state field - use named type declaration instead",category:"type"},MEL_LEXER:{code:"MEL_LEXER",message:"Lexer error",category:"syntax"},MEL_PARSER:{code:"MEL_PARSER",message:"Parser error",category:"syntax"}};function Ht(e){return Y[e]}function Jt(e){let n=Y[e];return n?`${e}: ${n.message}`:e}function Q(e,n){let{code:t,message:r,location:a}=e;if(!a||a.start.line===0&&a.start.column===0)return`[${t}] ${r}`;let{line:o,column:s}=a.start,l=`[${t}] ${r} (${o}:${s})`;if(!n)return l;let y=n.split(`
|
|
2
2
|
`)[o-1];if(!y)return l;let h=String(o).padStart(4," "),f=`${h} | ${y}`,p=Math.max(1,a.end.line===a.start.line?Math.min(a.end.column-s,y.length-s+1):1),E=`${" ".repeat(h.length+3+s-1)}${"^".repeat(p)}`;return`${l}
|
|
3
3
|
${f}
|
|
4
4
|
${E}`}function me(e,n){return e.map(t=>Q(t,n)).join(`
|
package/dist/lexer/tokens.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { SourceLocation } from "./source-location.js";
|
|
|
6
6
|
/**
|
|
7
7
|
* All token kinds in MEL
|
|
8
8
|
*/
|
|
9
|
-
export type TokenKind = "DOMAIN" | "STATE" | "COMPUTED" | "ACTION" | "EFFECT" | "WHEN" | "ONCE" | "PATCH" | "UNSET" | "MERGE" | "TRUE" | "FALSE" | "NULL" | "AS" | "AVAILABLE" | "DISPATCHABLE" | "FAIL" | "STOP" | "WITH" | "TYPE" | "IMPORT" | "FROM" | "EXPORT" | "PLUS" | "MINUS" | "STAR" | "SLASH" | "PERCENT" | "EQ_EQ" | "BANG_EQ" | "LT" | "LT_EQ" | "GT" | "GT_EQ" | "AMP_AMP" | "PIPE_PIPE" | "BANG" | "QUESTION_QUESTION" | "QUESTION" | "COLON" | "EQ" | "AT" | "LPAREN" | "RPAREN" | "LBRACE" | "RBRACE" | "LBRACKET" | "RBRACKET" | "COMMA" | "SEMICOLON" | "DOT" | "PIPE" | "NUMBER" | "STRING" | "IDENTIFIER" | "SYSTEM_IDENT" | "ITEM" | "EOF" | "ERROR";
|
|
9
|
+
export type TokenKind = "DOMAIN" | "STATE" | "COMPUTED" | "ACTION" | "EFFECT" | "WHEN" | "ONCE" | "PATCH" | "UNSET" | "MERGE" | "TRUE" | "FALSE" | "NULL" | "AS" | "AVAILABLE" | "DISPATCHABLE" | "FAIL" | "STOP" | "WITH" | "TYPE" | "IMPORT" | "FROM" | "EXPORT" | "PLUS" | "MINUS" | "STAR" | "SLASH" | "PERCENT" | "EQ_EQ" | "BANG_EQ" | "LT" | "LT_EQ" | "GT" | "GT_EQ" | "AMP_AMP" | "PIPE_PIPE" | "BANG" | "QUESTION_QUESTION" | "QUESTION" | "COLON" | "EQ" | "AT" | "LPAREN" | "RPAREN" | "LBRACE" | "RBRACE" | "LBRACKET" | "RBRACKET" | "COMMA" | "SEMICOLON" | "DOT" | "ELLIPSIS" | "PIPE" | "NUMBER" | "STRING" | "IDENTIFIER" | "SYSTEM_IDENT" | "ITEM" | "EOF" | "ERROR";
|
|
10
10
|
/**
|
|
11
11
|
* A token produced by the lexer
|
|
12
12
|
*/
|
package/dist/node-loader.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as n}from"./chunk-
|
|
1
|
+
import{c as n}from"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";import{readFile as i}from"fs/promises";import{fileURLToPath as c}from"url";function u(o){let[t]=o.split("?",1),[r]=t.split("#",1);return r}function s(o){return u(o).endsWith(".mel")}function a(o){try{return c(o)}catch{return o}}var h=async(o,t,r)=>s(o)?{...await r(o,t),shortCircuit:!0}:r(o,t),p=async(o,t,r)=>{if(!s(o))return r(o,t);let e=await i(new URL(o),"utf8");return{format:"module",source:n(e,a(o)),shortCircuit:!0}};export{p as load,h as resolve};
|
package/dist/parser/ast.d.ts
CHANGED
|
@@ -344,13 +344,18 @@ export interface TernaryExprNode extends ASTNode {
|
|
|
344
344
|
*/
|
|
345
345
|
export interface ObjectLiteralExprNode extends ASTNode {
|
|
346
346
|
kind: "objectLiteral";
|
|
347
|
-
properties:
|
|
347
|
+
properties: ObjectLiteralEntryNode[];
|
|
348
348
|
}
|
|
349
|
+
export type ObjectLiteralEntryNode = ObjectPropertyNode | ObjectSpreadNode;
|
|
349
350
|
export interface ObjectPropertyNode extends ASTNode {
|
|
350
351
|
kind: "objectProperty";
|
|
351
352
|
key: string;
|
|
352
353
|
value: ExprNode;
|
|
353
354
|
}
|
|
355
|
+
export interface ObjectSpreadNode extends ASTNode {
|
|
356
|
+
kind: "objectSpread";
|
|
357
|
+
expr: ExprNode;
|
|
358
|
+
}
|
|
354
359
|
/**
|
|
355
360
|
* Array literal expression ([1, 2, 3])
|
|
356
361
|
*/
|
package/dist/rollup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var l=e.rollup,t=l;export{t as default,l as melPlugin};
|
package/dist/rspack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.rspack,o=t;export{o as default,t as melPlugin};
|
package/dist/vite.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.vite,o=t;export{o as default,t as melPlugin};
|
package/dist/webpack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e}from"./chunk-
|
|
1
|
+
import{a as e}from"./chunk-MB43CHXV.js";import"./chunk-M3P5RIDR.js";import"./chunk-PEO2YZ2Y.js";var t=e.webpack,o=t;export{o as default,t as melPlugin};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@manifesto-ai/compiler",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.8.0",
|
|
4
4
|
"description": "Manifesto Compiler - MEL (Manifesto Expression Language) to DomainSchema compiler",
|
|
5
5
|
"author": "eggplantiny <eggplantiny@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|
|
63
63
|
"@anthropic-ai/sdk": "^0.26.0",
|
|
64
|
-
"@manifesto-ai/core": "^2.
|
|
64
|
+
"@manifesto-ai/core": "^2.13.0",
|
|
65
65
|
"openai": "^4.0.0",
|
|
66
66
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0",
|
|
67
67
|
"zod": "^4.3.6"
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
"vitest": "^4.1.2",
|
|
98
98
|
"webpack": "^5.106.1",
|
|
99
99
|
"zod": "^4.3.6",
|
|
100
|
-
"@manifesto-ai/core": "2.
|
|
100
|
+
"@manifesto-ai/core": "2.13.0"
|
|
101
101
|
},
|
|
102
102
|
"files": [
|
|
103
103
|
"dist"
|
package/dist/chunk-O654OLQV.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
var Je={domain:"DOMAIN",state:"STATE",computed:"COMPUTED",action:"ACTION",effect:"EFFECT",when:"WHEN",once:"ONCE",patch:"PATCH",unset:"UNSET",merge:"MERGE",true:"TRUE",false:"FALSE",null:"NULL",as:"AS",available:"AVAILABLE",dispatchable:"DISPATCHABLE",fail:"FAIL",stop:"STOP",with:"WITH",type:"TYPE",import:"IMPORT",from:"FROM",export:"EXPORT"},er=new Set(["function","var","let","const","if","else","for","while","do","switch","case","break","continue","return","throw","try","catch","finally","new","delete","instanceof","void","debugger","this","super","arguments","eval","async","await","yield","class","extends","interface","enum","namespace","module"]);function $i(t){return t in Je}function Lt(t){return er.has(t)}function Ft(t){return Object.hasOwn(Je,t)?Je[t]:void 0}function Ze(t,e,n,r){return{kind:t,lexeme:e,location:n,value:r}}function jt(t,e,n){return{line:t,column:e,offset:n}}function _t(t,e,n){return{start:t,end:e,source:n}}function Bi(t,e){return{start:t,end:t,source:e}}function h(t,e){return{start:t.start.offset<e.start.offset?t.start:e.start,end:t.end.offset>e.end.offset?t.end:e.end,source:t.source??e.source}}var et=class{source;sourcePath;tokens=[];diagnostics=[];start=0;current=0;line=1;column=1;lineStart=0;constructor(e,n){this.source=e,this.sourcePath=n}tokenize(){for(;!this.isAtEnd();)this.start=this.current,this.scanToken();return this.tokens.push(Ze("EOF","",this.currentLocation())),{tokens:this.tokens,diagnostics:this.diagnostics}}scanToken(){let e=this.advance();switch(e){case"(":this.addToken("LPAREN");break;case")":this.addToken("RPAREN");break;case"{":this.addToken("LBRACE");break;case"}":this.addToken("RBRACE");break;case"[":this.addToken("LBRACKET");break;case"]":this.addToken("RBRACKET");break;case",":this.addToken("COMMA");break;case";":this.addToken("SEMICOLON");break;case".":this.addToken("DOT");break;case"+":this.addToken("PLUS");break;case"-":this.addToken("MINUS");break;case"*":this.addToken("STAR");break;case"%":this.addToken("PERCENT");break;case":":this.addToken("COLON");break;case"@":this.addToken("AT");break;case"=":this.addToken(this.match("=")?"EQ_EQ":"EQ");break;case"!":this.addToken(this.match("=")?"BANG_EQ":"BANG");break;case"<":this.addToken(this.match("=")?"LT_EQ":"LT");break;case">":this.addToken(this.match("=")?"GT_EQ":"GT");break;case"&":this.match("&")?this.addToken("AMP_AMP"):this.error("Expected '&&' for logical AND");break;case"|":this.match("|")?this.addToken("PIPE_PIPE"):this.addToken("PIPE");break;case"?":this.addToken(this.match("?")?"QUESTION_QUESTION":"QUESTION");break;case"/":this.match("/")?this.lineComment():this.match("*")?this.blockComment():this.addToken("SLASH");break;case" ":case"\r":case" ":break;case`
|
|
2
|
-
`:this.newline();break;case'"':this.string('"');break;case"'":this.string("'");break;case"$":this.systemIdentifier();break;default:this.isDigit(e)?this.number():this.isAlpha(e)?this.identifier():this.error(`Unexpected character '${e}'`)}}lineComment(){for(;this.peek()!==`
|
|
3
|
-
`&&!this.isAtEnd();)this.advance()}blockComment(){let e=this.line,n=this.column-2;for(;!this.isAtEnd();){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance();return}this.peek()===`
|
|
4
|
-
`&&this.newline(),this.advance()}this.error(`Unterminated block comment starting at line ${e}:${n}`)}string(e){let n=this.line,r=this.column-1,o="";for(;this.peek()!==e&&!this.isAtEnd();){if(this.peek()===`
|
|
5
|
-
`){this.error("Unterminated string literal");return}if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":o+=`
|
|
6
|
-
`;break;case"r":o+="\r";break;case"t":o+=" ";break;case"\\":o+="\\";break;case"'":o+="'";break;case'"':o+='"';break;case"0":o+="\0";break;default:this.error(`Invalid escape sequence '\\${i}'`),o+=i}}else o+=this.advance()}if(this.isAtEnd()){this.error(`Unterminated string starting at line ${n}:${r}`);return}this.advance(),this.addToken("STRING",o)}number(){if(this.source[this.start]==="0"&&(this.peek()==="x"||this.peek()==="X")){for(this.advance();this.isHexDigit(this.peek());)this.advance();let n=this.source.slice(this.start+2,this.current),r=parseInt(n,16);this.addToken("NUMBER",r);return}for(;this.isDigit(this.peek());)this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(this.advance();this.isDigit(this.peek());)this.advance();if(this.peek()==="e"||this.peek()==="E"){if(this.advance(),(this.peek()==="+"||this.peek()==="-")&&this.advance(),!this.isDigit(this.peek())){this.error("Invalid number: expected digits after exponent");return}for(;this.isDigit(this.peek());)this.advance()}let e=parseFloat(this.source.slice(this.start,this.current));this.addToken("NUMBER",e)}identifier(){for(;this.isAlphaNumeric(this.peek());){if(this.peek()==="$"){this.advance(),this.error("'$' is forbidden in identifiers (MEL A17)","E004");continue}this.advance()}let e=this.source.slice(this.start,this.current);if(e.startsWith("__sys__")){this.error("'__sys__' prefix is reserved for compiler-generated identifiers (MEL A26)","E004"),this.addToken("ERROR");return}if(Lt(e)){this.error(`'${e}' is a reserved keyword and cannot be used`),this.addToken("ERROR");return}let n=Ft(e);n?this.addToken(n):this.addToken("IDENTIFIER")}systemIdentifier(){if(!this.isAlpha(this.peek())){this.error("Expected identifier after '$'"),this.addToken("ERROR");return}for(;this.isAlphaNumeric(this.peek());)this.advance();let e=this.source.slice(this.start,this.current);if(e==="$item"){this.addToken("ITEM");return}if(e==="$system"||e==="$meta"||e==="$input"){for(;this.peek()==="."&&this.isAlpha(this.peekNext());)for(this.advance();this.isAlphaNumeric(this.peek());)this.advance();this.addToken("SYSTEM_IDENT");return}this.error(`Invalid system identifier '${e}'. Expected $system.*, $meta.*, $input.*, or $item`),this.addToken("ERROR")}isAtEnd(){return this.current>=this.source.length}advance(){let e=this.source[this.current];return this.current++,this.column++,e}peek(){return this.isAtEnd()?"\0":this.source[this.current]}peekNext(){return this.current+1>=this.source.length?"\0":this.source[this.current+1]}match(e){return this.isAtEnd()||this.source[this.current]!==e?!1:(this.current++,this.column++,!0)}newline(){this.line++,this.column=1,this.lineStart=this.current}isDigit(e){return e>="0"&&e<="9"}isHexDigit(e){return this.isDigit(e)||e>="a"&&e<="f"||e>="A"&&e<="F"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}currentLocation(){let e=this.positionAt(this.start),n=this.positionAt(this.current);return _t(e,n,this.sourcePath)}positionAt(e){let n=1,r=0;for(let o=0;o<e;o++)this.source[o]===`
|
|
7
|
-
`&&(n++,r=o+1);return jt(n,e-r+1,e)}addToken(e,n){let r=this.source.slice(this.start,this.current);this.tokens.push(Ze(e,r,this.currentLocation(),n))}error(e,n="MEL_LEXER"){let r=this.currentLocation();this.diagnostics.push({severity:"error",code:n,message:e,location:r,source:this.getSourceLine(r.start.line)})}getSourceLine(e){return this.source.split(`
|
|
8
|
-
`)[e-1]??""}};function Pe(t,e){return new et(t,e).tokenize()}function Qi(t){return["literal","identifier","systemIdent","iterationVar","propertyAccess","indexAccess","functionCall","unary","binary","ternary","objectLiteral","arrayLiteral"].includes(t.kind)}function Xi(t){return["when","once","onceIntent","patch","effect","fail","stop"].includes(t.kind)}var $t=(f=>(f[f.NONE=0]="NONE",f[f.TERNARY=1]="TERNARY",f[f.NULLISH=2]="NULLISH",f[f.OR=3]="OR",f[f.AND=4]="AND",f[f.EQUALITY=5]="EQUALITY",f[f.COMPARISON=6]="COMPARISON",f[f.ADDITIVE=7]="ADDITIVE",f[f.MULTIPLICATIVE=8]="MULTIPLICATIVE",f[f.UNARY=9]="UNARY",f[f.CALL=10]="CALL",f[f.ACCESS=11]="ACCESS",f))($t||{});function tt(t){switch(t){case"QUESTION":return 1;case"QUESTION_QUESTION":return 2;case"PIPE_PIPE":return 3;case"AMP_AMP":return 4;case"EQ_EQ":case"BANG_EQ":return 5;case"LT":case"LT_EQ":case"GT":case"GT_EQ":return 6;case"PLUS":case"MINUS":return 7;case"STAR":case"SLASH":case"PERCENT":return 8;default:return 0}}function Gt(t){switch(t){case"PLUS":return"+";case"MINUS":return"-";case"STAR":return"*";case"SLASH":return"/";case"PERCENT":return"%";case"EQ_EQ":return"==";case"BANG_EQ":return"!=";case"LT":return"<";case"LT_EQ":return"<=";case"GT":return">";case"GT_EQ":return">=";case"AMP_AMP":return"&&";case"PIPE_PIPE":return"||";case"QUESTION_QUESTION":return"??";default:return null}}function Zi(t){return tt(t)!==0}function ea(t){return t==="BANG"||t==="MINUS"}function Bt(t){return t==="QUESTION"||t==="QUESTION_QUESTION"}var nt=class{tokens;current=0;diagnostics=[];constructor(e){this.tokens=e}parse(){try{return{program:this.parseProgram(),diagnostics:this.diagnostics}}catch{return{program:null,diagnostics:this.diagnostics}}}parseProgram(){let e=this.peek().location,n=[];for(;this.check("IMPORT");)n.push(this.parseImport());let r=this.parseAnnotationList();r.length>0&&!this.check("DOMAIN")&&this.reportUnsupportedAnnotations(r);let o=this.parseDomain(r);return{kind:"program",imports:n,domain:o,location:h(e,o.location)}}parseImport(){let e=this.consume("IMPORT","Expected 'import'").location;this.consume("LBRACE","Expected '{' after 'import'");let n=[];do n.push(this.consume("IDENTIFIER","Expected identifier").lexeme);while(this.match("COMMA"));this.consume("RBRACE","Expected '}' after import names"),this.consume("FROM","Expected 'from' after import names");let r=this.consume("STRING","Expected string after 'from'");return{kind:"import",names:n,from:r.value,location:h(e,r.location)}}parseDomain(e=[]){let n=this.consume("DOMAIN","Expected 'domain'").location,r=this.consume("IDENTIFIER","Expected domain name").lexeme;this.consume("LBRACE","Expected '{' after domain name");let o=[],i=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let s=this.parseAnnotationList();if(s.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(s);continue}if(this.check("TYPE"))o.push(this.parseTypeDecl(s));else{let c=this.parseDomainMember(s);c&&i.push(c)}}let a=this.consume("RBRACE","Expected '}' to close domain").location;return{kind:"domain",name:r,annotations:e.length>0?e:void 0,types:o,members:i,location:h(n,a)}}parseTypeDecl(e=[]){let n=this.consume("TYPE","Expected 'type'").location,r=this.consume("IDENTIFIER","Expected type name").lexeme;this.consume("EQ","Expected '=' after type name");let o=this.parseTypeExpr();return{kind:"typeDecl",name:r,annotations:e.length>0?e:void 0,typeExpr:o,location:h(n,o.location)}}parseDomainMember(e=[]){return this.check("STATE")?(this.reportUnsupportedAnnotations(e),this.parseState()):this.check("COMPUTED")?this.parseComputed(e):this.check("ACTION")?this.parseAction(e):this.isFlowDeclContext()?(this.reportUnsupportedAnnotations(e),this.parseFlowDecl()):(this.reportUnsupportedAnnotations(e),this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'state', 'computed', 'action', or 'flow'.`),this.advance(),null)}parseState(){let e=this.consume("STATE","Expected 'state'").location;this.consume("LBRACE","Expected '{' after 'state'");let n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}n.push(this.parseStateField(o))}let r=this.consume("RBRACE","Expected '}' to close state block").location;return{kind:"state",fields:n,location:h(e,r)}}parseStateField(e=[]){let n=this.consume("IDENTIFIER","Expected field name");this.consume("COLON","Expected ':' after field name");let r=this.parseTypeExpr(),o;return this.match("EQ")&&(o=this.parseExpression()),{kind:"stateField",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:r,initializer:o,location:h(n.location,o?.location??r.location)}}parseComputed(e=[]){let n=this.consume("COMPUTED","Expected 'computed'").location,r=this.consume("IDENTIFIER","Expected computed name").lexeme;this.consume("EQ","Expected '=' after computed name");let o=this.parseExpression();return{kind:"computed",name:r,annotations:e.length>0?e:void 0,expression:o,location:h(n,o.location)}}parseAction(e=[]){let n=this.consume("ACTION","Expected 'action'").location,r=this.consume("IDENTIFIER","Expected action name").lexeme;this.consume("LPAREN","Expected '(' after action name");let o=[];if(!this.check("RPAREN"))do{let l=this.parseAnnotationList();if(l.length>0&&(this.check("RPAREN")||this.isAtEnd())){this.reportUnsupportedAnnotations(l);break}o.push(this.parseParam(l))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters");let i;this.match("AVAILABLE")&&(this.consume("WHEN","Expected 'when' after 'available'"),i=this.parseExpression());let a;if(this.match("DISPATCHABLE")&&(this.consume("WHEN","Expected 'when' after 'dispatchable'"),a=this.parseExpression()),this.check("AVAILABLE")){let l=a?"'available when' must appear before 'dispatchable when' in an action":"Action can declare 'available when' at most once";throw this.errorAtCurrent(l)}if(this.check("DISPATCHABLE"))throw this.errorAtCurrent("Action can declare 'dispatchable when' at most once");this.consume("LBRACE","Expected '{' to start action body");let s=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let l=this.parseGuardedStmt();l&&s.push(l)}let c=this.consume("RBRACE","Expected '}' to close action").location;return{kind:"action",name:r,annotations:e.length>0?e:void 0,params:o,available:i,dispatchable:a,body:s,location:h(n,c)}}parseFlowDecl(){let e=this.consume("IDENTIFIER","Expected 'flow'"),n=this.consume("IDENTIFIER","Expected flow name").lexeme;this.consume("LPAREN","Expected '(' after flow name");let r=[];if(!this.check("RPAREN"))do{let a=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(a),a.length>0&&(this.check("RPAREN")||this.isAtEnd()))break;r.push(this.parseParam(a))}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' to start flow body");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseFlowStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close flow").location;return{kind:"flow",name:n,params:r,body:o,location:h(e.location,i)}}parseParam(e=[]){let n=this.consume("IDENTIFIER","Expected parameter name");this.consume("COLON","Expected ':' after parameter name");let r=this.parseTypeExpr();return{kind:"param",name:n.lexeme,annotations:e.length>0?e:void 0,typeExpr:r,location:h(n.location,r.location)}}parseGuardedStmt(){let e=this.parseAnnotationList();if(this.reportUnsupportedAnnotations(e),this.check("WHEN"))return this.parseWhenStmt();if(this.check("ONCE"))return this.parseOnceStmt();if(this.isOnceIntentContext())return this.parseOnceIntentStmt();if(this.isIncludeContext())return this.parseIncludeStmt();if(this.check("FAIL"))return this.parseFailStmt();if(this.check("STOP"))return this.parseStopStmt();let n=this.peek();return n.kind==="PATCH"||n.lexeme==="patch"||n.kind==="EFFECT"||n.lexeme==="effect"?(this.error(`'${n.lexeme}' must be inside a guard block (when, once, or onceIntent). Wrap it: when true { ${n.lexeme} ... }`),this.skipToRecoveryPoint(),null):(this.error(`Unexpected token '${n.lexeme}'. Expected 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseFlowStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("WHEN")?this.parseWhenStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'when', 'include', 'once', 'onceIntent', 'patch', or 'effect'.`),this.advance(),null)}skipToRecoveryPoint(){let e=0;for(;!this.isAtEnd();){let n=this.peek();if(n.kind==="LBRACE"){e++,this.advance();continue}if(n.kind==="RBRACE"){if(e===0)return;e--,this.advance();continue}if(e===0&&(n.kind==="WHEN"||n.kind==="ONCE"||n.lexeme==="onceIntent"||this.isIncludeContext()||n.kind==="FAIL"||n.kind==="STOP"))return;this.advance()}}parseWhenStmt(){let e=this.consume("WHEN","Expected 'when'").location,n=this.parseExpression();this.consume("LBRACE","Expected '{' after when condition");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close when block").location;return{kind:"when",condition:n,body:r,location:h(e,o)}}parseOnceStmt(){let e=this.consume("ONCE","Expected 'once'").location;this.consume("LPAREN","Expected '(' after 'once'");let n=this.parsePath();this.consume("RPAREN","Expected ')' after marker");let r;this.match("WHEN")&&(r=this.parseExpression()),this.consume("LBRACE","Expected '{' to start once block");let o=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let a=this.parseInnerStmt();a&&o.push(a)}let i=this.consume("RBRACE","Expected '}' to close once block").location;return{kind:"once",marker:n,condition:r,body:o,location:h(e,i)}}parseOnceIntentStmt(){let e=this.consume("IDENTIFIER","Expected 'onceIntent'"),n;this.match("WHEN")&&(n=this.parseExpression()),this.consume("LBRACE","Expected '{' to start onceIntent block");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let i=this.parseInnerStmt();i&&r.push(i)}let o=this.consume("RBRACE","Expected '}' to close onceIntent block").location;return{kind:"onceIntent",condition:n,body:r,location:h(e.location,o)}}parseInnerStmt(){let e=this.parseAnnotationList();return this.reportUnsupportedAnnotations(e),this.check("PATCH")?this.parsePatchStmt():this.check("EFFECT")?this.parseEffectStmt():this.check("WHEN")?this.parseWhenStmt():this.check("ONCE")?this.parseOnceStmt():this.isOnceIntentContext()?this.parseOnceIntentStmt():this.isIncludeContext()?this.parseIncludeStmt():this.check("FAIL")?this.parseFailStmt():this.check("STOP")?this.parseStopStmt():(this.error(`Unexpected token '${this.peek().lexeme}'. Expected 'patch', 'effect', 'when', 'once', 'onceIntent', 'include', 'fail', or 'stop'.`),this.advance(),null)}parseIncludeStmt(){let e=this.consume("IDENTIFIER","Expected 'include'"),n=this.consume("IDENTIFIER","Expected flow name after 'include'");this.consume("LPAREN","Expected '(' after flow name");let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));let o=this.consume("RPAREN","Expected ')' after include arguments").location;return{kind:"include",flowName:n.lexeme,args:r,location:h(e.location,o)}}parsePatchStmt(){let e=this.consume("PATCH","Expected 'patch'").location,n=this.parsePath(),r,o,i;return this.match("UNSET")?(r="unset",i=this.previous().location):this.match("MERGE")?(r="merge",o=this.parseExpression(),i=o.location):(this.consume("EQ","Expected '=', 'unset', or 'merge' after path"),r="set",o=this.parseExpression(),i=o.location),{kind:"patch",path:n,op:r,value:o,location:h(e,i)}}parseEffectStmt(){let e=this.consume("EFFECT","Expected 'effect'").location,n=this.consume("IDENTIFIER","Expected effect type").lexeme;for(;this.match("DOT");)n+="."+this.consume("IDENTIFIER","Expected identifier after '.'").lexeme;this.consume("LPAREN","Expected '(' after effect type"),this.consume("LBRACE","Expected '{' for effect arguments");let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseEffectArg()),this.match("COMMA");this.consume("RBRACE","Expected '}' after effect arguments");let o=this.consume("RPAREN","Expected ')' to close effect").location;return{kind:"effect",effectType:n,args:r,location:h(e,o)}}parseEffectArg(){let e=this.match("IDENTIFIER","FAIL")?this.previous():this.consume("IDENTIFIER","Expected argument name");this.consume("COLON","Expected ':' after argument name");let n=["into","pass","fail"].includes(e.lexeme),r=n?this.parsePath():this.parseExpression();return{kind:"effectArg",name:e.lexeme,value:r,isPath:n,location:h(e.location,r.location)}}parseFailStmt(){let e=this.consume("FAIL","Expected 'fail'").location,n=this.consume("STRING","Expected error code string after 'fail'"),r=n.value,o,i=n.location;return this.match("WITH")&&(o=this.parseExpression(),i=o.location),{kind:"fail",code:r,message:o,location:h(e,i)}}parseStopStmt(){let e=this.consume("STOP","Expected 'stop'").location,n=this.consume("STRING","Expected reason string after 'stop'");return{kind:"stop",reason:n.value,location:h(e,n.location)}}parseTypeExpr(){let e=this.parseBaseType();if(this.check("PIPE")){let n=[e];for(;this.match("PIPE");)n.push(this.parseBaseType());e={kind:"unionType",types:n,location:h(n[0].location,n[n.length-1].location)}}return e}parseBaseType(){if(this.check("LBRACE"))return this.parseObjectType();if(this.check("STRING")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("NUMBER")){let n=this.advance();return{kind:"literalType",value:n.value,location:n.location}}if(this.check("TRUE")||this.check("FALSE")){let n=this.advance();return{kind:"literalType",value:n.kind==="TRUE",location:n.location}}if(this.check("NULL"))return{kind:"literalType",value:null,location:this.advance().location};let e=this.consume("IDENTIFIER","Expected type name");if(this.match("LT"))if(e.lexeme==="Array"){let n=this.parseTypeExpr(),r=this.consume("GT","Expected '>' after array element type").location;return{kind:"arrayType",elementType:n,location:h(e.location,r)}}else if(e.lexeme==="Record"){let n=this.parseTypeExpr();this.consume("COMMA","Expected ',' between Record type parameters");let r=this.parseTypeExpr(),o=this.consume("GT","Expected '>' after Record value type").location;return{kind:"recordType",keyType:n,valueType:r,location:h(e.location,o)}}else{for(this.error(`Unknown generic type '${e.lexeme}'`);!this.check("GT")&&!this.isAtEnd();)this.advance();this.match("GT")}return{kind:"simpleType",name:e.lexeme,location:e.location}}parseObjectType(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.parseAnnotationList();if(o.length>0&&(this.check("RBRACE")||this.isAtEnd())){this.reportUnsupportedAnnotations(o);continue}let i=this.consume("IDENTIFIER","Expected field name"),a=this.match("QUESTION");this.consume("COLON","Expected ':' after field name");let s=this.parseTypeExpr();n.push({kind:"typeField",name:i.lexeme,annotations:o.length>0?o:void 0,typeExpr:s,optional:a,location:h(i.location,s.location)}),this.match("COMMA")}let r=this.consume("RBRACE","Expected '}' to close object type").location;return{kind:"objectType",fields:n,location:h(e,r)}}parseExpression(e=0){let n=this.parsePrimary();for(;;){let r=tt(this.peek().kind);if(r<=e)break;if(this.peek().kind==="QUESTION"){n=this.parseTernary(n);continue}let o=Gt(this.peek().kind);if(!o)break;this.advance();let i=Bt(this.previous().kind)?r-1:r,a=this.parseExpression(i);n={kind:"binary",operator:o,left:n,right:a,location:h(n.location,a.location)}}return n}parseTernary(e){this.consume("QUESTION","Expected '?'");let n=this.parseExpression();this.consume("COLON","Expected ':' in ternary expression");let r=this.parseExpression(0);return{kind:"ternary",condition:e,consequent:n,alternate:r,location:h(e.location,r.location)}}parsePrimary(){if(this.check("BANG")||this.check("MINUS")&&this.isUnaryContext()){let e=this.advance(),n=this.parsePrimary();return{kind:"unary",operator:e.kind==="BANG"?"!":"-",operand:n,location:h(e.location,n.location)}}if(this.match("LPAREN")){let e=this.parseExpression();return this.consume("RPAREN","Expected ')' after expression"),e}if(this.check("LBRACE"))return this.parseObjectLiteral();if(this.check("LBRACKET"))return this.parseArrayLiteral();if(this.check("NUMBER")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"number",location:e.location}}if(this.check("STRING")){let e=this.advance();return{kind:"literal",value:e.value,literalType:"string",location:e.location}}if(this.check("TRUE")||this.check("FALSE")){let e=this.advance();return{kind:"literal",value:e.kind==="TRUE",literalType:"boolean",location:e.location}}if(this.check("NULL"))return{kind:"literal",value:null,literalType:"null",location:this.advance().location};if(this.check("SYSTEM_IDENT")){let e=this.advance(),n=e.lexeme.slice(1).split(".");return this.parsePostfix({kind:"systemIdent",path:n,location:e.location})}if(this.check("ITEM")){let e=this.advance();return this.parsePostfix({kind:"iterationVar",name:"item",location:e.location})}if(this.check("MERGE")&&this.peekNext()?.kind==="LPAREN"){let e=this.advance();return this.parseFunctionCall(e)}if(this.check("IDENTIFIER")){let e=this.advance();return this.check("LPAREN")?this.parseFunctionCall(e):this.parsePostfix({kind:"identifier",name:e.lexeme,location:e.location})}return this.error(`Unexpected token '${this.peek().lexeme}'`),{kind:"literal",value:null,literalType:"null",location:this.peek().location}}parseFunctionCall(e){this.consume("LPAREN","Expected '(' for function call");let n=[];if(!this.check("RPAREN"))do n.push(this.parseExpression());while(this.match("COMMA"));let r=this.consume("RPAREN","Expected ')' after arguments").location;return this.parsePostfix({kind:"functionCall",name:e.lexeme,args:n,location:h(e.location,r)})}parsePostfix(e){for(;;)if(this.match("DOT")){let n=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"propertyAccess",object:e,property:n.lexeme,location:h(e.location,n.location)}}else if(this.match("LBRACKET")){let n=this.parseExpression(),r=this.consume("RBRACKET","Expected ']' after index").location;e={kind:"indexAccess",object:e,index:n,location:h(e.location,r)}}else break;return e}parseObjectLiteral(){let e=this.consume("LBRACE","Expected '{'").location,n=[];for(;!this.check("RBRACE")&&!this.isAtEnd();){let o=this.consume("IDENTIFIER","Expected property name");this.consume("COLON","Expected ':' after property name");let i=this.parseExpression();n.push({kind:"objectProperty",key:o.lexeme,value:i,location:h(o.location,i.location)}),this.check("RBRACE")||this.consume("COMMA","Expected ',' between properties")}let r=this.consume("RBRACE","Expected '}' to close object").location;return{kind:"objectLiteral",properties:n,location:h(e,r)}}parseArrayLiteral(){let e=this.consume("LBRACKET","Expected '['").location,n=[];for(;!this.check("RBRACKET")&&!this.isAtEnd();)n.push(this.parseExpression()),this.check("RBRACKET")||this.consume("COMMA","Expected ',' between elements");let r=this.consume("RBRACKET","Expected ']' to close array").location;return{kind:"arrayLiteral",elements:n,location:h(e,r)}}parsePath(){let e=[],n=this.peek().location,r=this.consume("IDENTIFIER","Expected identifier");for(e.push({kind:"propertySegment",name:r.lexeme,location:r.location});;)if(this.match("DOT")){let i=this.consume("IDENTIFIER","Expected property name");e.push({kind:"propertySegment",name:i.lexeme,location:i.location})}else if(this.match("LBRACKET")){let i=this.parseExpression(),a=this.consume("RBRACKET","Expected ']'").location;e.push({kind:"indexSegment",index:i,location:h(i.location,a)})}else break;let o=e[e.length-1];return{kind:"path",segments:e,location:h(n,o.location)}}isUnaryContext(){if(this.current===0)return!0;let e=this.previous();return["LPAREN","LBRACKET","LBRACE","COMMA","COLON","EQ","PLUS","MINUS","STAR","SLASH","PERCENT","AT","EQ_EQ","BANG_EQ","LT","LT_EQ","GT","GT_EQ","AMP_AMP","PIPE_PIPE","BANG","QUESTION","QUESTION_QUESTION"].includes(e.kind)}peek(){return this.tokens[this.current]}peekNext(){return this.peekAt(1)}peekAt(e){return this.current+e>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.current+e]}previous(){return this.tokens[this.current-1]}isAtEnd(){return this.peek().kind==="EOF"}advance(){return this.isAtEnd()||this.current++,this.previous()}check(e){return this.isAtEnd()?!1:this.peek().kind===e}isOnceIntentContext(){if(!this.check("IDENTIFIER")||this.peek().lexeme!=="onceIntent")return!1;let n=this.peekNext();return n.kind==="LBRACE"||n.kind==="WHEN"}isFlowDeclContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="flow"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}isIncludeContext(){return!this.check("IDENTIFIER")||this.peek().lexeme!=="include"?!1:this.peekNext().kind==="IDENTIFIER"&&this.peekAt(2).kind==="LPAREN"}match(...e){for(let n of e)if(this.check(n))return this.advance(),!0;return!1}consume(e,n){if(this.check(e))return this.advance();throw this.errorAtCurrent(n)}parseAnnotationList(){let e=[];for(;this.check("AT");)e.push(this.parseAnnotation());return e}parseAnnotation(){let e=this.consume("AT","Expected '@'").location,n=this.consume("IDENTIFIER","Expected annotation name after '@'");if(n.lexeme!=="meta")throw this.errorAtToken(n,"Expected 'meta' after '@'");this.consume("LPAREN","Expected '(' after '@meta'");let r=this.consume("STRING","Expected string tag as first @meta argument"),o;this.match("COMMA")&&(o=this.parseExpression());let i=this.consume("RPAREN","Expected ')' after @meta arguments").location;return{kind:"annotation",tag:r.value,payload:o,location:h(e,i)}}reportUnsupportedAnnotations(e){for(let n of e)this.diagnostics.push({severity:"error",code:"E053",message:"@meta can attach only to domain, type, type field, state field, computed, or action declarations.",location:n.location})}error(e){this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.previous().location})}errorAtCurrent(e){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:e,location:this.peek().location}),new Error(e)}errorAtToken(e,n){return this.diagnostics.push({severity:"error",code:"MEL_PARSER",message:n,location:e.location}),new Error(n)}};function Ie(t){return new nt(t).parse()}var Me=class{parent;symbols=new Map;kind;constructor(e,n=null){this.kind=e,this.parent=n}define(e){this.symbols.set(e.name,e)}lookup(e){let n=this.symbols.get(e);return n||this.parent?.lookup(e)}isDefined(e){return this.symbols.has(e)}},rt=class{diagnostics=[];scopes=new Map;currentScope=null;domainScope=null;analyze(e){return this.diagnostics=[],this.scopes=new Map,this.currentScope=null,this.domainScope=null,this.analyzeDomain(e.domain),{scopes:this.scopes,diagnostics:this.diagnostics}}analyzeDomain(e){let n=new Me("domain");this.domainScope=n,this.currentScope=n,this.scopes.set("domain",n);for(let r of e.members)if(r.kind==="state")for(let o of r.fields)this.defineSymbol({name:o.name,kind:"state",location:o.location});else r.kind==="computed"?this.defineSymbol({name:r.name,kind:"computed",location:r.location}):r.kind==="action"?this.defineSymbol({name:r.name,kind:"action",location:r.location}):r.kind;for(let r of e.members)r.kind==="computed"?this.analyzeComputedExpr(r):r.kind==="action"&&this.analyzeAction(r)}analyzeComputedExpr(e){this.analyzeExpr(e.expression,"computed")}analyzeAction(e){let n=new Me("action",this.domainScope);this.currentScope=n,this.scopes.set(`action.${e.name}`,n);for(let r of e.params)n.define({name:r.name,kind:"param",location:r.location});for(let r of e.body)this.analyzeStmt(r);this.currentScope=this.domainScope}analyzeStmt(e){switch(e.kind){case"when":this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"onceIntent":e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"once":this.validatePath(e.marker),e.condition&&this.analyzeExpr(e.condition,"action");for(let n of e.body)this.analyzeStmt(n);break;case"patch":this.validatePath(e.path),e.value&&this.analyzeExpr(e.value,"action");break;case"effect":for(let n of e.args)n.isPath?this.validatePath(n.value):this.analyzeExpr(n.value,"action");break;case"include":case"fail":case"stop":break}}analyzeExpr(e,n){switch(e.kind){case"identifier":this.checkIdentifier(e.name,e.location,n);break;case"systemIdent":this.checkSystemIdent(e.path,e.location,n);break;case"propertyAccess":this.analyzeExpr(e.object,n);break;case"indexAccess":this.analyzeExpr(e.object,n),this.analyzeExpr(e.index,n);break;case"functionCall":for(let r of e.args)this.analyzeExpr(r,n);break;case"binary":this.analyzeExpr(e.left,n),this.analyzeExpr(e.right,n);break;case"unary":this.analyzeExpr(e.operand,n);break;case"ternary":this.analyzeExpr(e.condition,n),this.analyzeExpr(e.consequent,n),this.analyzeExpr(e.alternate,n);break;case"objectLiteral":for(let r of e.properties)this.analyzeExpr(r.value,n);break;case"arrayLiteral":for(let r of e.elements)this.analyzeExpr(r,n);break;case"iterationVar":break;case"literal":break}}checkIdentifier(e,n,r){let o=this.currentScope?.lookup(e);if(!o){this.error(`Undefined identifier '${e}'`,n,"E_UNDEFINED");return}r==="computed"&&o.kind==="param"&&this.error(`Cannot access parameter '${e}' in computed expression`,n,"E_INVALID_ACCESS")}checkSystemIdent(e,n,r){let[o,...i]=e;if(o==="system"&&r==="computed"&&this.error("Cannot use $system.* in computed expressions (non-deterministic)",n,"E001"),o==="system"){let a=["uuid","timestamp","time.now","random"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid system value '$system.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}if(o==="meta"){let a=["intentId","actionName","timestamp"],s=i.join(".");s&&!a.includes(s)&&this.error(`Invalid meta value '$meta.${s}'. Valid values: ${a.join(", ")}`,n,"E003")}}validatePath(e){if(!e||!e.segments)return;let n=e.segments[0];n?.kind==="propertySegment"&&(this.currentScope?.lookup(n.name)||this.error(`Undefined identifier '${n.name}' in path`,e.location,"E_UNDEFINED"))}defineSymbol(e){if(this.currentScope){if(this.currentScope.isDefined(e.name)){this.error(`Duplicate identifier '${e.name}'`,e.location,"E_DUPLICATE");return}this.currentScope.define(e)}}error(e,n,r){this.diagnostics.push({severity:"error",code:r,message:e,location:n})}};function Ut(t){return new rt().analyze(t)}function D(t,e,n,r){return{severity:"error",code:t,message:e,location:n,...r}}function qt(t,e,n,r){return{severity:"warning",code:t,message:e,location:n,...r}}function da(t,e,n){return{severity:"info",code:t,message:e,location:n}}function tr(t){return t.severity==="error"}function pa(t){return t.some(tr)}function ua(t,e){return t.filter(n=>n.severity===e)}var Vt=new Set(["eq","neq","gt","gte","lt","lte","and","or","not","isNull","isNotNull","hasKey","startsWith","endsWith","strIncludes","includes","every","some","existsById"]),Ht=new Set(["add","sub","mul","div","mod","absDiff","abs","clamp","floor","ceil","round","sqrt","pow","len","strlen","indexOf","streak","sum","min","max","toNumber"]),Kt=new Set(["trim","lower","upper","concat","typeof","toString","substring","substr","replace"]),nr=new Set(["keys","values","entries","merge","filter","map","append","reverse","unique","flat","split","fromEntries"]),rr=new Set(["updateById","removeById"]);function De(t){let e=new Map,n=new Map,r=new Map;for(let o of t.types)r.set(o.name,o);for(let o of t.members){if(o.kind==="state"){for(let i of o.fields)e.set(i.name,i.typeExpr);continue}o.kind==="computed"&&n.set(o.name,o)}return{stateTypes:e,computedDecls:n,typeDefs:r,computedTypeCache:new Map,computedTypeInFlight:new Set}}function Oe(t){let e=new Map;for(let n of t)e.set(n.name,n.typeExpr);return e}function y(t,e,n){switch(t.kind){case"literal":return Er(t.value,t.location);case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??or(t.name,n);case"propertyAccess":return Z(y(t.object,e,n),t.property,n);case"indexAccess":return Ne(y(t.object,e,n),n);case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let o=y(r.value,e,n);return o?{kind:"typeField",name:r.key,typeExpr:o,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{let r=w(t.elements.map(o=>y(o,e,n)),t.location);return r?{kind:"arrayType",elementType:r,location:t.location}:null}case"unary":return ir(t);case"binary":return ar(t,e,n);case"ternary":return w([y(t.consequent,e,n),y(t.alternate,e,n)],t.location);case"functionCall":return sr(t,e,n);case"systemIdent":return null;case"iterationVar":return e.get("$item")??null}}function G(t,e,n){let r=y(t,e,n);if(r)return Wt(r,n);switch(t.kind){case"literal":return"primitive";case"objectLiteral":case"arrayLiteral":return"nonprimitive";case"binary":return t.operator==="??"?Te([G(t.left,e,n),G(t.right,e,n)]):t.operator==="=="||t.operator==="!="||t.operator==="+"||t.operator==="-"||t.operator==="*"||t.operator==="/"||t.operator==="%"||t.operator==="<"||t.operator==="<="||t.operator===">"||t.operator===">="||t.operator==="&&"||t.operator==="||"?"primitive":"unknown";case"unary":return"primitive";case"ternary":return Te([G(t.consequent,e,n),G(t.alternate,e,n)]);case"functionCall":return nr.has(t.name)?"nonprimitive":Vt.has(t.name)||Ht.has(t.name)||Kt.has(t.name)||t.name==="toBoolean"?"primitive":(t.name==="cond"||t.name==="if")&&t.args.length>=3?Te([G(t.args[1],e,n),G(t.args[2],e,n)]):t.name==="coalesce"?Te(t.args.map(o=>G(o,e,n))):"unknown";case"identifier":case"propertyAccess":case"indexAccess":case"systemIdent":case"iterationVar":return"unknown"}}function Wt(t,e){let n=S(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name==="object"?"nonprimitive":n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?"primitive":"unknown";case"literalType":return"primitive";case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":return Te(n.types.map(r=>Wt(r,e)))}}function S(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),S(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Z(t,e,n){let r=S(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(i=>i.name===e)?.typeExpr??null;if(r.kind==="unionType"){let o=r.types.filter(i=>!U(i)).map(i=>Z(i,e,n)).filter(i=>i!==null);return w(o,r.location)}return null}function Ne(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType"){let r=n.types.filter(o=>!U(o)).map(o=>Ne(o,e)).filter(o=>o!==null);return w(r,n.location)}return null}function B(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="unionType"){let r=n.types.filter(o=>!U(o)).map(o=>B(o,e)).filter(o=>o!==null);return w(r,n.location)}return null}function Re(t,e){let n=S(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number";case"literalType":return typeof n.value=="string"||typeof n.value=="number";case"unionType":return n.types.length>0&&n.types.every(r=>Re(r,e));default:return!1}}function U(t){return t.kind==="simpleType"&&t.name==="null"||t.kind==="literalType"&&t.value===null}function or(t,e){if(e.computedTypeCache.has(t))return e.computedTypeCache.get(t)??null;let n=e.computedDecls.get(t);if(!n||e.computedTypeInFlight.has(t))return null;e.computedTypeInFlight.add(t);let r=y(n.expression,new Map,e);return e.computedTypeInFlight.delete(t),e.computedTypeCache.set(t,r),r}function ir(t){return t.operator==="!"?P("boolean",t.location):P("number",t.location)}function ar(t,e,n){switch(t.operator){case"==":case"!=":case"<":case"<=":case">":case">=":case"&&":case"||":return P("boolean",t.location);case"+":case"-":case"*":case"/":case"%":return P("number",t.location);case"??":return w([y(t.left,e,n),y(t.right,e,n)],t.location)}}function sr(t,e,n){if(Vt.has(t.name))return P("boolean",t.location);if(Ht.has(t.name))return P("number",t.location);if(t.name==="idiv")return w([P("number",t.location),P("null",t.location)],t.location);if(Kt.has(t.name))return P("string",t.location);if(t.name==="toBoolean")return P("boolean",t.location);if(t.name==="findById"&&t.args.length>=1){let r=B(y(t.args[0],e,n),n);return r?w([r,P("null",t.location)],t.location):null}if(t.name==="find"&&t.args.length>=1){let r=B(y(t.args[0],e,n),n);return r?w([r,P("null",t.location)],t.location):null}if(t.name==="filter"&&t.args.length>=1)return y(t.args[0],e,n);if(t.name==="map"&&t.args.length>=2){let r=y(t.args[0],e,n),o=B(r,n);if(!o)return null;let i=y(t.args[1],kr(e,o),n);return i?{kind:"arrayType",elementType:i,location:t.location}:null}if((t.name==="first"||t.name==="last")&&t.args.length>=1)return B(y(t.args[0],e,n),n);if(t.name==="at"&&t.args.length>=1)return Ne(y(t.args[0],e,n),n);if(t.name==="field"&&t.args.length>=2){let r=Tr(t.args[1]);return r?Z(y(t.args[0],e,n),r,n):null}return rr.has(t.name)&&t.args.length>=1?y(t.args[0],e,n):(t.name==="cond"||t.name==="if")&&t.args.length>=3?w([y(t.args[1],e,n),y(t.args[2],e,n)],t.location):t.name==="coalesce"?yr(t,e,n):t.name==="match"?cr(t,e,n):t.name==="argmax"||t.name==="argmin"?lr(t,e,n):t.name==="slice"&&t.args.length>=1?y(t.args[0],e,n):t.name==="split"?{kind:"arrayType",elementType:P("string",t.location),location:t.location}:t.name==="keys"?{kind:"arrayType",elementType:P("string",t.location),location:t.location}:t.name==="values"&&t.args.length>=1?gr(t,e,n):null}function Te(t){let e=!1;for(let n of t){if(n==="nonprimitive")return"nonprimitive";n==="unknown"&&(e=!0)}return e?"unknown":"primitive"}function w(t,e){let n=t.filter(i=>i!==null);if(n.length===0)return null;if(n.length===1)return n[0];let r=[],o=new Set;for(let i of n){let a=JSON.stringify(i);o.has(a)||(o.add(a),r.push(i))}return r.length===1?r[0]:{kind:"unionType",types:r,location:e}}function cr(t,e,n){if(t.args.length<3)return null;let r=[];for(let o=1;o<t.args.length-1;o+=1){let i=t.args[o];if(i.kind!=="arrayLiteral"||i.elements.length!==2)return null;r.push(y(i.elements[1],e,n))}return r.push(y(t.args[t.args.length-1],e,n)),w(r,t.location)}function lr(t,e,n){if(t.args.length<2)return null;let r=[];for(let i=0;i<t.args.length-1;i+=1){let a=t.args[i];if(a.kind!=="arrayLiteral"||a.elements.length!==3)return null;r.push(y(a.elements[0],e,n))}let o=w(r,t.location);return o?ur(t,e,n)?o:w([o,P("null",t.location)],t.location):null}var dr=Symbol("arg-selection:other-string"),pr=Symbol("arg-selection:other-number");function ur(t,e,n){let r=[];for(let c=0;c<t.args.length-1;c+=1){let l=t.args[c];if(l.kind!=="arrayLiteral"||l.elements.length!==3)return!1;r.push(l.elements[1])}let o=new Map;for(let c of r)if(!ie(c,e,n,o))return!1;let i=[...o.values()].map(c=>({key:c.key,values:mr(c,n)}));if(i.some(c=>c.values===null||c.values.length===0))return!1;let a=1;for(let c of i)if(a*=c.values.length,a>256)return!1;let s=new Map;return Yt(i,0,s,()=>r.some(c=>F(c,s)===!0))}function Yt(t,e,n,r){if(e>=t.length)return r();let o=t[e];for(let i of o.values)if(n.set(o.key,i),!Yt(t,e+1,n,r))return n.delete(o.key),!1;return n.delete(o.key),!0}function ie(t,e,n,r){switch(t.kind){case"literal":return t.literalType==="boolean";case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":return fr(t,e,n,r);case"unary":return t.operator==="!"&&ie(t.operand,e,n,r);case"binary":return t.operator==="&&"||t.operator==="||"?ie(t.left,e,n,r)&&ie(t.right,e,n,r):t.operator==="=="||t.operator==="!="?zt(t.left,t.right,e,n,r):!1;case"functionCall":switch(t.name){case"and":case"or":return t.args.every(o=>ie(o,e,n,r));case"not":return t.args.length===1&&ie(t.args[0],e,n,r);case"eq":case"neq":return t.args.length===2&&zt(t.args[0],t.args[1],e,n,r);case"isNull":case"isNotNull":return t.args.length===1&&ot(t.args[0],e,n,r,null);default:return!1}default:return!1}}function fr(t,e,n,r){let o=ke(t),i=y(t,e,n);return!o||!i||!Xt(i,n)||at(t,e,n)?!1:(r.get(o)||r.set(o,{key:o,typeExpr:i,comparedLiterals:[]}),!0)}function zt(t,e,n,r,o){let i=it(t),a=it(e);return i!==void 0&&a!==void 0?!0:a!==void 0?ot(t,n,r,o,a):i!==void 0?ot(e,n,r,o,i):!1}function ot(t,e,n,r,o){let i=ke(t),a=y(t,e,n);if(!i||!a||!Jt(a,n)||at(t,e,n))return!1;let s=r.get(i);return s?(s.comparedLiterals.some(c=>Object.is(c,o))||s.comparedLiterals.push(o),!0):(r.set(i,{key:i,typeExpr:a,comparedLiterals:[o]}),!0)}function mr(t,e){let n=[],r=!1,o=a=>{n.some(s=>Object.is(s,a))||n.push(a)},i=a=>{let s=S(a,e);if(!s||r){r=!0;return}switch(s.kind){case"literalType":o(s.value);return;case"simpleType":switch(s.name){case"boolean":o(!0),o(!1);return;case"string":for(let c of t.comparedLiterals)typeof c=="string"&&o(c);o(dr);return;case"number":for(let c of t.comparedLiterals)typeof c=="number"&&o(c);o(pr);return;case"null":o(null);return;default:r=!0;return}case"unionType":for(let c of s.types)i(c);return;default:r=!0}};return i(t.typeExpr),r||n.length===0?null:n}function F(t,e){switch(t.kind){case"literal":return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0;case"identifier":case"iterationVar":case"propertyAccess":case"indexAccess":{let n=ke(t);return n?e.get(n):void 0}case"unary":{let n=F(t.operand,e);return t.operator==="!"&&typeof n=="boolean"?!n:void 0}case"binary":{let n=F(t.left,e),r=F(t.right,e);switch(t.operator){case"&&":return typeof n=="boolean"&&typeof r=="boolean"?n&&r:void 0;case"||":return typeof n=="boolean"&&typeof r=="boolean"?n||r:void 0;case"==":return n!==void 0&&r!==void 0?Object.is(n,r):void 0;case"!=":return n!==void 0&&r!==void 0?!Object.is(n,r):void 0;default:return}}case"functionCall":switch(t.name){case"and":{let n=t.args.map(r=>F(r,e));return n.every(r=>typeof r=="boolean")?n.every(Boolean):void 0}case"or":{let n=t.args.map(r=>F(r,e));return n.every(r=>typeof r=="boolean")?n.some(Boolean):void 0}case"not":{let n=t.args.length===1?F(t.args[0],e):void 0;return typeof n=="boolean"?!n:void 0}case"eq":case"neq":{if(t.args.length!==2)return;let n=F(t.args[0],e),r=F(t.args[1],e);return n===void 0||r===void 0?void 0:t.name==="eq"?Object.is(n,r):!Object.is(n,r)}case"isNull":{if(t.args.length!==1)return;let n=F(t.args[0],e);return n===void 0?void 0:n===null}case"isNotNull":{if(t.args.length!==1)return;let n=F(t.args[0],e);return n===void 0?void 0:n!==null}case"cond":case"if":{if(t.args.length!==3)return;let n=F(t.args[0],e);return typeof n!="boolean"?void 0:F(n?t.args[1]:t.args[2],e)}default:return}default:return}}function ke(t){switch(t.kind){case"identifier":return`id:${t.name}`;case"iterationVar":return"$item";case"propertyAccess":{let e=ke(t.object);return e?`${e}.${t.property}`:null}case"indexAccess":{let e=ke(t.object),n=it(t.index);return e&&n!==void 0?`${e}[${JSON.stringify(n)}]`:null}default:return null}}function at(t,e,n){switch(t.kind){case"propertyAccess":return st(y(t.object,e,n),n)||hr(t.object,t.property,e,n)||at(t.object,e,n);case"indexAccess":return!0;default:return!1}}function hr(t,e,n,r){return Qt(y(t,n,r),e,r)}function Qt(t,e,n){let r=S(t,n);if(!r)return!0;if(r.kind==="objectType"){let o=r.fields.find(i=>i.name===e);return!o||o.optional}if(r.kind==="unionType"){let o=r.types.filter(i=>!U(i));return o.length===0||o.some(i=>Qt(i,e,n))}return!0}function Xt(t,e){let n=S(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="boolean";case"literalType":return typeof n.value=="boolean";case"unionType":return n.types.length>0&&n.types.every(r=>Xt(r,e));default:return!1}}function Jt(t,e){let n=S(t,e);if(!n)return!1;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null";case"literalType":return typeof n.value=="string"||typeof n.value=="number"||typeof n.value=="boolean"||n.value===null;case"unionType":return n.types.length>0&&n.types.every(r=>Jt(r,e));default:return!1}}function it(t){if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function yr(t,e,n){let r=t.args.map(a=>y(a,e,n));if(r.some(a=>a===null))return w(r,t.location);let o=r.map(a=>en(a,n)).filter(a=>a!==null);if(o.length===0)return w(r,t.location);let i=[...o];return r.every(a=>a!==null&&st(a,n))&&i.push(P("null",t.location)),w(i,t.location)}function gr(t,e,n){if(t.args.length<1)return null;let r=Zt(y(t.args[0],e,n),n);return r?{kind:"arrayType",elementType:r,location:t.location}:null}function Zt(t,e){let n=S(t,e);return n?n.kind==="recordType"?n.valueType:n.kind==="objectType"?w(n.fields.map(r=>r.typeExpr),n.location):n.kind==="unionType"?w(n.types.filter(r=>!U(r)).map(r=>Zt(r,e)),n.location):null:null}function en(t,e){let n=S(t,e);if(!n||U(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(o=>en(o,e)).filter(o=>o!==null);return r.length===0?null:w(r,n.location)}function st(t,e){let n=S(t,e);return!n||U(n)?!0:n.kind!=="unionType"?!1:n.types.some(r=>st(r,e))}function Er(t,e){return{kind:"literalType",value:t,location:e}}function P(t,e){return{kind:"simpleType",name:t,location:e}}function Tr(t){return t.kind==="literal"&&typeof t.value=="string"?t.value:null}function kr(t,e){let n=new Map(t);return n.set("$item",e),n}var Nr=new Set(["findById","existsById"]),lt=new Set(["updateById","removeById"]),br=new Set([...Nr,...lt]);function W(t,e,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;e.has(i)||(e.add(i),t.push(D(n,r,o)))}function tn(t){let e=[],n=new Set,r=De(t.domain);Ar(t.domain,r,e,n);for(let o of t.domain.members)switch(o.kind){case"computed":N(o.expression,"computed",new Map,r,e,n,0);break;case"action":{let i=Oe(o.params);Sr(o,i,r,e,n);break}case"state":case"flow":break}return e}function Sr(t,e,n,r,o){t.available&&N(t.available,"available",e,n,r,o,0),t.dispatchable&&N(t.dispatchable,"dispatchable",e,n,r,o,0);for(let i of t.body)xr(i,e,n,r,o)}function xr(t,e,n,r,o){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"include":break}}function ae(t,e,n,r,o){switch(t.kind){case"when":N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"once":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"onceIntent":t.condition&&N(t.condition,"guard",e,n,r,o,0);for(let i of t.body)ae(i,e,n,r,o);break;case"patch":t.value&&N(t.value,"patch",e,n,r,o,0);break;case"effect":for(let i of t.args)i.isPath||N(i.value,"action",e,n,r,o,0);break;case"fail":t.message&&N(t.message,"action",e,n,r,o,0);break;case"include":case"stop":break}}function N(t,e,n,r,o,i,a){switch(t.kind){case"functionCall":{vr(t,e,n,r,o,i,a);let s=a+(lt.has(t.name)?1:0);for(let c of t.args)N(c,e,n,r,o,i,s);break}case"binary":N(t.left,e,n,r,o,i,a),N(t.right,e,n,r,o,i,a);break;case"unary":N(t.operand,e,n,r,o,i,a);break;case"ternary":N(t.condition,e,n,r,o,i,a),N(t.consequent,e,n,r,o,i,a),N(t.alternate,e,n,r,o,i,a);break;case"propertyAccess":N(t.object,e,n,r,o,i,a);break;case"indexAccess":N(t.object,e,n,r,o,i,a),N(t.index,e,n,r,o,i,a);break;case"objectLiteral":for(let s of t.properties)N(s.value,e,n,r,o,i,a);break;case"arrayLiteral":for(let s of t.elements)N(s,e,n,r,o,i,a);break;case"literal":case"identifier":case"systemIdent":case"iterationVar":break}}function vr(t,e,n,r,o,i,a){if(!br.has(t.name)||t.args.length===0)return;lt.has(t.name)&&(e==="available"?W(o,i,"E035","updateById/removeById are not allowed in available conditions.",t.location):e==="dispatchable"?W(o,i,"E048","updateById/removeById are not allowed in dispatchable conditions.",t.location):e==="guard"?W(o,i,"E034","updateById/removeById are not allowed in guard conditions.",t.location):e!=="patch"&&W(o,i,"E031","updateById/removeById are only allowed in patch RHS.",t.location),a>0&&W(o,i,"E032","Nested transform primitives are not allowed.",t.location),e==="patch"&&!ct(t.args[0],r)&&W(o,i,"E033","Transform primitive collection argument must resolve to a state path.",t.args[0].location));let s=Cr(t.args[0],n,r);if(!s)return;let c=nn(s,r);if(!c){W(o,i,"E030","Collection element type must declare an 'id' field for entity primitives.",t.args[0].location);return}Re(c,r)||W(o,i,"E030a","Entity 'id' field must be string or number.",t.args[0].location)}function Ar(t,e,n,r){for(let o of t.members)if(o.kind==="state")for(let i of o.fields)wr(i,e,n,r)}function wr(t,e,n,r){if(!t.initializer||t.initializer.kind!=="arrayLiteral")return;let o=B(t.typeExpr,e);if(!o)return;let i=nn(o,e);if(!i||!Re(i,e))return;let a=new Map;for(let s of t.initializer.elements){if(s.kind!=="objectLiteral")continue;let c=s.properties.find(p=>p.key==="id");if(!c||c.value.kind!=="literal"||typeof c.value.value!="string"&&typeof c.value.value!="number")continue;let l=`${typeof c.value.value}:${String(c.value.value)}`;if(a.get(l)){W(n,r,"E030b","Duplicate '.id' values detected in state initializer.",c.value.location);continue}a.set(l,c.value.location)}}function Cr(t,e,n){return B(y(t,e,n),n)}function nn(t,e){return Z(t,"id",e)}function ct(t,e){switch(t.kind){case"identifier":return e.stateTypes.has(t.name);case"propertyAccess":return ct(t.object,e);case"indexAccess":return ct(t.object,e);default:return!1}}function rn(){return{inAction:!1,inGuard:!1,guardDepth:0,hasMarkerPatch:!1,currentActionParamTypes:new Map,diagnostics:[]}}var Pr=/\b(await(?:ing)?|wait(?:ing)?|pending)\b/i;function T(t,e){return{kind:"simpleType",name:t,location:e}}function q(t,e,n){let r=S(t,n),o=S(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=r.kind==="unionType"?r.types:[r],a=!1;for(let s of i){let c=o.types.map(l=>q(s,l,n));if(!c.includes(!0)){if(c.every(l=>l===!1))return!1;a=!0}}return a?null:!0}if(r.kind==="unionType"){let i=!1;for(let a of r.types){let s=q(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:q(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=q(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:q(r.valueType,o.valueType,n):null}function v(t,e){let n=S(t,e);if(!n)return"unknown";switch(n.kind){case"simpleType":return n.name;case"literalType":return JSON.stringify(n.value);case"arrayType":return`Array<${v(n.elementType,e)}>`;case"recordType":return`Record<${v(n.keyType,e)}, ${v(n.valueType,e)}>`;case"objectType":return`{ ${n.fields.map(r=>`${r.name}${r.optional?"?":""}: ${v(r.typeExpr,e)}`).join("; ")} }`;case"unionType":return n.types.map(r=>v(r,e)).join(" | ")}}function Le(t,e){let n=S(t,e);if(!n)return null;switch(n.kind){case"simpleType":return n.name==="string"||n.name==="number"||n.name==="boolean"||n.name==="null"?new Set([n.name]):n.name==="object"?"nonprimitive":null;case"literalType":return new Set([n.value===null?"null":typeof n.value]);case"arrayType":case"recordType":case"objectType":return"nonprimitive";case"unionType":{let r=new Set;for(let o of n.types){let i=Le(o,e);if(i===null)return null;if(i==="nonprimitive")return"nonprimitive";for(let a of i)r.add(a)}return r}}}function dt(t,e){let n=Le(t,e);if(n===null)return null;if(n==="nonprimitive")return"invalid";let r=[...n].filter(o=>o!=="null");return r.length!==1||n.has("null")?"invalid":r[0]}function an(t,e,n){let r=Le(t,n),o=Le(e,n);if(r===null||o===null)return null;if(r==="nonprimitive"||o==="nonprimitive")return!1;if(!(r instanceof Set)||!(o instanceof Set))return null;let i=[...r].filter(s=>s!=="null"),a=[...o].filter(s=>s!=="null");return i.length===0||a.length===0?!0:i.some(s=>a.includes(s))}function sn(t,e){let n=S(t,e);if(!n||U(n))return null;if(n.kind!=="unionType")return n;let r=n.types.map(a=>sn(a,e)).filter(a=>a!==null);if(r.length===0)return null;let o=[],i=new Set;for(let a of r){let s=JSON.stringify(a);i.has(s)||(i.add(s),o.push(a))}return o.length===1?o[0]:{kind:"unionType",types:o,location:n.location}}function pt(t,e,n){if(!t||!e)return null;let r=q(t,e,n);if(r===!0)return!0;let o=q(e,t,n);if(o===!0)return!0;let i=an(t,e,n);return i!==null?i:r===!1&&o===!1?!1:null}function ut(t,e,n){let r=S(t,n),o=S(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=!1;for(let a of o.types){if(U(a))continue;let s=ut(r,a,n);if(s===!0)return!0;s===null&&(i=!0)}return i?null:!1}if(r.kind==="unionType"){let i=!1;for(let a of r.types){let s=ut(a,o,n);if(s===!1)return!1;s===null&&(i=!0)}return i?null:!0}if(o.kind!=="objectType"||r.kind!=="objectType")return!1;for(let i of r.fields){let a=o.fields.find(c=>c.name===i.name);if(!a)return!1;let s=q(i.typeExpr,a.typeExpr,n);if(s!==!0)return s}return!0}function cn(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>cn(o,e));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"}function ln(t,e){let n=S(t,e);if(!n)return null;if(n.kind==="unionType"){let r=n.types.map(o=>ln(o,e));return r.every(o=>o===!0)?!0:r.some(o=>o===!1)?!1:null}return n.kind==="arrayType"||n.kind==="recordType"||n.kind==="objectType"?!0:n.kind==="literalType"?typeof n.value=="string":n.kind==="simpleType"?n.name==="string"||n.name==="object":!1}function Ir(t,e){let n=new Map(t);return n.set("$item",e),n}function on(t){let e=Fe(t);if(typeof e=="number")return e;if(t.kind==="literal")return t.literalType==="null"?null:typeof t.value=="string"||typeof t.value=="number"||typeof t.value=="boolean"?t.value:void 0}function Fe(t){if(t.kind==="literal"&&t.literalType==="number"&&typeof t.value=="number")return t.value;if(t.kind==="unary"&&t.operator==="-"){let e=Fe(t.operand);return typeof e=="number"?-e:void 0}}function Mr(t,e){let[n,...r]=t.segments;if(!n||n.kind!=="propertySegment")return null;let o=e.stateTypes.get(n.name)??null;for(let i of r){if(!o)return null;o=i.kind==="propertySegment"?Z(o,i.name,e):Ne(o,e)}return o}function Dr(t){let e="";for(let[n,r]of t.segments.entries()){if(r.kind==="propertySegment"){e+=n===0?r.name:`.${r.name}`;continue}r.index.kind==="literal"?e+=`[${JSON.stringify(r.index.value)}]`:e+="[*]"}return e}var ft=class{ctx=rn();symbols=null;validate(e){return this.ctx=rn(),this.symbols=De(e.domain),this.validateDomain(e.domain),this.symbols=null,{valid:!this.ctx.diagnostics.some(n=>n.severity==="error"),diagnostics:this.ctx.diagnostics}}validateDomain(e){e.name.startsWith("__")&&this.error("Domain name cannot start with '__' (reserved prefix)",e.location,"E_RESERVED_NAME");for(let n of e.members)switch(n.kind){case"state":this.validateState(n);break;case"computed":this.validateExpr(n.expression,"computed");break;case"action":this.validateAction(n);break;case"flow":break}}validateState(e){let n=new Map;for(let r of e.fields){let o=n.get(r.name);o?this.error(`Duplicate state field '${r.name}'. First declared at line ${o.start.line}`,r.location,"E_DUPLICATE_FIELD"):n.set(r.name,r.location),this.validateStateField(r)}}validateStateField(e){this.checkAnonymousObjectType(e.typeExpr,e.location),e.initializer&&this.validateStateInitializer(e.initializer)}validateStateInitializer(e){switch(e.kind){case"literal":return;case"identifier":case"iterationVar":this.error("State initializers must be compile-time constants",e.location,"E042");return;case"systemIdent":e.path[0]==="system"?this.error("$system.* cannot be used in state initializers",e.location,"E002"):this.error("State initializers must be compile-time constants",e.location,"E042");return;case"objectLiteral":for(let n of e.properties)this.validateStateInitializer(n.value);return;case"arrayLiteral":for(let n of e.elements)this.validateStateInitializer(n);return;case"functionCall":{let n=this.ctx.diagnostics.length;for(let r of e.args)this.validateStateInitializer(r);this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"binary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.left),this.validateStateInitializer(e.right),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"unary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.operand),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"ternary":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.condition),this.validateStateInitializer(e.consequent),this.validateStateInitializer(e.alternate),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"propertyAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}case"indexAccess":{let n=this.ctx.diagnostics.length;this.validateStateInitializer(e.object),this.validateStateInitializer(e.index),this.ctx.diagnostics.length===n&&this.error("State initializers must be compile-time constants",e.location,"E042");return}}}checkAnonymousObjectType(e,n){switch(e.kind){case"objectType":this.ctx.diagnostics.push(qt("W012","Anonymous object type in state field. Use a named type declaration instead: type MyType = { ... }",e.location,{suggestion:"Define this type using 'type TypeName = { ... }' and reference it by name"}));for(let r of e.fields)this.checkAnonymousObjectType(r.typeExpr,n);break;case"arrayType":this.checkAnonymousObjectType(e.elementType,n);break;case"recordType":this.checkAnonymousObjectType(e.keyType,n),this.checkAnonymousObjectType(e.valueType,n);break;case"unionType":for(let r of e.types)this.checkAnonymousObjectType(r,n);break}}validateAction(e){this.ctx.inAction=!0,this.ctx.currentActionParamTypes=Oe(e.params),e.available&&this.validateAvailableExpr(e.available),e.dispatchable&&this.validateDispatchableExpr(e.dispatchable);for(let n of e.body)this.validateGuardedStmt(n);this.ctx.inAction=!1,this.ctx.currentActionParamTypes=new Map}validateAvailableExpr(e){switch(e.kind){case"identifier":this.ctx.currentActionParamTypes.has(e.name)&&this.error("Action parameters cannot be used in available condition",e.location,"E005");break;case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in available condition (must be pure expression)",e.location,"E005"),e.path[0]==="input"&&this.error("$input.* cannot be used in available condition (parameters not available at availability check)",e.location,"E005"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in available condition (availability is schema-context only)",e.location,"E005");break;case"functionCall":for(let n of e.args)this.validateAvailableExpr(n);break;case"binary":this.validateAvailableExpr(e.left),this.validateAvailableExpr(e.right);break;case"unary":this.validateAvailableExpr(e.operand);break;case"ternary":this.validateAvailableExpr(e.condition),this.validateAvailableExpr(e.consequent),this.validateAvailableExpr(e.alternate);break;case"propertyAccess":this.validateAvailableExpr(e.object);break;case"indexAccess":this.validateAvailableExpr(e.object),this.validateAvailableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateAvailableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateAvailableExpr(n);break}}validateDispatchableExpr(e){switch(e.kind){case"systemIdent":e.path[0]==="system"&&this.error("$system.* cannot be used in dispatchable condition (must be pure expression)",e.location,"E047"),e.path[0]==="input"&&this.error("$input.* cannot be used in dispatchable condition (use bare action parameter names)",e.location,"E047"),e.path[0]==="meta"&&this.error("$meta.* cannot be used in dispatchable condition (dispatchability is snapshot + bound-input only)",e.location,"E047");break;case"functionCall":for(let n of e.args)this.validateDispatchableExpr(n);break;case"binary":this.validateDispatchableExpr(e.left),this.validateDispatchableExpr(e.right);break;case"unary":this.validateDispatchableExpr(e.operand);break;case"ternary":this.validateDispatchableExpr(e.condition),this.validateDispatchableExpr(e.consequent),this.validateDispatchableExpr(e.alternate);break;case"propertyAccess":this.validateDispatchableExpr(e.object);break;case"indexAccess":this.validateDispatchableExpr(e.object),this.validateDispatchableExpr(e.index);break;case"objectLiteral":for(let n of e.properties)this.validateDispatchableExpr(n.value);break;case"arrayLiteral":for(let n of e.elements)this.validateDispatchableExpr(n);break}}validateGuardedStmt(e){switch(e.kind){case"when":this.validateWhen(e);break;case"once":this.validateOnce(e);break;case"onceIntent":this.validateOnceIntent(e);break;case"patch":this.validatePatch(e);break;case"effect":this.validateEffect(e);break;case"include":break;case"fail":this.validateFail(e);break;case"stop":this.validateStop(e);break}}validateWhen(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.validateCondition(e.condition,"when");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnce(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,this.ctx.hasMarkerPatch=!1,e.condition&&this.validateCondition(e.condition,"once");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validateOnceIntent(e){this.ctx.inGuard=!0,this.ctx.guardDepth++,e.condition&&this.validateCondition(e.condition,"onceIntent");for(let n of e.body)this.validateGuardedStmt(n);this.ctx.guardDepth--,this.ctx.guardDepth===0&&(this.ctx.inGuard=!1)}validatePatch(e){if(this.ctx.inGuard||this.error("Patch must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_PATCH"),e.value){let n=this.ctx.diagnostics.length,r=this.validateExpr(e.value,"action");if(!this.symbols||n!==this.ctx.diagnostics.length)return;let o=Mr(e.path,this.symbols);if(!o||!r)return;(e.op==="merge"?ut(r,o,this.symbols):q(r,o,this.symbols))===!1&&this.error(`Patch value for '${Dr(e.path)}' must be assignable to ${v(o,this.symbols)}, got ${v(r,this.symbols)}`,e.value.location,"E_TYPE_MISMATCH")}}validateEffect(e){this.ctx.inGuard||this.error("Effect must be inside a guard (when, once, or onceIntent)",e.location,"E_UNGUARDED_EFFECT");for(let n of e.args)n.isPath||this.validateExpr(n.value,"action")}validateFail(e){this.ctx.inGuard||this.error("fail must be inside a guard (when, once, or onceIntent)",e.location,"E006"),e.message&&this.validateExpr(e.message,"action")}validateStop(e){this.ctx.inGuard||this.error("stop must be inside a guard (when, once, or onceIntent)",e.location,"E007"),Pr.test(e.reason)&&this.error("stop message suggests waiting/pending - use 'Already processed' style instead",e.location,"E008")}validateCondition(e,n){let r=this.ctx.diagnostics.length,o=this.validateExpr(e,"action");r===this.ctx.diagnostics.length&&this.requireAssignable(o,T("boolean",e.location),e.location,`Condition in ${n} must evaluate to boolean`)}validateExpr(e,n,r=this.ctx.currentActionParamTypes){switch(e.kind){case"functionCall":return this.validateFunctionCall(e,n,r),this.inferType(e,r);case"binary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(e.left,n,r),a=this.validateExpr(e.right,n,r);if(!(o!==this.ctx.diagnostics.length))switch(e.operator){case"==":case"!=":this.validatePrimitiveEquality(e.left,e.right,i,a,e.location);break;case"<":case"<=":case">":case">=":this.requireAssignable(i,T("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"&&":case"||":this.requireAssignable(i,T("boolean",e.left.location),e.left.location,`Operator '${e.operator}' requires a boolean left operand`),this.requireAssignable(a,T("boolean",e.right.location),e.right.location,`Operator '${e.operator}' requires a boolean right operand`);break;case"+":case"-":case"*":case"/":case"%":this.requireAssignable(i,T("number",e.left.location),e.left.location,`Operator '${e.operator}' requires a numeric left operand`),this.requireAssignable(a,T("number",e.right.location),e.right.location,`Operator '${e.operator}' requires a numeric right operand`);break;case"??":this.validateCoalesceTypes([i,a],e.location);break}return this.inferType(e,r)}case"unary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(e.operand,n,r);return o===this.ctx.diagnostics.length&&this.requireAssignable(i,T(e.operator==="!"?"boolean":"number",e.operand.location),e.operand.location,e.operator==="!"?"Unary '!' requires a boolean operand":"Unary '-' requires a numeric operand"),this.inferType(e,r)}case"ternary":{let o=this.ctx.diagnostics.length,i=this.validateExpr(e.condition,n,r);return this.validateExpr(e.consequent,n,r),this.validateExpr(e.alternate,n,r),o===this.ctx.diagnostics.length&&this.requireAssignable(i,T("boolean",e.condition.location),e.condition.location,"Ternary condition must evaluate to boolean"),this.inferType(e,r)}case"propertyAccess":return this.validateExpr(e.object,n,r),this.inferType(e,r);case"indexAccess":return this.validateExpr(e.object,n,r),this.validateExpr(e.index,n,r),this.inferType(e,r);case"objectLiteral":for(let o of e.properties)this.validateExpr(o.value,n,r);return this.inferType(e,r);case"arrayLiteral":for(let o of e.elements)this.validateExpr(o,n,r);return this.inferType(e,r);case"systemIdent":return this.inferType(e,r);case"literal":case"identifier":case"iterationVar":return this.inferType(e,r)}}validateFunctionCall(e,n,r){let{name:o,args:i,location:a}=e;if(["reduce","fold","foldl","foldr","scan"].includes(o)&&this.error(`Function '${o}' is forbidden. Use sum(), min(), max() for aggregation instead`,a,"E011"),["sum","min","max"].includes(o)&&i.length===1){n==="action"&&this.error(`Primitive aggregation '${o}()' can only be used in computed expressions, not in actions`,a,"E009");let c=i[0];c.kind==="functionCall"&&this.error(`Primitive aggregation '${o}()' does not allow composition. Use a direct reference, not '${c.name}()'`,a,"E010")}switch(o){case"eq":case"neq":break;case"len":case"sum":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"gt":case"gte":case"lt":case"lte":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"not":case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":case"isNull":case"isNotNull":case"trim":case"lower":case"upper":case"strlen":case"keys":case"values":case"entries":case"first":case"last":case"typeof":case"toString":case"toNumber":case"toBoolean":case"reverse":case"unique":case"flat":case"fromEntries":i.length!==1&&this.error(`Function '${o}' expects 1 argument, got ${i.length}`,a,"E_ARG_COUNT");break;case"pow":case"findById":case"existsById":case"filter":case"map":case"find":case"every":case"some":case"at":case"includes":case"field":case"hasKey":case"pick":case"omit":case"startsWith":case"endsWith":case"strIncludes":case"indexOf":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"updateById":case"clamp":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"removeById":case"streak":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"slice":case"substring":case"substr":case"replace":(i.length<2||i.length>3)&&this.error(`Function '${o}' expects 2-3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"split":i.length!==2&&this.error(`Function '${o}' expects 2 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;case"and":case"or":case"concat":case"min":case"max":case"merge":case"coalesce":case"append":i.length<1&&this.error(`Function '${o}' expects at least 1 argument`,a,"E_ARG_COUNT");break;case"match":i.length<3&&this.error("Function 'match' expects a selector, at least one [key, value] arm, and a default value",a,"E050");break;case"argmax":case"argmin":i.length<2&&this.error(`Function '${o}' expects at least one [label, eligible, score] candidate and a tie-break literal`,a,"E052");break;case"if":case"cond":i.length!==3&&this.error(`Function '${o}' expects 3 arguments, got ${i.length}`,a,"E_ARG_COUNT");break;default:this.error(`Unknown function '${o}'. Check spelling or see MEL builtin function reference`,a,"E_UNKNOWN_FN");break}let s=[];if(["filter","map","find","every","some"].includes(o)&&i.length>0){let c=this.validateExpr(i[0],n,r);s.push(c);let l=r;if(this.symbols){let d=B(c,this.symbols);d&&(l=Ir(r,d))}for(let d=1;d<i.length;d+=1)s.push(this.validateExpr(i[d],n,d===1?l:r))}else for(let c of i)s.push(this.validateExpr(c,n,r));if(this.symbols)switch(o){case"eq":case"neq":i.length===2&&this.validatePrimitiveEquality(i[0],i[1],s[0],s[1],a);break;case"add":case"sub":case"mul":case"div":case"mod":case"absDiff":case"idiv":case"pow":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"gt":case"gte":case"lt":case"lte":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`));break;case"and":case"or":for(let[c,l]of i.entries())this.requireAssignable(s[c],T("boolean",l.location),l.location,`Function '${o}' expects boolean arguments`);break;case"not":i.length===1&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,"Function 'not' expects a boolean argument");break;case"neg":case"abs":case"floor":case"ceil":case"round":case"sqrt":i.length===1&&this.requireAssignable(s[0],T("number",i[0].location),i[0].location,`Function '${o}' expects a numeric argument`);break;case"clamp":if(i.length===3){this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'clamp' expects a numeric first argument"),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,"Function 'clamp' expects a numeric second argument"),this.requireAssignable(s[2],T("number",i[2].location),i[2].location,"Function 'clamp' expects a numeric third argument");let c=Fe(i[1]),l=Fe(i[2]);typeof c=="number"&&typeof l=="number"&&c>l&&this.error("Function 'clamp' requires literal bounds in lo, hi order",a,"E049")}break;case"streak":i.length===2&&(this.requireAssignable(s[0],T("number",i[0].location),i[0].location,"Function 'streak' expects a numeric first argument"),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,"Function 'streak' expects a boolean second argument"));break;case"trim":case"lower":case"upper":case"strlen":i.length===1&&this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string argument`);break;case"startsWith":case"endsWith":case"strIncludes":case"indexOf":case"split":i.length===2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,`Function '${o}' expects a string second argument`));break;case"replace":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,"Function 'replace' expects a string first argument"),this.requireAssignable(s[1],T("string",i[1].location),i[1].location,"Function 'replace' expects a string second argument")),i.length===3&&this.requireAssignable(s[2],T("string",i[2].location),i[2].location,"Function 'replace' expects a string replacement argument");break;case"substring":case"substr":i.length>=2&&(this.requireAssignable(s[0],T("string",i[0].location),i[0].location,`Function '${o}' expects a string first argument`),this.requireAssignable(s[1],T("number",i[1].location),i[1].location,`Function '${o}' expects a numeric second argument`)),i.length===3&&this.requireAssignable(s[2],T("number",i[2].location),i[2].location,`Function '${o}' expects a numeric third argument`);break;case"len":i.length===1&&this.requireLenCompatible(s[0],i[0].location);break;case"filter":case"find":case"every":case"some":i.length===2&&(this.requireArrayCompatible(s[0],i[0].location,o),this.requireAssignable(s[1],T("boolean",i[1].location),i[1].location,`Function '${o}' requires a boolean-valued callback`));break;case"map":i.length===2&&this.requireArrayCompatible(s[0],i[0].location,o);break;case"coalesce":this.validateCoalesceTypes(s,a);break;case"match":this.validateMatchCall(i,s,a,r);break;case"argmax":case"argmin":this.validateArgSelectionCall(o,i,a,r);break;case"if":case"cond":i.length===3&&this.requireAssignable(s[0],T("boolean",i[0].location),i[0].location,`Function '${o}' expects a boolean condition`);break}}validatePrimitiveEquality(e,n,r,o,i){if(!this.symbols)return;if(e.kind==="objectLiteral"||e.kind==="arrayLiteral"||n.kind==="objectLiteral"||n.kind==="arrayLiteral"){this.error("eq/neq operands must be compatible primitive types, not object or array literals",i,"E_TYPE_MISMATCH");return}an(r,o,this.symbols)===!1&&this.error(`eq/neq operands must be compatible primitive types, got ${v(r,this.symbols)} and ${v(o,this.symbols)}`,i,"E_TYPE_MISMATCH")}inferType(e,n){return this.symbols?y(e,n,this.symbols):null}requireAssignable(e,n,r,o){if(!this.symbols||!e)return;q(e,n,this.symbols)===!1&&this.error(`${o}, got ${v(e,this.symbols)}`,r,"E_TYPE_MISMATCH")}requireArrayCompatible(e,n,r){if(!this.symbols||!e)return;cn(e,this.symbols)===!1&&this.error(`Function '${r}' expects an array first argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}requireLenCompatible(e,n){if(!this.symbols||!e)return;ln(e,this.symbols)===!1&&this.error(`Function 'len' expects a string, array, object, or record argument, got ${v(e,this.symbols)}`,n,"E_TYPE_MISMATCH")}validateCoalesceTypes(e,n){if(!this.symbols)return;let r=e.map(o=>sn(o,this.symbols)).filter(o=>o!==null);for(let o=0;o<r.length;o+=1)for(let i=o+1;i<r.length;i+=1)if(pt(r[o],r[i],this.symbols)===!1){this.error(`coalesce arguments must have compatible non-null types, got ${v(r[o],this.symbols)} and ${v(r[i],this.symbols)}`,n,"E_TYPE_MISMATCH");return}}validateMatchCall(e,n,r,o){if(!this.symbols||e.length<3)return;let i=n[0],a=dt(i,this.symbols);a==="invalid"&&this.error(`Function 'match' requires a selector of type string, number, or boolean, got ${v(i,this.symbols)}`,e[0].location,"E_TYPE_MISMATCH");let s=new Set,c=[];for(let l=1;l<e.length-1;l+=1){let d=e[l];if(d.kind!=="arrayLiteral"||d.elements.length!==2){this.error("Function 'match' requires each arm to be an inline [key, value] array literal",d.location,"E050");continue}let[p,f]=d.elements,m=on(p);if(m==null)this.error("Function 'match' requires literal string, number, or boolean arm keys",p.location,"E050");else{let $=`${typeof m}:${String(m)}`;s.has($)?this.error(`Function 'match' has duplicate arm key ${JSON.stringify(m)}`,p.location,"E051"):s.add($)}let A=this.inferType(p,o),b=dt(A,this.symbols);(b==="invalid"||a!==null&&b!==null&&a!==b)&&this.error(`Function 'match' selector and arm keys must use the same primitive type, got ${v(i,this.symbols)} and ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"),c.push(this.inferType(f,o))}c.push(n[n.length-1]);for(let l=0;l<c.length;l+=1)for(let d=l+1;d<c.length;d+=1)if(pt(c[l],c[d],this.symbols)===!1){this.error(`Function 'match' arm values and default must have compatible types, got ${v(c[l],this.symbols)} and ${v(c[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}validateArgSelectionCall(e,n,r,o){if(!this.symbols||n.length<2)return;let i=n[n.length-1],a=on(i);a!=="first"&&a!=="last"&&this.error(`Function '${e}' requires a final tie-break literal of "first" or "last"`,i.location,"E052");let s=[],c=null;for(let l=0;l<n.length-1;l+=1){let d=n[l];if(d.kind!=="arrayLiteral"||d.elements.length!==3){this.error(`Function '${e}' requires inline [label, eligible, score] array literal candidates`,d.location,"E052");continue}let[p,f,m]=d.elements,A=this.inferType(p,o),b=dt(A,this.symbols);b==="invalid"?this.error(`Function '${e}' requires labels with exactly one primitive scalar type, got ${v(A,this.symbols)}`,p.location,"E_TYPE_MISMATCH"):c===null?c=b:b!==null&&b!==c&&this.error(`Function '${e}' candidate labels must share one primitive scalar type, got ${c} and ${b}`,p.location,"E_TYPE_MISMATCH"),this.requireAssignable(this.inferType(f,o),T("boolean",f.location),f.location,`Function '${e}' expects a boolean eligible value`),this.requireAssignable(this.inferType(m,o),T("number",m.location),m.location,`Function '${e}' expects a numeric score value`),s.push(A)}for(let l=0;l<s.length;l+=1)for(let d=l+1;d<s.length;d+=1)if(pt(s[l],s[d],this.symbols)===!1){this.error(`Function '${e}' candidate labels must have compatible scalar types, got ${v(s[l],this.symbols)} and ${v(s[d],this.symbols)}`,r,"E_TYPE_MISMATCH");return}}error(e,n,r){this.ctx.diagnostics.push({severity:"error",code:r,message:e,location:n})}warn(e,n,r){this.ctx.diagnostics.push({severity:"warning",code:r,message:e,location:n})}};function dn(t){let n=new ft().validate(t),r=tn(t),o=[...n.diagnostics,...r];return{valid:!o.some(i=>i.severity==="error"),diagnostics:o}}var mt={mode:"schema",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},ht={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!1},yt={mode:"action",allowSysPaths:{prefixes:["input"]},fnTableVersion:"1.0",allowItem:!1},gt={mode:"action",allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0",allowItem:!0},Or={allowSysPaths:{prefixes:["meta","input"]},fnTableVersion:"1.0"};var _=class extends Error{code;path;details;constructor(e,n,r){super(n),this.name="LoweringError",this.code=e,this.path=r?.path,this.details=r?.details}};function je(t,e,n){return new _("INVALID_KIND_FOR_CONTEXT",`Node kind '${t}' is not allowed in ${e} context`,{path:n,details:{kind:t,context:e}})}function g(t,e){return new _("UNKNOWN_CALL_FN",`Unknown function '${t}' in call expression`,{path:e,details:{fn:t}})}function _e(t,e){return new _("INVALID_SYS_PATH",`System path '${t.join(".")}' is not allowed in Translator path`,{path:e,details:{sysPath:t}})}function Et(t,e){return new _("UNSUPPORTED_BASE",`Unsupported base expression kind '${t}'. Only var(item) is supported.`,{path:e,details:{baseKind:t}})}function Rr(t,e){return new _("INVALID_SHAPE",`Invalid node shape: ${t}`,{path:e,details:{description:t}})}function Tt(t,e){return new _("UNKNOWN_NODE_KIND",`Unknown expression node kind '${t}'`,{path:e,details:{kind:t}})}function Lr(t,e){let n=Array.from(t),r=Array.from(e),o=Math.min(n.length,r.length);for(let i=0;i<o;i+=1){let a=n[i].codePointAt(0)??0,s=r[i].codePointAt(0)??0;if(a!==s)return a-s}return n.length-r.length}function pn(t){return t.map((e,n)=>({item:e,index:n})).sort((e,n)=>{let r=Lr(e.item.key,n.item.key);return r!==0?r:e.index-n.index}).map(({item:e})=>e)}function u(t,e){switch(t.kind){case"lit":return Fr(t);case"var":return jr(t,e);case"sys":return _r(t,e);case"get":return $r(t,e);case"field":return un(t,e);case"call":return Gr(t,e);case"obj":return Br(t,e);case"arr":return Ur(t,e);default:throw Tt(t.kind)}}function Fr(t){return{kind:"lit",value:t.value}}function jr(t,e){if(!e.allowItem)throw je("var",e.mode);return{kind:"get",path:"$item"}}function _r(t,e){if(t.path.length===0)throw _e(t.path);let n=t.path[0];if(!(e.allowSysPaths?.prefixes??["meta","input"]).includes(n))throw _e(t.path);return{kind:"get",path:t.path.join(".")}}function $r(t,e){let n=t.path.map(r=>r.name).join(".");if(t.base===void 0)return{kind:"get",path:n};if(t.base.kind==="var"&&t.base.name==="item"){if(!e.allowItem)throw je("var",e.mode);return{kind:"get",path:`$item.${n}`}}throw Et(t.base.kind)}function un(t,e){if(t.object.kind==="get"&&t.object.base===void 0){let n=t.object.path.map(r=>r.name).join(".");return{kind:"get",path:n?`${n}.${t.property}`:t.property}}return{kind:"field",object:u(t.object,e),property:t.property}}function Gr(t,e){let{fn:n,args:r}=t;if(n==="absDiff"){if(r.length!==2)throw g(n);return{kind:"abs",arg:{kind:"sub",left:u(r[0],e),right:u(r[1],e)}}}if(n==="clamp"){if(r.length!==3)throw g(n);return{kind:"min",args:[{kind:"max",args:[u(r[0],e),u(r[1],e)]},u(r[2],e)]}}if(n==="idiv"){if(r.length!==2)throw g(n);return{kind:"floor",arg:{kind:"div",left:u(r[0],e),right:u(r[1],e)}}}if(n==="streak"){if(r.length!==2)throw g(n);return{kind:"if",cond:u(r[1],e),then:{kind:"add",left:u(r[0],e),right:{kind:"lit",value:1}},else:{kind:"lit",value:0}}}if(n==="match")return qr(r,e);if(n==="argmax"||n==="argmin")return zr(n,r,e);if(Yr(n)){if(r.length!==2)throw g(n);let[o,i]=r;return{kind:n,left:u(o,e),right:u(i,e)}}if(n==="isNotNull"){if(r.length!==1)throw g(n);return{kind:"not",arg:{kind:"isNull",arg:u(r[0],e)}}}if(fn(n)){if(r.length!==1)throw g(n);return{kind:Qr(n),arg:u(r[0],e)}}if(n==="trim"){if(r.length!==1)throw g(n);return{kind:"trim",str:u(r[0],e)}}if(n==="lower"||n==="toLowerCase"){if(r.length!==1)throw g(n);return{kind:"toLowerCase",str:u(r[0],e)}}if(n==="upper"||n==="toUpperCase"){if(r.length!==1)throw g(n);return{kind:"toUpperCase",str:u(r[0],e)}}if(n==="strlen"||n==="strLen"){if(r.length!==1)throw g(n);return{kind:"strLen",str:u(r[0],e)}}if(Xr(n))return r.length===1?{kind:n==="min"?"minArray":"maxArray",array:u(r[0],e)}:{kind:n,args:r.map(o=>u(o,e))};if(n==="sum"){if(r.length!==1)throw g(n);return{kind:"sumArray",array:u(r[0],e)}}if(n==="pow"){if(r.length!==2)throw g(n);return{kind:"pow",base:u(r[0],e),exponent:u(r[1],e)}}if(Jr(n))return{kind:n,args:r.map(o=>u(o,e))};if(n==="if"||n==="cond"){if(r.length!==3)throw g(n);return{kind:"if",cond:u(r[0],e),then:u(r[1],e),else:u(r[2],e)}}if(n==="field"){if(r.length!==2)throw g(n);let o=u(r[0],e),i=r[1];if(i.kind!=="lit"||typeof i.value!="string")throw g(n);return un({kind:"field",object:r[0],property:i.value},e)}if(Zr(n)){if(r.length!==1)throw g(n);return{kind:n,array:u(r[0],e)}}if(eo(n)){if(r.length!==1)throw g(n);return{kind:n,obj:u(r[0],e)}}if(n==="at"){if(r.length!==2)throw g(n);return{kind:"at",array:u(r[0],e),index:u(r[1],e)}}if(n==="includes"){if(r.length!==2)throw g(n);return{kind:"includes",array:u(r[0],e),item:u(r[1],e)}}if(to(n)){if(r.length!==2)throw g(n);let o={...e,allowItem:!0};return n==="map"?{kind:"map",array:u(r[0],e),mapper:u(r[1],o)}:{kind:n,array:u(r[0],e),predicate:u(r[1],o)}}if(n==="slice"){if(r.length<2||r.length>3)throw g(n);let o={kind:"slice",array:u(r[0],e),start:u(r[1],e)};return r.length===3&&(o.end=u(r[2],e)),o}if(n==="substring"||n==="substr"){if(r.length<2||r.length>3)throw g(n);let o={kind:"substring",str:u(r[0],e),start:u(r[1],e)};return r.length===3&&(o.end=u(r[2],e)),o}if(n==="append"){if(r.length<1)throw g(n);return{kind:"append",array:u(r[0],e),items:r.slice(1).map(o=>u(o,e))}}if(n==="merge")return{kind:"merge",objects:r.map(o=>u(o,e))};throw g(n)}function Br(t,e){let n={};for(let r of pn(t.fields))n[r.key]=u(r.value,e);return{kind:"object",fields:n}}function Ur(t,e){if(t.elements.every(o=>o.kind==="lit"))return{kind:"lit",value:t.elements.map(i=>i.value)};let r=t.elements.map(o=>u(o,e));return r.length===0?{kind:"lit",value:[]}:{kind:"append",array:{kind:"lit",value:[]},items:r}}function qr(t,e){if(t.length<3)throw g("match");let n=u(t[0],e),r=u(t[t.length-1],e);for(let o=t.length-2;o>=1;o-=1){let i=t[o];if(i.kind!=="arr"||i.elements.length!==2)throw g("match");r={kind:"if",cond:{kind:"eq",left:n,right:u(i.elements[0],e)},then:u(i.elements[1],e),else:r}}return r}function zr(t,e,n){if(e.length<2)throw g(t);let r=e[e.length-1];if(r.kind!=="lit"||r.value!=="first"&&r.value!=="last")throw g(t);let o=e.slice(0,-1).map(i=>Vr(i,n,t));if(o.length===0)throw g(t);return Hr(t,o,r.value)}function Vr(t,e,n){if(t.kind!=="arr"||t.elements.length!==3)throw g(n);return{label:u(t.elements[0],e),eligible:u(t.elements[1],e),score:u(t.elements[2],e)}}function Hr(t,e,n){let r={kind:"lit",value:null};for(let o=e.length-1;o>=0;o-=1)r={kind:"if",cond:Kr(t,e,n,o),then:e[o].label,else:r};return r}function Kr(t,e,n,r){let o=e[r],i=[];for(let a=0;a<e.length;a+=1){if(a===r)continue;let s=e[a];i.push({kind:"or",args:[{kind:"not",arg:s.eligible},{kind:Wr(t,n,r,a),left:o.score,right:s.score}]})}return i.length===0?o.eligible:{kind:"and",args:[o.eligible,...i]}}function Wr(t,e,n,r){let o=e==="first"?n<r:n>r;return t==="argmax"?o?"gte":"gt":o?"lte":"lt"}function Yr(t){return["eq","neq","gt","gte","lt","lte","add","sub","mul","div","mod"].includes(t)}function fn(t){return["not","neg","abs","floor","ceil","round","sqrt","len","typeof","isNull","toString"].includes(t)}function Qr(t){if(t==="isNotNull")throw g(t);if(!fn(t))throw g(t);return t}function Xr(t){return t==="min"||t==="max"}function Jr(t){return["and","or","concat","coalesce"].includes(t)}function Zr(t){return["first","last"].includes(t)}function eo(t){return["keys","values","entries"].includes(t)}function to(t){return["filter","find","every","some","map"].includes(t)}function no(t,e){return t.map(n=>ro(n,e))}function ro(t,e){let n=t.condition?u(t.condition,$e(e,"action")):void 0,r=oo(t.op,e);return{fragmentId:t.fragmentId,condition:n,op:r,confidence:t.confidence}}function oo(t,e){switch(t.kind){case"addType":return{kind:"addType",typeName:t.typeName,typeExpr:se(t.typeExpr)};case"addField":return{kind:"addField",typeName:t.typeName,field:{name:t.field.name,type:se(t.field.type),optional:t.field.optional,defaultValue:t.field.defaultValue}};case"setFieldType":return{kind:"setFieldType",path:t.path,typeExpr:se(t.typeExpr)};case"setDefaultValue":return{kind:"setDefaultValue",path:t.path,value:t.value};case"addConstraint":return{kind:"addConstraint",targetPath:t.targetPath,rule:u(t.rule,$e(e,"schema")),message:t.message};case"addComputed":return{kind:"addComputed",name:t.name,expr:u(t.expr,$e(e,"schema")),deps:t.deps};case"addActionAvailable":return{kind:"addActionAvailable",actionName:t.actionName,expr:u(t.expr,$e(e,"schema"))}}}function se(t){switch(t.kind){case"primitive":return{kind:"primitive",name:t.name};case"array":return{kind:"array",element:se(t.element)};case"object":return{kind:"object",fields:t.fields.map(e=>({name:e.name,type:se(e.type),optional:e.optional}))};case"union":return{kind:"union",members:t.members.map(se)};case"literal":return{kind:"literal",value:t.value};case"ref":return{kind:"ref",name:t.name}}}function $e(t,e){return{mode:e,allowSysPaths:t.allowSysPaths,fnTableVersion:t.fnTableVersion,actionName:t.actionName,allowItem:!1}}function io(t,e){return t.map(n=>Ge(n,e))}function Ge(t,e){let n=t.condition?u(t.condition,e):void 0,r=t.value?u(t.value,e):void 0;return{condition:n,op:t.op,path:ao(t.path,e),value:r}}function ao(t,e){return t.map(n=>n.kind==="prop"?n:{kind:"expr",expr:u(n.expr,e)})}function I(t,e={}){switch(t.kind){case"literal":return{kind:"lit",value:lo(t.value,t.literalType)};case"identifier":return e.resolveIdentifier?.(t.name)??z(t.name);case"systemIdent":return so(t,e);case"iterationVar":return{kind:"var",name:t.name};case"propertyAccess":return co(t.object,t.property,e);case"indexAccess":return{kind:"call",fn:"at",args:[I(t.object,e),I(t.index,e)]};case"functionCall":return{kind:"call",fn:t.name,args:t.args.map(n=>I(n,e))};case"unary":return{kind:"call",fn:t.operator==="!"?"not":"neg",args:[I(t.operand,e)]};case"binary":return{kind:"call",fn:po(t.operator),args:[I(t.left,e),I(t.right,e)]};case"ternary":return{kind:"call",fn:"cond",args:[I(t.condition,e),I(t.consequent,e),I(t.alternate,e)]};case"objectLiteral":return{kind:"obj",fields:t.properties.map(n=>({key:n.key,value:I(n.value,e)}))};case"arrayLiteral":return{kind:"arr",elements:t.elements.map(n=>I(n,e))}}}function z(...t){return{kind:"get",path:mn(...t)}}function kt(t,...e){return{kind:"get",base:t,path:mn(...e)}}function be(...t){return{kind:"sys",path:t}}function Be(t){return{kind:"obj",fields:Object.entries(t).map(([e,n])=>({key:e,value:n}))}}function mn(...t){return t.map(e=>({kind:"prop",name:e}))}function so(t,e){return e.resolveSystemIdent?.(t.path)??be(...t.path)}function co(t,e,n){let r=I(t,n);return r.kind==="get"?{kind:"get",...r.base?{base:r.base}:void 0,path:[...r.path,{kind:"prop",name:e}]}:r.kind==="var"&&r.name==="item"?kt(r,e):{kind:"field",object:r,property:e}}function lo(t,e){if(e==="null")return null;if(e==="number"){if(typeof t=="number")return t;if(typeof t=="bigint")return Number(t);if(typeof t=="string"&&t.length>0){let n=Number(t);if(!Number.isNaN(n))return n}throw new Error("Invalid number literal")}if(e==="string"){if(typeof t=="string")return t;throw new Error("Invalid string literal")}if(e==="boolean"){if(typeof t=="boolean")return t;throw new Error("Invalid boolean literal")}throw new Error("Unsupported literal type")}function po(t){switch(t){case"+":return"add";case"-":return"sub";case"*":return"mul";case"/":return"div";case"%":return"mod";case"==":return"eq";case"!=":return"neq";case"<":return"lt";case"<=":return"lte";case">":return"gt";case">=":return"gte";case"&&":return"and";case"||":return"or";case"??":return"coalesce"}}import{hashSchemaSync as go,semanticPathToPatchPath as Eo,sha256Sync as To}from"@manifesto-ai/core";var uo=new Set(["findById","existsById","updateById","removeById"]);function hn(t){return{...t,computed:{fields:Object.fromEntries(Object.entries(t.computed.fields).map(([e,n])=>[e,fo(n)]))},actions:Object.fromEntries(Object.entries(t.actions).map(([e,n])=>[e,mo(n)]))}}function fo(t){return{...t,expr:yn(t.expr)}}function mo(t){return{...t,flow:Ue(t.flow),available:t.available?yn(t.available):void 0,dispatchable:t.dispatchable?ho(t.dispatchable):void 0}}function Ue(t){switch(t.kind){case"seq":return{kind:"seq",steps:t.steps.map(e=>Ue(e))};case"if":return{kind:"if",cond:Nt(t.cond),then:Ue(t.then),else:t.else?Ue(t.else):void 0};case"patch":return{kind:"patch",op:t.op,path:t.path,value:t.value?Nt(t.value):void 0};case"effect":return{kind:"effect",type:t.type,params:Object.fromEntries(Object.entries(t.params).map(([e,n])=>[e,yo(n)]))};case"fail":return{kind:"fail",code:t.code,message:t.message?Nt(t.message):void 0};case"call":case"halt":return t}}function yn(t){return u(R(t),mt)}function Nt(t){return u(R(t),ht)}function ho(t){return u(R(t),yt)}function yo(t){return u(R(t),gt)}function R(t){switch(t.kind){case"lit":case"var":return t;case"sys":return t.path[0]==="system"?z("$system",...t.path.slice(1)):t;case"get":return{kind:"get",...t.base?{base:R(t.base)}:void 0,path:t.path};case"field":return{kind:"field",object:R(t.object),property:t.property};case"obj":return{kind:"obj",fields:t.fields.map(e=>({key:e.key,value:R(e.value)}))};case"arr":return{kind:"arr",elements:t.elements.map(e=>R(e))};case"call":return uo.has(t.fn)?R(gn(t.fn,t.args)):{kind:"call",fn:t.fn,args:t.args.map(e=>R(e))}}}function gn(t,e){let[n,r,o]=e,i=R(n),a=r?R(r):{kind:"lit",value:null},s={kind:"var",name:"item"},c=kt(s,"id");switch(t){case"findById":return{kind:"call",fn:"find",args:[i,{kind:"call",fn:"eq",args:[c,a]}]};case"existsById":return{kind:"call",fn:"not",args:[{kind:"call",fn:"isNull",args:[gn("findById",e)]}]};case"updateById":{let l=o?R(o):Be({});return{kind:"call",fn:"map",args:[i,{kind:"call",fn:"cond",args:[{kind:"call",fn:"eq",args:[c,a]},{kind:"call",fn:"merge",args:[s,l]},s]}]}}case"removeById":return{kind:"call",fn:"filter",args:[i,{kind:"call",fn:"not",args:[{kind:"call",fn:"eq",args:[c,a]}]}]};default:return{kind:"call",fn:t,args:e.map(l=>R(l))}}}function ko(t){return{domainName:t,stateFields:new Set,computedFields:new Set,actionParams:new Map,onceIntentCounters:new Map,currentAction:null,diagnostics:[],typeDefs:new Map,typeDefinitions:new Map,stateFieldSpecs:new Map,stateFieldTypes:new Map}}function No(t){let e=ko(t.domain.name);bo(t.domain,e);let n=So(t.domain,e),r=xo(t.domain,e),o=Co(t.domain,e),i=Oo(t.domain,e);if(e.diagnostics.some(l=>l.severity==="error"))return{schema:null,diagnostics:e.diagnostics};let a={id:`mel:${t.domain.name.toLowerCase()}`,version:"1.0.0",types:n,state:r,computed:o,actions:i,meta:{name:t.domain.name}},s=Vo(a);return{schema:{...a,hash:s},diagnostics:e.diagnostics}}function En(t){let e=No(t);return e.schema?{schema:hn(e.schema),diagnostics:e.diagnostics}:{schema:null,diagnostics:e.diagnostics}}function bo(t,e){for(let n of t.types)e.typeDefs.set(n.name,n);for(let n of t.members)if(n.kind==="state")for(let r of n.fields)e.stateFields.add(r.name);else n.kind==="computed"?e.computedFields.add(n.name):n.kind}function So(t,e){let n={};for(let r of t.types){let o=Y(r.typeExpr);e.typeDefinitions.set(r.name,o),n[r.name]={name:r.name,definition:o}}return n}function Y(t){switch(t.kind){case"simpleType":return["string","number","boolean","null","object","array"].includes(t.name)?{kind:"primitive",type:t.name}:{kind:"ref",name:t.name};case"arrayType":return{kind:"array",element:Y(t.elementType)};case"recordType":return{kind:"record",key:Y(t.keyType),value:Y(t.valueType)};case"objectType":let e={};for(let r of t.fields)e[r.name]={type:Y(r.typeExpr),optional:r.optional};return{kind:"object",fields:e};case"unionType":return{kind:"union",types:t.types.map(Y)};case"literalType":return{kind:"literal",value:t.value};default:let n=t;throw new Error(`Unknown type expression kind: ${t.kind}`)}}function xo(t,e){let n={},r={};for(let o of t.members)if(o.kind==="state")for(let i of o.fields){let a=Y(i.typeExpr);r[i.name]=a,e.stateFieldTypes.set(i.name,a);let s=te(i.typeExpr,e);s&&e.stateFieldSpecs.set(i.name,s);let c=vo(i,e);c&&(n[i.name]=c)}return{fields:n,fieldTypes:r}}function vo(t,e){let n=te(t.typeExpr,e);if(!n)return null;let r=t.initializer?ze(t.initializer,e):void 0;return r!==void 0&&xe(r,Y(t.typeExpr),t.name,t.location,e),{...n,required:!0,default:r}}function te(t,e,n=[]){switch(t.kind){case"simpleType":switch(t.name){case"string":return{type:"string",required:!0};case"number":return{type:"number",required:!0};case"boolean":return{type:"boolean",required:!0};case"null":return{type:"null",required:!0};default:{let r=e.typeDefs.get(t.name);return r?n.includes(t.name)?(bt(e,"E044",`Recursive type '${t.name}' cannot be lowered to FieldSpec in a schema position`,t.location),null):te(r.typeExpr,e,[...n,t.name]):{type:"object",required:!0}}}case"unionType":{let r=t.types.filter(s=>!(s.kind==="simpleType"&&s.name==="null")&&!(s.kind==="literalType"&&s.value===null)),o=r.length!==t.types.length,i=[],a=!o;for(let s of r){if(s.kind!=="literalType"){a=!1;break}i.push(s.value)}return a&&i.length>0?{type:{enum:i},required:!0}:o&&r.length===1?te(r[0],e,n):(bt(e,"E043",`Union type '${ce(t)}' cannot be soundly lowered to FieldSpec`,t.location),null)}case"arrayType":{let r=te(t.elementType,e,n);return r?{type:"array",required:!0,items:r}:null}case"recordType":return{type:"object",required:!0};case"literalType":return typeof t.value=="string"?{type:"string",required:!0}:typeof t.value=="number"?{type:"number",required:!0}:typeof t.value=="boolean"?{type:"boolean",required:!0}:{type:"null",required:!0};case"objectType":{let r={};for(let o of t.fields){let i=te(o.typeExpr,e,n);if(!i)return null;r[o.name]={...i,required:!o.optional}}return{type:"object",required:!0,fields:r}}}}function bt(t,e,n,r){t.diagnostics.push({severity:"error",code:e,message:n,location:r})}function ce(t){switch(t.kind){case"simpleType":return t.name;case"unionType":return t.types.map(e=>ce(e)).join(" | ");case"arrayType":return`Array<${ce(t.elementType)}>`;case"recordType":return`Record<${ce(t.keyType)}, ${ce(t.valueType)}>`;case"literalType":return JSON.stringify(t.value);case"objectType":return`{ ${t.fields.map(e=>`${e.name}${e.optional?"?":""}: ${ce(e.typeExpr)}`).join("; ")} }`}}function ne(t,e,n=[]){if(t.kind!=="ref")return t;if(n.includes(t.name))return null;let r=e.typeDefinitions.get(t.name);return r?ne(r,e,[...n,t.name]):null}function Ao(t){return t?.kind==="primitive"&&t.type==="null"||t?.kind==="literal"&&t.value===null}function Tn(t,e){let n=ne(t,e);if(!n||n.kind!=="union")return null;let r=n.types.filter(o=>{let i=ne(o,e);return!Ao(i)});return r.length===1?r[0]:null}function wo(t,e,n){if(e===null||Array.isArray(e)||typeof e!="object")return t;let r=Tn(t,n);return r&&ne(r,n)?.kind==="object"?r:t}function Q(t){switch(t.kind){case"primitive":return t.type;case"array":return`Array<${Q(t.element)}>`;case"record":return`Record<${Q(t.key)}, ${Q(t.value)}>`;case"object":return`{ ${Object.entries(t.fields).map(([e,n])=>`${e}${n.optional?"?":""}: ${Q(n.type)}`).join("; ")} }`;case"union":return t.types.map(e=>Q(e)).join(" | ");case"literal":return JSON.stringify(t.value);case"ref":return t.name}}function Se(t,e,n){let r=ne(e,n);if(!r)return!1;switch(r.kind){case"primitive":switch(r.type){case"null":return t===null;case"string":return typeof t=="string";case"number":return typeof t=="number";case"boolean":return typeof t=="boolean";case"object":return t!==null&&!Array.isArray(t)&&typeof t=="object";case"array":return Array.isArray(t);default:return!1}case"literal":return Object.is(t,r.value);case"array":return Array.isArray(t)&&t.every(o=>Se(o,r.element,n));case"record":return t!==null&&!Array.isArray(t)&&typeof t=="object"&&Object.values(t).every(o=>Se(o,r.value,n));case"object":if(t===null||Array.isArray(t)||typeof t!="object")return!1;for(let o of Object.keys(t))if(!(o in r.fields))return!1;for(let[o,i]of Object.entries(r.fields)){if(!(o in t)){if(!i.optional)return!1;continue}if(!Se(t[o],i.type,n))return!1}return!0;case"union":return r.types.some(o=>Se(t,o,n));case"ref":return!1}}function xe(t,e,n,r,o){if(t===void 0)return;let i=ne(e,o);if(!i){o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(e)}, got ${JSON.stringify(t)}`,location:r});return}if(i.kind==="union"){if(Se(t,i,o))return;o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(i)}, got ${JSON.stringify(t)}`,location:r});return}switch(i.kind){case"primitive":{let a=Array.isArray(t)?"array":t===null?"null":typeof t;switch(i.type){case"null":t!==null&&ee(o,n,"null",a,r);return;case"string":case"number":case"boolean":typeof t!==i.type&&ee(o,n,i.type,a,r);return;case"object":(t===null||Array.isArray(t)||typeof t!="object")&&ee(o,n,"object",a,r);return;case"array":Array.isArray(t)||ee(o,n,"array",a,r);return}return}case"literal":Object.is(t,i.value)||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects literal ${JSON.stringify(i.value)}, got ${JSON.stringify(t)}`,location:r});return;case"array":if(!Array.isArray(t)){ee(o,n,"array",t===null?"null":typeof t=="object"?"object":typeof t,r);return}for(let a=0;a<t.length;a+=1)xe(t[a],i.element,`${n}[${a}]`,r,o);return;case"record":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;ee(o,n,"object",a,r);return}for(let[a,s]of Object.entries(t))xe(s,i.value,`${n}.${a}`,r,o);return;case"object":if(t===null||Array.isArray(t)||typeof t!="object"){let a=Array.isArray(t)?"array":t===null?"null":typeof t;ee(o,n,"object",a,r);return}for(let a of Object.keys(t))a in i.fields||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is not declared in ${Q(i)}`,location:r});for(let[a,s]of Object.entries(i.fields)){if(!(a in t)){s.optional||o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}.${a}' is required`,location:r});continue}xe(t[a],s.type,`${n}.${a}`,r,o)}return;case"ref":o.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${n}' expects ${Q(e)}, got ${JSON.stringify(t)}`,location:r});return}}function ee(t,e,n,r,o){t.diagnostics.push({severity:"error",code:"E_TYPE_MISMATCH",message:`Type mismatch: field '${e}' expects ${n}, got ${r}`,location:o})}function ze(t,e){switch(t.kind){case"literal":return t.value;case"arrayLiteral":return t.elements.map(n=>ze(n,e));case"objectLiteral":{let n={};for(let r of t.properties)n[r.key]=ze(r.value,e);return n}default:return}}function Co(t,e){let n=[],r=0;for(let i of t.members)if(i.kind==="computed"){let a=V(i.expression,e),s=Do(a);n.push({name:i.name,deps:s,expr:a,location:i.location,order:r}),r+=1}let o={};for(let i of Po(n,e))o[i.name]={deps:i.deps,expr:i.expr};return{fields:o}}function Po(t,e){if(t.length<=1)return[...t];let n=new Map(t.map(c=>[c.name,c])),r=new Map,o=new Map,i=new Map;for(let c of t)o.set(c.name,[]),i.set(c.name,0);for(let c of t){let l=Array.from(new Set(c.deps.filter(d=>n.has(d))));r.set(c.name,l),i.set(c.name,l.length);for(let d of l)o.get(d).push(c.name)}let a=t.filter(c=>(i.get(c.name)??0)===0).map(c=>c.name),s=[];for(;a.length>0;){let c=a.shift();s.push(n.get(c));for(let l of o.get(c)??[]){let d=(i.get(l)??0)-1;i.set(l,d),d===0&&Io(a,l,n)}}if(s.length!==t.length){let c=new Set(s.map(f=>f.name)),l=t.filter(f=>!c.has(f.name)),d=Mo(l[0].name,r),p=d?d.join(" -> "):l.map(f=>f.name).join(", ");return bt(e,"E040",`Circular computed dependency: ${p}`,(d?n.get(d[0]):l[0]).location),[...t]}return s}function Io(t,e,n){let r=n.get(e)?.order??Number.MAX_SAFE_INTEGER,o=t.length;for(let i=0;i<t.length;i+=1){let a=n.get(t[i])?.order??Number.MAX_SAFE_INTEGER;if(r<a){o=i;break}}t.splice(o,0,e)}function Mo(t,e){let n=new Set,r=[],o=new Set;function i(a){n.add(a),r.push(a),o.add(a);for(let s of e.get(a)??[])if(n.has(s)){if(o.has(s)){let c=r.indexOf(s);return[...r.slice(c),s]}}else{let c=i(s);if(c)return c}return r.pop(),o.delete(a),null}return i(t)}function Do(t){let e=new Set;function n(r){switch(r.kind){case"lit":case"sys":case"var":return;case"get":r.base===void 0?e.add(r.path.map(o=>o.name).join(".")):n(r.base);return;case"field":n(r.object);return;case"call":for(let o of r.args)n(o);return;case"obj":for(let o of r.fields)n(o.value);return;case"arr":for(let o of r.elements)n(o);return}}return n(t),Array.from(e)}function Oo(t,e){let n={};for(let r of t.members)if(r.kind==="action"){e.currentAction=r.name,e.onceIntentCounters.set(r.name,0);let o=new Set;for(let p of r.params)o.add(p.name);e.actionParams.set(r.name,o);let i=r.params.map(p=>p.name),a=kn(r.body,e),s,c;if(r.params.length>0){let p={},f={};for(let m of r.params){let A=te(m.typeExpr,e);A&&(p[m.name]=structuredClone(A),f[m.name]={type:Y(m.typeExpr),optional:!1})}s={type:"object",required:!0,fields:p},c={kind:"object",fields:f}}let l;r.available&&(l=V(r.available,e));let d;r.dispatchable&&(d=V(r.dispatchable,e,{preferActionParams:!0})),n[r.name]={flow:a,input:s,inputType:c,params:i,available:l,dispatchable:d},e.currentAction=null}return n}function kn(t,e){return t.length===0?{kind:"seq",steps:[]}:t.length===1?Ve(t[0],e):{kind:"seq",steps:t.map(n=>Ve(n,e))}}function Ve(t,e){switch(t.kind){case"when":return Ro(t,e);case"once":return Lo(t,e);case"onceIntent":return Fo(t,e);case"patch":return jo(t,e);case"effect":return _o(t,e);case"fail":return Go(t,e);case"stop":return Bo(t,e);case"include":return{kind:"seq",steps:[]}}}function Ro(t,e){let n=V(t.condition,e),r=kn(t.body,e);return{kind:"if",cond:n,then:r}}function Lo(t,e){let n=St(t.marker,e),r=be("meta","intentId"),o=He("neq",[z(...Nn(n)),r]);if(t.condition){let s=V(t.condition,e);o=He("and",[o,s])}let i={kind:"patch",op:"set",path:xt(n),value:r},a=t.body.map(s=>Ve(s,e));return{kind:"if",cond:o,then:{kind:"seq",steps:[i,...a]}}}function Fo(t,e){let n=e.currentAction??"unknown",r=e.onceIntentCounters.get(n)??0;e.onceIntentCounters.set(n,r+1);let o=To(`${n}:${r}:intent`),i=`$mel.guards.intent.${o}`,a=be("meta","intentId"),s=He("neq",[z(...Nn(i)),a]);if(t.condition){let d=V(t.condition,e);s=He("and",[s,d])}let c={kind:"patch",op:"merge",path:xt("$mel.guards.intent"),value:Be({[o]:a})},l=t.body.map(d=>Ve(d,e));return{kind:"if",cond:s,then:{kind:"seq",steps:[c,...l]}}}function jo(t,e){let n=St(t.path,e),r={kind:"patch",op:t.op,path:xt(n)};if(t.value){let o=V(t.value,e);if(r.value=o,t.op==="set"){let i=t.path.segments[0];if(i.kind==="propertySegment"){let a=e.stateFieldTypes.get(i.name);if(a){let s=a,c=t.path.segments;for(let l=1;l<c.length;l++){let d=c[l],p=s?ne(s,e):null;if(!p){s=null;break}if(p.kind==="union"){let f=Tn(s,e);if(!f){s=null;break}s=f,l-=1;continue}if(d.kind==="propertySegment"&&p.kind==="object"&&p.fields[d.name])s=p.fields[d.name].type;else if(d.kind==="propertySegment"&&p.kind==="record")s=p.value;else if(d.kind==="indexSegment"&&p.kind==="array")s=p.element;else{s=null;break}}if(s){let l=$o(t.value,e);if(l!==void 0){let d=t.path.segments.map(f=>f.kind==="propertySegment"?f.name:"[*]").join("."),p=wo(s,l,e);xe(l,p,d,t.location,e)}}}}}}return r}function _o(t,e){let n={};for(let r of t.args)r.isPath?n[r.name]={kind:"lit",value:St(r.value,e)}:n[r.name]=V(r.value,e);return{kind:"effect",type:t.effectType,params:n}}function $o(t,e){return ze(t,e)}function Go(t,e){let n={kind:"fail",code:t.code};return t.message&&(n.message=V(t.message,e)),n}function Bo(t,e){return{kind:"halt",reason:t.reason}}function Uo(t){return t.replaceAll("\\","\\\\").replaceAll(".","\\.")}function qe(...t){return t.map(Uo).join(".")}function St(t,e){let n=[];for(let o of t.segments)if(o.kind==="propertySegment")n.push(o.name);else{let i=V(o.index,e);i.kind==="lit"?n.push(String(i.value)):n.push("*")}let r=n[0];return e.stateFields.has(r)?qe(...n):e.computedFields.has(r)?qe(...n):e.currentAction&&e.actionParams.get(e.currentAction)?.has(r)?`input.${qe(...n)}`:qe(...n)}function xt(t){return Eo(t)}function He(t,e){return{kind:"call",fn:t,args:e}}function Nn(t){return t.split(/(?<!\\)\./g).map(e=>e.replaceAll("\\.",".").replaceAll("\\\\","\\"))}function V(t,e,n={}){return I(t,{resolveIdentifier:r=>qo(r,e,n),resolveSystemIdent:r=>zo(r,e)})}function qo(t,e,n={}){return n.preferActionParams&&e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?z("input",t):e.stateFields.has(t)||e.computedFields.has(t)?z(t):e.currentAction&&e.actionParams.get(e.currentAction)?.has(t)?z("input",t):(e.diagnostics.push({severity:"error",code:"E_UNKNOWN_IDENT",message:`Unknown identifier '${t}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),z(t))}function zo(t,e){let[n,...r]=t;switch(n){case"system":case"meta":case"input":return be(n,...r);default:return e.diagnostics.push({severity:"error",code:"E_INVALID_SYSTEM",message:`Invalid system identifier namespace '$${n}'`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),{kind:"lit",value:null}}}function Vo(t){return go(t)}var Ho="@meta can attach only to domain, type, type field, state field, computed, or action declarations.",Ko="Action-parameter annotations are not part of the current MEL syntax.",bn="Annotation payloads must be JSON-like literals. MEL expressions are not allowed in @meta payloads.",Sn="Annotation payload nesting exceeds the current MEL limit of 2 levels.",Wo="Annotation target does not map to the emitted DomainSchema.",xn=2;function vn(t,e){let n=[],r=new Map,o=t.domain;le(o.annotations,`domain:${o.name}`,n,r);for(let a of o.types)le(a.annotations,`type:${a.name}`,n,r),de(a.typeExpr,a.name,0,n,r);for(let a of o.members)switch(a.kind){case"state":for(let s of a.fields)le(s.annotations,`state_field:${s.name}`,n,r),re(s.typeExpr,n);break;case"computed":le(a.annotations,`computed:${a.name}`,n,r);break;case"action":le(a.annotations,`action:${a.name}`,n,r),Yo(a,n);for(let s of a.params)re(s.typeExpr,n);break;case"flow":break}let i={};for(let a of[...r.keys()].sort()){if(!Jo(e,a)){n.push(D("E057",Wo,Zo(t,a)??o.location));continue}let s=r.get(a);s&&s.length>0&&(i[a]=Object.freeze(s.map(c=>Xo(c))))}return{annotations:Object.freeze({schemaHash:e.hash,entries:Object.freeze(i)}),diagnostics:n}}function le(t,e,n,r){if(!t||t.length===0)return;let o=[];for(let a of t){let s=a.payload===void 0?{ok:!0,value:void 0}:vt(a.payload,0,n);s.ok&&o.push({tag:a.tag,...s.value===void 0?{}:{payload:s.value}})}if(o.length===0)return;let i=r.get(e);if(i){i.push(...o);return}r.set(e,o)}function de(t,e,n,r,o){switch(t.kind){case"objectType":for(let i of t.fields)i.annotations?.length&&(n===0?le(i.annotations,`type_field:${e}.${i.name}`,r,o):An(i.annotations,r)),de(i.typeExpr,e,n+1,r,o);return;case"arrayType":de(t.elementType,e,n,r,o);return;case"recordType":de(t.keyType,e,n,r,o),de(t.valueType,e,n,r,o);return;case"unionType":for(let i of t.types)de(i,e,n,r,o);return;case"simpleType":case"literalType":return}}function re(t,e){switch(t.kind){case"objectType":for(let n of t.fields)An(n.annotations,e),re(n.typeExpr,e);return;case"arrayType":re(t.elementType,e);return;case"recordType":re(t.keyType,e),re(t.valueType,e);return;case"unionType":for(let n of t.types)re(n,e);return;case"simpleType":case"literalType":return}}function Yo(t,e){for(let n of t.params)Qo(n,e)}function Qo(t,e){if(t.annotations)for(let n of t.annotations)e.push(D("E054",Ko,n.location))}function An(t,e){if(t)for(let n of t)e.push(D("E053",Ho,n.location))}function vt(t,e,n){switch(t.kind){case"literal":return t.literalType==="string"||t.literalType==="number"||t.literalType==="boolean"||t.literalType==="null"?{ok:!0,value:t.value}:(n.push(D("E055",bn,t.location)),{ok:!1});case"arrayLiteral":{if(e+1>xn)return n.push(D("E056",Sn,t.location)),{ok:!1};let r=[];for(let o of t.elements){let i=vt(o,e+1,n);if(!i.ok)return{ok:!1};r.push(i.value)}return{ok:!0,value:r}}case"objectLiteral":{if(e+1>xn)return n.push(D("E056",Sn,t.location)),{ok:!1};let r={};for(let o of t.properties){let i=vt(o.value,e+1,n);if(!i.ok)return{ok:!1};r[o.key]=i.value}return{ok:!0,value:r}}default:return n.push(D("E055",bn,t.location)),{ok:!1}}}function Xo(t){return t.payload===void 0?Object.freeze({tag:t.tag}):Object.freeze({tag:t.tag,payload:At(t.payload)})}function At(t){if(Array.isArray(t))return Object.freeze(t.map(e=>At(e)));if(t!==null&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=At(r);return Object.freeze(e)}return t}function Jo(t,e){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.meta?.name===o||t.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(t.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,o);case"computed":return Object.hasOwn(t.computed.fields,o);case"action":return Object.hasOwn(t.actions,o);default:return!1}}function Zo(t,e){let n=e.indexOf(":");if(n<0)return null;let r=e.slice(0,n),o=e.slice(n+1),i=t.domain;if(r==="domain"&&i.name===o)return i.location;if(r==="type")return i.types.find(a=>a.name===o)?.location??null;if(r==="type_field"){let a=o.indexOf(".");if(a<=0)return null;let s=o.slice(0,a),c=o.slice(a+1),l=i.types.find(d=>d.name===s);return!l||l.typeExpr.kind!=="objectType"?l?.location??null:l.typeExpr.fields.find(d=>d.name===c)?.location??l.location}if(r==="state_field"){for(let a of i.members){if(a.kind!=="state")continue;let s=a.fields.find(c=>c.name===o);if(s)return s.location}return null}return r==="computed"?i.members.find(a=>a.kind==="computed"&&a.name===o)?.location??null:r==="action"?i.members.find(a=>a.kind==="action"&&a.name===o)?.location??null:null}var wt=16;function k(t){return structuredClone(t)}function C(t,e,n,r,o){let i=`${n}:${o.start.offset}:${o.end.offset}:${r}`;e.has(i)||(e.add(i),t.push(D(n,r,o)))}function ei(t){let e=new Map,n=new Set,r=new Map,o=new Set,i=new Map;for(let a of t.types)r.set(a.name,a);for(let a of t.members)switch(a.kind){case"state":for(let s of a.fields)e.set(s.name,s.typeExpr);break;case"computed":n.add(a.name);break;case"action":o.add(a.name);break;case"flow":i.has(a.name)||i.set(a.name,a);break}return{stateTypes:e,computedNames:n,typeDefs:r,actionNames:o,flows:i}}function ti(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function ni(t){let e=new Map;for(let n of t.params)e.set(n.name,n.typeExpr);return e}function ri(t,e,n,r){let o=new Map;for(let i of e.flows.values()){o.set(i.name,[]),e.actionNames.has(i.name)&&C(n,r,"E022",`Flow '${i.name}' conflicts with action '${i.name}'.`,i.location);for(let s of i.params)(e.stateTypes.has(s.name)||e.computedNames.has(s.name)||e.typeDefs.has(s.name))&&C(n,r,"E021",`Flow parameter '${s.name}' conflicts with a top-level identifier.`,s.location);let a=ti(i);for(let s of i.body)ii(s,i.name,a,e,n,r,o.get(i.name))}for(let i of t.members)if(i.kind==="action"){let a=ni(i);for(let s of i.body)oi(s,a,e,n,r)}return o}function oi(t,e,n,r,o){switch(t.kind){case"include":We(t,e,n,r,o);break;case"when":for(let i of t.body)ue(i,e,n,r,o);break;case"once":for(let i of t.body)ue(i,e,n,r,o);break;case"onceIntent":for(let i of t.body)ue(i,e,n,r,o);break;case"fail":case"stop":break}}function ue(t,e,n,r,o){switch(t.kind){case"include":C(r,o,"E016","include is only allowed at action or flow body top-level.",t.location),We(t,e,n,r,o);break;case"when":for(let i of t.body)ue(i,e,n,r,o);break;case"once":for(let i of t.body)ue(i,e,n,r,o);break;case"onceIntent":for(let i of t.body)ue(i,e,n,r,o);break;case"patch":case"effect":case"fail":case"stop":break}}function ii(t,e,n,r,o,i,a){switch(t.kind){case"include":We(t,n,r,o,i)&&a.push({target:t.flowName,location:t.location});break;case"when":for(let s of t.body)Ke(s,e,n,r,o,i);break;case"once":C(o,i,"E017","once() is not allowed in flow bodies.",t.location);break;case"onceIntent":C(o,i,"E018","onceIntent is not allowed in flow bodies.",t.location);break;case"patch":C(o,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":C(o,i,"E020","effect is not allowed in flow bodies.",t.location);break}}function Ke(t,e,n,r,o,i){switch(t.kind){case"include":C(o,i,"E016","include is only allowed at action or flow body top-level.",t.location),We(t,n,r,o,i);break;case"when":for(let a of t.body)Ke(a,e,n,r,o,i);break;case"once":C(o,i,"E017","once() is not allowed in flow bodies.",t.location);for(let a of t.body)Ke(a,e,n,r,o,i);break;case"onceIntent":C(o,i,"E018","onceIntent is not allowed in flow bodies.",t.location);for(let a of t.body)Ke(a,e,n,r,o,i);break;case"patch":C(o,i,"E019","patch is not allowed in flow bodies.",t.location);break;case"effect":C(o,i,"E020","effect is not allowed in flow bodies.",t.location);break;case"fail":case"stop":break}}function We(t,e,n,r,o){let i=n.flows.get(t.flowName);if(!i)return C(r,o,"E015",`'${t.flowName}' is not a declared flow.`,t.location),!1;if(t.args.length!==i.params.length)return C(r,o,"E023",`include '${t.flowName}' expected ${i.params.length} argument(s), got ${t.args.length}.`,t.location),!0;for(let a=0;a<t.args.length;a+=1){let s=t.args[a],c=i.params[a],l=ve(s,e,n);if(!l)continue;pe(l,c.typeExpr,n)===!1&&C(r,o,"E024",`include '${t.flowName}' argument ${a+1} is not assignable to parameter '${c.name}'.`,s.location)}return!0}function ai(t,e,n,r){function o(i,a,s){s.add(i);for(let c of t.get(i)??[]){if(a+1>wt){C(n,r,"E014",`Include expansion depth exceeds limit (${wt}).`,c.location);continue}if(s.has(c.target)){C(n,r,"E013","Circular include detected.",c.location);continue}o(c.target,a+1,new Set(s))}}for(let i of e.flows.keys())o(i,1,new Set)}function O(t,e){switch(t.kind){case"identifier":return e.has(t.name)?k(e.get(t.name)):k(t);case"systemIdent":case"literal":case"iterationVar":return k(t);case"functionCall":return{...k(t),args:t.args.map(n=>O(n,e))};case"binary":return{...k(t),left:O(t.left,e),right:O(t.right,e)};case"unary":return{...k(t),operand:O(t.operand,e)};case"ternary":return{...k(t),condition:O(t.condition,e),consequent:O(t.consequent,e),alternate:O(t.alternate,e)};case"propertyAccess":return{...k(t),object:O(t.object,e)};case"indexAccess":return{...k(t),object:O(t.object,e),index:O(t.index,e)};case"objectLiteral":return{...k(t),properties:t.properties.map(n=>({...k(n),value:O(n.value,e)}))};case"arrayLiteral":return{...k(t),elements:t.elements.map(n=>O(n,e))}}}function si(t,e){switch(t.kind){case"when":return[wn(t,e)];case"fail":return[{...k(t),message:t.message?O(t.message,e):void 0}];case"stop":return[k(t)];case"patch":case"effect":case"once":case"onceIntent":case"include":return[]}}function wn(t,e){return{...k(t),condition:O(t.condition,e),body:t.body.flatMap(n=>si(n,e))}}function ci(t,e,n){let r=new Map;for(let o=0;o<t.params.length;o+=1)r.set(t.params[o].name,O(e.args[o],n));return r}function li(t,e,n,r,o){switch(t.kind){case"when":return[wn(t,n)];case"include":return Cn(t,e,n,r,o);case"once":case"onceIntent":case"patch":case"effect":return[]}}function Cn(t,e,n,r,o){let i=e.flows.get(t.flowName);if(!i||t.args.length!==i.params.length||r>wt||o.includes(t.flowName))return[];let a=ci(i,t,n),s=[...o,t.flowName];return i.body.flatMap(c=>li(c,e,a,r+1,s))}function fe(t){switch(t.kind){case"when":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"once":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"onceIntent":return[{...k(t),body:t.body.flatMap(e=>fe(e))}];case"include":return[];case"patch":case"effect":case"fail":case"stop":return[k(t)]}}function di(t,e,n){switch(t.kind){case"include":return Cn(t,e,new Map,n,[]);case"when":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"once":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"onceIntent":return[{...k(t),body:t.body.flatMap(r=>fe(r))}];case"fail":case"stop":return[k(t)]}}function pi(t,e){let n=[];for(let r of t.domain.members)switch(r.kind){case"state":case"computed":n.push(k(r));break;case"action":n.push({...k(r),body:r.body.flatMap(o=>di(o,e,1))});break;case"flow":break}return{...k(t),domain:{...k(t.domain),types:t.domain.types.map(r=>k(r)),members:n}}}function ve(t,e,n){switch(t.kind){case"literal":return{kind:"literalType",value:t.value,location:t.location};case"identifier":return e.get(t.name)??n.stateTypes.get(t.name)??null;case"propertyAccess":{let r=ve(t.object,e,n);return Pn(r,t.property,n)}case"indexAccess":{let r=ve(t.object,e,n);return In(r,n)}case"objectLiteral":return{kind:"objectType",fields:t.properties.map(r=>{let o=ve(r.value,e,n);return o?{kind:"typeField",name:r.key,typeExpr:o,optional:!1,location:r.location}:null}).filter(r=>r!==null),location:t.location};case"arrayLiteral":{if(t.elements.length===0)return null;let r=ve(t.elements[0],e,n);return r?{kind:"arrayType",elementType:r,location:t.location}:null}case"systemIdent":case"functionCall":case"binary":case"unary":case"ternary":case"iterationVar":return null}}function Ae(t,e,n=new Set){return t?t.kind==="simpleType"&&e.typeDefs.has(t.name)?n.has(t.name)?null:(n.add(t.name),Ae(e.typeDefs.get(t.name).typeExpr,e,n)):t:null}function Pn(t,e,n){let r=Ae(t,n);if(!r)return null;if(r.kind==="objectType")return r.fields.find(i=>i.name===e)?.typeExpr??null;if(r.kind==="unionType")for(let o of r.types){if(o.kind==="simpleType"&&o.name==="null")continue;let i=Pn(o,e,n);if(i)return i}return null}function In(t,e){let n=Ae(t,e);if(!n)return null;if(n.kind==="arrayType")return n.elementType;if(n.kind==="recordType")return n.valueType;if(n.kind==="unionType")for(let r of n.types){if(r.kind==="simpleType"&&r.name==="null")continue;let o=In(r,e);if(o)return o}return null}function pe(t,e,n){let r=Ae(t,n),o=Ae(e,n);if(!r||!o)return null;if(o.kind==="unionType"){let i=o.types.map(a=>pe(r,a,n));return i.includes(!0)?!0:i.every(a=>a===!1)?!1:null}if(r.kind==="unionType"){let i=r.types.map(a=>pe(a,o,n));return i.every(a=>a===!0)?!0:i.some(a=>a===!1)?!1:null}if(o.kind==="simpleType"){if(r.kind==="simpleType")return r.name===o.name;if(r.kind==="literalType")return o.name==="null"?r.value===null:typeof r.value===o.name}if(o.kind==="literalType")return r.kind!=="literalType"?!1:r.value===o.value;if(o.kind==="arrayType")return r.kind!=="arrayType"?!1:pe(r.elementType,o.elementType,n);if(o.kind==="objectType"){if(r.kind!=="objectType")return!1;for(let i of o.fields){let a=r.fields.find(c=>c.name===i.name);if(!a){if(i.optional)continue;return!1}let s=pe(a.typeExpr,i.typeExpr,n);if(s!==!0)return s}return!0}return o.kind==="recordType"?r.kind!=="recordType"?null:pe(r.valueType,o.valueType,n):null}function Mn(t){let e=ei(t.domain),n=[],r=new Set,o=ri(t.domain,e,n,r);return ai(o,e,n,r),{program:pi(t,e),diagnostics:n}}var ui=new Set(["$item","$index","$array"]);function Rn(t){let e=Object.keys(t.state.fields).filter(d=>!d.startsWith("$")),n=fi(t),r=new Set(n),o=new Set(e),i=Object.keys(t.actions),a=[...e.map(d=>({id:Ct(d),kind:"state",name:d})),...n.map(d=>({id:Pt(d),kind:"computed",name:d})),...i.map(d=>({id:On(d),kind:"action",name:d}))],s=new Set,c=[],l=(d,p,f)=>{if(!d||!p)return;let m=`${d}|${f}|${p}`;s.has(m)||(s.add(m),c.push({from:d,to:p,relation:f}))};for(let d of n){let p=t.computed.fields[d];if(p)for(let f of p.deps)l(Dn(f,t,r,o),Pt(d),"feeds")}for(let d of i){let p=t.actions[d],f=On(d);for(let m of mi(p.flow,t))o.has(m)&&l(f,Ct(m),"mutates");if(p.available)for(let m of $n(p.available))l(Dn(m,t,r,o),f,"unlocks")}return gi({nodes:a,edges:c})}function fi(t){let e=t.computed.fields,n=new Map,r=(o,i)=>{let a=n.get(o);if(a!==void 0)return a;if(i.has(o))return!1;i.add(o);let s=e[o];if(!s)return i.delete(o),n.set(o,!0),!0;for(let c of $n(s.expr)){if(_n(c))return i.delete(o),n.set(o,!1),!1;let l=Ln(c,e);if(l!==null&&!r(l,i))return i.delete(o),n.set(o,!1),!1}return i.delete(o),n.set(o,!0),!0};return Object.keys(e).filter(o=>r(o,new Set))}function mi(t,e){let n=new Set,r=(o,i)=>{if(o)switch(o.kind){case"seq":o.steps.forEach(a=>r(a,i));return;case"if":r(o.then,i),r(o.else,i);return;case"patch":{let a=hi(o.path);a&&n.add(a);return}case"effect":{let a=yi(o.params.into);a&&n.add(a);return}case"call":{if(i.has(o.flow))return;let a=e.actions[o.flow];if(!a)return;let s=new Set(i);s.add(o.flow),r(a.flow,s);return}case"halt":case"fail":return}};return r(t,new Set),[...n]}function hi(t){let[e]=t;return!e||e.kind!=="prop"||e.name.startsWith("$")?null:e.name}function yi(t){return typeof t!="object"||t===null||t.kind!=="lit"||typeof t.value!="string"?null:Fn(t.value)}function Dn(t,e,n,r){let o=Ln(t,e.computed.fields);if(o!==null&&n.has(o))return Pt(o);if(_n(t))return null;let i=Fn(t);return!i||!r.has(i)?null:Ct(i)}function Ln(t,e){if(Object.prototype.hasOwnProperty.call(e,t))return t;if(!t.startsWith("computed."))return null;let n=t.slice(9);return Object.prototype.hasOwnProperty.call(e,n)?n:null}function Fn(t){let e=jn(t),n=e.startsWith("data.")?e.slice(5):e,r=/^([^.[\]]+)/.exec(n);if(!r)return null;let[o]=r.slice(1);return!o||o.startsWith("$")?null:o}function jn(t){return t.startsWith("/")?t.slice(1).replace(/\//g,"."):t}function _n(t){let e=jn(t),n=e.startsWith("data.")?e.slice(5):e,o=/^([^.[\]]+)/.exec(n)?.[1]??"";return o.startsWith("$")?!ui.has(o):!1}function $n(t){let e=[],n=new WeakSet,r=o=>{if(o==null)return;if(Array.isArray(o)){o.forEach(r);return}if(typeof o!="object")return;let i=o;if(!n.has(i)&&(n.add(i),i.kind!=="lit")){if(i.kind==="get"&&typeof i.path=="string"){e.push(i.path);return}for(let a of Object.values(i))r(a)}};return r(t),e}function Ct(t){return`state:${t}`}function Pt(t){return`computed:${t}`}function On(t){return`action:${t}`}function gi(t){return Object.freeze({nodes:Object.freeze(t.nodes.map(e=>Object.freeze(e))),edges:Object.freeze([...t.edges].sort(Ei).map(e=>Object.freeze(e)))})}function Ei(t,e){return t.from.localeCompare(e.from)||t.to.localeCompare(e.to)||t.relation.localeCompare(e.relation)}var Ti="Source-map target does not map to the emitted DomainSchema.",ki="Source-map entry missing for emitted DomainSchema target.",Ni=new TextEncoder;function zn(t){return Object.freeze({coordinateUnit:"utf16",compilerVersion:t,emissionOptionsFingerprint:"default"})}function Vn(t,e,n,r){let o=[],i=new Map,a=t.domain,s=xi(e,r.coordinateUnit);i.set(`domain:${a.name}`,ye({target:{kind:"domain",domain:{name:a.name}},span:s(a.location)}));for(let l of a.types)i.set(`type:${l.name}`,ye({target:{kind:"type",type:{name:l.name}},span:s(l.location)})),me(l.typeExpr,l.name,0,i,s);for(let l of a.members)switch(l.kind){case"state":for(let d of l.fields)i.set(`state_field:${d.name}`,ye({target:{kind:"state_field",field:{name:d.name}},span:s(d.location)}));break;case"computed":i.set(`computed:${l.name}`,ye({target:{kind:"computed",computed:{name:l.name}},span:s(l.location)}));break;case"action":i.set(`action:${l.name}`,ye({target:{kind:"action",action:{name:l.name}},span:s(l.location)}));break;case"flow":break}let c={};for(let l of[...i.keys()].sort()){if(!Si(n,l)){o.push(D("E058",Ti,Gn(t,l)??a.location));continue}let d=i.get(l);d&&(c[l]=d)}for(let l of bi(t,n))Object.hasOwn(c,l)||o.push(D("E058",ki,Gn(t,l)??a.location));return{sourceMap:Object.freeze({schemaHash:n.hash,sourceHash:Un(e),format:"manifesto/source-map-v1",coordinateUnit:r.coordinateUnit,emissionFingerprint:Un(`${r.coordinateUnit}\0${r.compilerVersion}\0${r.emissionOptionsFingerprint}`),entries:Object.freeze(c)}),diagnostics:o}}function me(t,e,n,r,o){switch(t.kind){case"objectType":for(let i of t.fields)n===0&&r.set(`type_field:${e}.${i.name}`,ye({target:{kind:"type_field",type:{name:e},field:{name:i.name}},span:o(i.location)})),me(i.typeExpr,e,n+1,r,o);return;case"arrayType":me(t.elementType,e,n+1,r,o);return;case"recordType":me(t.keyType,e,n+1,r,o),me(t.valueType,e,n+1,r,o);return;case"unionType":for(let i of t.types)me(i,e,n+1,r,o);return;case"simpleType":case"literalType":return}}function bi(t,e){let n=new Set;n.add(`domain:${t.domain.name}`);for(let[r,o]of Object.entries(e.types))if(n.add(`type:${r}`),o.definition.kind==="object")for(let i of Object.keys(o.definition.fields))n.add(`type_field:${r}.${i}`);for(let r of Object.keys(e.state.fields))n.add(`state_field:${r}`);for(let r of Object.keys(e.computed.fields))n.add(`computed:${r}`);for(let r of Object.keys(e.actions))n.add(`action:${r}`);return[...n].sort()}function Si(t,e){let n=e.indexOf(":");if(n<0)return!1;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.meta?.name===o||t.id===`mel:${o.toLowerCase()}`;case"type":return Object.hasOwn(t.types,o);case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return!1;let a=o.slice(0,i),s=o.slice(i+1),c=t.types[a];return!c||c.definition.kind!=="object"?!1:Object.hasOwn(c.definition.fields,s)}case"state_field":return Object.hasOwn(t.state.fields,o);case"computed":return Object.hasOwn(t.computed.fields,o);case"action":return Object.hasOwn(t.actions,o);default:return!1}}function Gn(t,e){let n=e.indexOf(":");if(n<0)return null;let r=e.slice(0,n),o=e.slice(n+1);switch(r){case"domain":return t.domain.name===o?t.domain.location:null;case"type":return t.domain.types.find(i=>i.name===o)?.location??null;case"type_field":{let i=o.indexOf(".");if(i<=0||i!==o.lastIndexOf("."))return null;let a=o.slice(0,i),s=o.slice(i+1),c=t.domain.types.find(l=>l.name===a);return c?he(c.typeExpr,s,0):null}case"state_field":for(let i of t.domain.members){if(i.kind!=="state")continue;let a=i.fields.find(s=>s.name===o);if(a)return a.location}return null;case"computed":return t.domain.members.find(i=>i.kind==="computed"&&i.name===o)?.location??null;case"action":return t.domain.members.find(i=>i.kind==="action"&&i.name===o)?.location??null;default:return null}}function he(t,e,n){switch(t.kind){case"objectType":for(let r of t.fields){if(n===0&&r.name===e)return r.location;let o=he(r.typeExpr,e,n+1);if(o)return o}return null;case"arrayType":return he(t.elementType,e,n+1);case"recordType":return he(t.keyType,e,n+1)??he(t.valueType,e,n+1);case"unionType":for(let r of t.types){let o=he(r,e,n+1);if(o)return o}return null;case"simpleType":case"literalType":return null}}function xi(t,e){return e==="utf16"?n=>vi(n):n=>Ai(n,t)}function vi(t){return Object.freeze({start:Object.freeze({line:t.start.line,column:t.start.column}),end:Object.freeze({line:t.end.line,column:t.end.column})})}function Ai(t,e){return Object.freeze({start:Bn(t.start,e),end:Bn(t.end,e)})}function Bn(t,e){let n=qn(e.slice(0,t.offset)),r=t.offset-(t.column-1),o=qn(e.slice(0,r));return Object.freeze({line:t.line,column:n-o+1})}function ye(t){return Object.freeze({target:wi(t.target),span:Object.freeze({start:Object.freeze({...t.span.start}),end:Object.freeze({...t.span.end})})})}function wi(t){switch(t.kind){case"domain":return Object.freeze({kind:t.kind,domain:Object.freeze({...t.domain})});case"type":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type})});case"type_field":return Object.freeze({kind:t.kind,type:Object.freeze({...t.type}),field:Object.freeze({...t.field})});case"state_field":return Object.freeze({kind:t.kind,field:Object.freeze({...t.field})});case"computed":return Object.freeze({kind:t.kind,computed:Object.freeze({...t.computed})});case"action":return Object.freeze({kind:t.kind,action:Object.freeze({...t.action})})}}function Un(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return`fnv1a32:${e.toString(16).padStart(8,"0")}`}function qn(t){return Ni.encode(t).length}import{sha256Sync as Ye}from"@manifesto-ai/core";function Hn(t){return t.kind==="literal"&&t.literalType==="boolean"&&t.value===!0}function ge(t){return I(t)}var Qe=class{constructor(e){this.deps=e;this.exprValidator=new Mt(e.mapLocation)}conditionComposer=new It;exprValidator;collect(e,n,r,o){return this.collectPatchStatements(e,n,r,o)}collectPatchStatements(e,n,r,o){let i=[];for(let a of e){if(a.kind==="patch"){this.exprValidator.validatePath(a.path,n),a.value&&this.exprValidator.validateExpr(a.value,n),i.push({patch:a,condition:o});continue}if(a.kind==="when"){this.exprValidator.validateExpr(a.condition,n);let s=o;try{s=this.conditionComposer.and(o,this.deps.toMelExpr(a.condition))}catch(f){n.push({severity:"error",code:"E_LOWER",message:f.message,location:this.deps.mapLocation(a.condition.location)})}let c=Ye(`${r.actionName}:${r.whenCounter}:when`);r.whenCounter+=1;let l={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__whenGuards",location:a.location},{kind:"propertySegment",name:c,location:a.location}],location:a.location},d=we(l),p=this.collectPatchStatements(a.body,n,r,void 0).map(f=>({patch:f.patch,condition:this.conditionComposer.and(d,f.condition)}));i.push({patch:{kind:"patch",op:"set",path:l,value:{kind:"literal",literalType:"boolean",value:!0,location:a.location},location:a.location},condition:s},...p,{patch:{kind:"patch",op:"unset",path:l,location:a.location}});continue}if(a.kind==="once"){this.exprValidator.validatePath(a.marker,n);let s=o,c=we(a.marker),l=a.marker,d=a.location,p={kind:"call",fn:"neq",args:[c,{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{p=this.conditionComposer.and(p,this.deps.toMelExpr(a.condition))??p}catch($){n.push({severity:"error",code:"E_LOWER",message:$.message,location:this.deps.mapLocation(a.condition.location)})}}s=this.conditionComposer.and(o,p);let f=Ye(`${r.actionName}:${r.onceCounter}:once`);r.onceCounter+=1;let m={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:d},{kind:"propertySegment",name:"__onceScopeGuards",location:d},{kind:"propertySegment",name:f,location:d}],location:d},A=we(m),b=this.collectPatchStatements(a.body,n,r,A);i.push({patch:{kind:"patch",op:"set",path:m,value:{kind:"literal",literalType:"boolean",value:!0,location:d},location:d},condition:s},{patch:{kind:"patch",op:"set",path:l,value:{kind:"systemIdent",path:["meta","intentId"],location:d},location:d},condition:A},...b,{patch:{kind:"patch",op:"unset",path:m,location:d},condition:s});continue}if(a.kind==="onceIntent"){let s=Ye(`${r.actionName}:${r.onceCounter}:onceIntent`);r.onceCounter+=1;let c={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:a.location},{kind:"propertySegment",name:"__onceScopeGuards",location:a.location},{kind:"propertySegment",name:s,location:a.location}],location:a.location},l=we(c),d=Ye(`${r.actionName}:${r.onceIntentCounter}:intent`);r.onceIntentCounter+=1;let p=a.location,m={kind:"call",fn:"neq",args:[we({kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p},{kind:"propertySegment",name:d,location:p}],location:p}),{kind:"sys",path:["meta","intentId"]}]};if(a.condition){this.exprValidator.validateExpr(a.condition,n);try{m=this.conditionComposer.and(m,this.deps.toMelExpr(a.condition))??m}catch(H){n.push({severity:"error",code:"E_LOWER",message:H.message,location:this.deps.mapLocation(a.condition.location)})}}let A=this.conditionComposer.and(o,m),b={kind:"path",segments:[{kind:"propertySegment",name:"$mel",location:p},{kind:"propertySegment",name:"guards",location:p},{kind:"propertySegment",name:"intent",location:p}],location:p},$=this.collectPatchStatements(a.body,n,r,l);i.push({patch:{kind:"patch",op:"set",path:c,value:{kind:"literal",literalType:"boolean",value:!0,location:p},location:p},condition:A},{patch:{kind:"patch",op:"merge",path:b,value:{kind:"objectLiteral",properties:[{kind:"objectProperty",key:d,value:{kind:"systemIdent",path:["meta","intentId"],location:p},location:p}],location:p},location:p},condition:l},...$,{patch:{kind:"patch",op:"unset",path:c,location:p},condition:A});continue}n.push({severity:"error",code:"E_UNSUPPORTED_STMT",message:`Unsupported statement '${a.kind}' in patch text. Only patch statements are allowed.`,location:this.deps.mapLocation(a.location)})}return i}};function Kn(t){return{op:t.patch.op,path:Ci(t.patch.path),...t.condition?{condition:t.condition}:void 0,...t.patch.value?{value:ge(t.patch.value)}:void 0}}function we(t){let e=t.segments,n;for(let r of e){if(r.kind==="propertySegment"){let o={kind:"prop",name:r.name};n?n={kind:"call",fn:"field",args:[n,{kind:"lit",value:r.name}]}:n={kind:"get",path:[o]};continue}if(!n)throw new Error("Path cannot start with index access in compileMelPatch guard.");n={kind:"call",fn:"at",args:[n,ge(r.index)]}}if(!n)throw new Error("Empty patch guard path.");return n}function Ci(t){return t.segments.map(e=>e.kind==="propertySegment"?{kind:"prop",name:e.name}:{kind:"expr",expr:ge(e.index)})}var It=class{and(e,n){return e?n?{kind:"call",fn:"and",args:[e,n]}:e:n}},Mt=class{constructor(e){this.mapLocation=e}symbols={stateTypes:new Map,computedDecls:new Map,typeDefs:new Map,computedTypeCache:new Map,computedTypeInFlight:new Set};validatePath(e,n){for(let r of e.segments)r.kind==="indexSegment"&&this.validateExpr(r.index,n)}validateExpr(e,n){switch(e.kind){case"functionCall":(e.name==="eq"||e.name==="neq")&&e.args.length>=2&&this.validatePrimitiveEquality(e.args[0],e.args[1],e.location,n);for(let r of e.args)this.validateExpr(r,n);return;case"binary":(e.operator==="=="||e.operator==="!=")&&this.validatePrimitiveEquality(e.left,e.right,e.location,n),this.validateExpr(e.left,n),this.validateExpr(e.right,n);return;case"unary":this.validateExpr(e.operand,n);return;case"ternary":this.validateExpr(e.condition,n),this.validateExpr(e.consequent,n),this.validateExpr(e.alternate,n);return;case"propertyAccess":this.validateExpr(e.object,n);return;case"indexAccess":this.validateExpr(e.object,n),this.validateExpr(e.index,n);return;case"objectLiteral":for(let r of e.properties)this.validateExpr(r.value,n);return;case"arrayLiteral":for(let r of e.elements)this.validateExpr(r,n);return;case"literal":case"identifier":case"systemIdent":case"iterationVar":return}}validatePrimitiveEquality(e,n,r,o){let i=G(e,new Map,this.symbols),a=G(n,new Map,this.symbols);i!=="nonprimitive"&&a!=="nonprimitive"||o.push({severity:"error",code:"E_TYPE_MISMATCH",message:"eq/neq operands must be primitive types (null, boolean, number, string)",location:this.mapLocation(r)})}};function Yn(t){let e=[],n=0;for(let r of t)e.push(n),n+=r.length+1;return e}function Qn(t,e){return n=>Xn(n,t,e)}function Dt(t,e,n){return t.map(r=>Pi(r,e,n))}function Pi(t,e,n){return{...t,location:Xn(t.location,e,n)}}function Xn(t,e,n){return{...t,start:Wn(t.start,e,n),end:Wn(t.end,e,n)}}function Wn(t,e,n){let r=t.line-3,o=e.length,i=Math.min(Math.max(r,1),o),a=n[i-1]??0,s=e[i-1]??"",c=Math.max(s.length+1,1),l=Math.min(Math.max(t.column-6,1),c);return{line:i,column:l,offset:Math.max(a+l-1,0)}}var Ce="__compileMelPatch",Mi="__patchDomain",Di=" ";function Jn(t,e){let n=[],r=[],o=[],i=t.split(`
|
|
9
|
-
`),a=Yn(i),s=Qn(i,a),c=Oi(t,Ce),l=performance.now(),d;try{let x=Pe(c);d=x.tokens;let M=Dt(x.diagnostics.filter(J=>J.severity==="error"),i,a);if(M.length>0)return o.push(...M),n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}}),{ops:[],trace:n,warnings:r,errors:o}}catch(x){return o.push({severity:"error",code:"E_LEX",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-l}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-l,details:{tokenCount:d.length}});let p=performance.now(),f;try{let x=Ie(d),M=Dt(x.diagnostics,i,a),J=M.filter(Xe=>Xe.severity==="error"),j=M.filter(Xe=>Xe.severity!=="error");if(J.length>0)return o.push(...J),r.push(...j),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};if(!x.program)return o.push({severity:"error",code:"E_PARSE",message:"Failed to parse MEL patch program",location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),r.push(...j),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o};f=x.program,r.push(...j)}catch(x){return o.push({severity:"error",code:"E_PARSE",message:x.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-p}),{ops:[],trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-p});let m=performance.now(),A={actionName:e.actionName,onceCounter:0,onceIntentCounter:0,whenCounter:0},b=f.domain.members.find(x=>x.kind==="action"&&x.name===Ce);if(!b)return o.push({severity:"error",code:"E_ANALYZE",message:`Synthetic patch action '${Ce}' not found during parsing`,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"analyze",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:r,errors:o};let $=i.length+3+2;if(b.location.end.line!==$)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ce}'.`,location:s(b.location)}),n.push({phase:"analyze",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:r,errors:o};let[H]=b.body;if(!H||H.kind!=="when"||!Hn(H.condition)||b.body.length!==1)return o.push({severity:"error",code:"E_PATCH_WRAPPER",message:`Malformed synthetic patch wrapper for action '${Ce}'.`,location:s(b.location)}),n.push({phase:"analyze",durationMs:performance.now()-m}),{ops:[],trace:n,warnings:r,errors:o};let E=new Qe({mapLocation:s,toMelExpr:ge}).collect(H.body,o,A,void 0);if(o.length===0&&t.trim()!==""&&E.length===0&&o.push({severity:"error",code:"E_PATCH_WRAPPER",message:"Patch wrapper parsing produced no patch statements. The patch source may be malformed.",location:s(H.location)}),n.push({phase:"analyze",durationMs:performance.now()-m,details:{count:E.length}}),o.length>0)return{ops:[],trace:n,warnings:r,errors:o};let L=performance.now(),X={mode:"action",allowSysPaths:e.allowSysPaths??{prefixes:["meta","input"]},fnTableVersion:e.fnTableVersion??"1.0",actionName:e.actionName},K=[];for(let x of E)try{let M=Kn(x);K.push(Ge(M,X))}catch(M){M instanceof _?o.push({severity:"error",code:M.code,message:M.message,location:s(x.patch.location)}):M instanceof Error?o.push({severity:"error",code:"E_LOWER",message:M.message,location:s(x.patch.location)}):o.push({severity:"error",code:"E_LOWER",message:"Unknown lowering failure",location:s(x.patch.location)})}return n.push({phase:"lower",durationMs:performance.now()-L,details:{count:K.length}}),o.length>0?{ops:[],trace:n,warnings:r,errors:o}:{ops:K,trace:n,warnings:r,errors:o}}function Oi(t,e){let n=t.split(`
|
|
10
|
-
`).map(r=>`${Di}${r}`).join(`
|
|
11
|
-
`);return[`domain ${Mi} {`,` action ${e}() {`," when true {",n," }"," }","}"].join(`
|
|
12
|
-
`)}var Ri="3.5.0";function Li(t,e){let n=Zn(t,e);return{schema:n.schema,trace:n.trace,warnings:n.warnings,errors:n.errors}}function Fi(t,e){let n=Zn(t,e);return n.errors.length>0||!n.schema||!n.annotations||!n.sourceMap?{module:null,trace:n.trace,warnings:n.warnings,errors:n.errors}:{module:ji(n.schema,n.annotations,n.sourceMap),trace:n.trace,warnings:n.warnings,errors:n.errors}}function Zn(t,e){let n=[],r=[],o=[],i=performance.now(),a;try{let E=Pe(t);a=E.tokens;let L=E.diagnostics.filter(K=>K.severity==="error");if(L.length>0)return o.push(...L),n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o};let X=E.diagnostics.filter(K=>K.severity==="warning");r.push(...X)}catch(E){let L=E;return o.push({severity:"error",code:"E_LEX",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"lex",durationMs:performance.now()-i}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"lex",durationMs:performance.now()-i,details:{tokenCount:a.length}});let s=performance.now(),c;try{let E=Ie(a),L=E.diagnostics.filter(X=>X.severity==="error");if(L.length>0)return o.push(...L),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};c=E.program}catch(E){let L=E;return o.push({severity:"error",code:"E_PARSE",message:L.message,location:{start:{line:1,column:1,offset:0},end:{line:1,column:1,offset:0}}}),n.push({phase:"parse",durationMs:performance.now()-s}),{program:null,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:o}}n.push({phase:"parse",durationMs:performance.now()-s});let l=performance.now(),d=Mn(c),p=d.diagnostics.filter(E=>E.severity==="error"),f=d.diagnostics.filter(E=>E.severity==="warning"),m=Ut(d.program),A=dn(d.program),b=[...p,...m.diagnostics.filter(E=>E.severity==="error"),...A.diagnostics.filter(E=>E.severity==="error")],$=[...f,...m.diagnostics.filter(E=>E.severity==="warning"),...A.diagnostics.filter(E=>E.severity==="warning")];if(r.push(...$),n.push({phase:"analyze",durationMs:performance.now()-l}),b.length>0)return o.push(...b),{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};let H=performance.now(),oe=En(d.program);n.push({phase:"generate",durationMs:performance.now()-H});for(let E of oe.diagnostics)E.severity==="warning"?r.push(E):o.push(E);if(oe.schema){let E=vn(d.program,oe.schema),L=E.diagnostics.filter(j=>j.severity==="warning"),X=E.diagnostics.filter(j=>j.severity==="error");if(r.push(...L),o.push(...X),X.length>0)return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)};let K=zn(Ri),x=Vn(d.program,t,oe.schema,K),M=x.diagnostics.filter(j=>j.severity==="warning"),J=x.diagnostics.filter(j=>j.severity==="error");return r.push(...M),o.push(...J),J.length>0?{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)}:{program:d.program,schema:oe.schema,annotations:E.annotations,sourceMap:x.sourceMap,trace:n,warnings:r,errors:Ee(o)}}return{program:d.program,schema:null,annotations:null,sourceMap:null,trace:n,warnings:r,errors:Ee(o)}}function ji(t,e,n){return Object.freeze({schema:t,graph:Rt(Rn(t)),annotations:e,sourceMap:n})}function Rt(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let e of t)Rt(e);return Object.freeze(t)}for(let e of Object.values(t))Rt(e);return Object.freeze(t)}var Ot=10;function Ee(t){if(t.length<=Ot)return t;let e=t.slice(0,Ot);return e.push({severity:"error",code:"E_TOO_MANY",message:`... and ${t.length-Ot} more error(s). Fix the errors above first.`,location:{start:{line:0,column:0,offset:0},end:{line:0,column:0,offset:0}}}),e}function _i(t,e){return Jn(t,e)}export{Je as a,er as b,$i as c,Lt as d,Ft as e,Ze as f,jt as g,_t as h,Bi as i,h as j,et as k,Pe as l,Qi as m,Xi as n,$t as o,tt as p,Gt as q,Zi as r,ea as s,Bt as t,nt as u,Ie as v,Me as w,rt as x,Ut as y,D as z,qt as A,da as B,tr as C,pa as D,ua as E,ft as F,dn as G,mt as H,ht as I,yt as J,gt as K,Or as L,_ as M,je as N,g as O,_e as P,Et as Q,Rr as R,Tt as S,Lr as T,u as U,no as V,io as W,Ge as X,No as Y,En as Z,vn as _,Mn as $,Rn as aa,zn as ba,Vn as ca,Li as da,Fi as ea,_i as fa};
|