vsn 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,9 +1,9 @@
1
1
  var me=(l=>(l.Whitespace="Whitespace",l.Identifier="Identifier",l.Number="Number",l.String="String",l.Template="Template",l.Boolean="Boolean",l.Null="Null",l.Behavior="Behavior",l.Use="Use",l.State="State",l.On="On",l.Construct="Construct",l.Destruct="Destruct",l.Return="Return",l.If="If",l.Else="Else",l.For="For",l.While="While",l.Try="Try",l.Catch="Catch",l.LBrace="LBrace",l.RBrace="RBrace",l.LParen="LParen",l.RParen="RParen",l.LBracket="LBracket",l.RBracket="RBracket",l.Colon="Colon",l.Semicolon="Semicolon",l.Comma="Comma",l.Ellipsis="Ellipsis",l.Dot="Dot",l.Hash="Hash",l.Greater="Greater",l.Less="Less",l.Plus="Plus",l.Minus="Minus",l.Tilde="Tilde",l.Star="Star",l.Slash="Slash",l.Percent="Percent",l.Equals="Equals",l.Arrow="Arrow",l.DoubleEquals="DoubleEquals",l.TripleEquals="TripleEquals",l.NotEquals="NotEquals",l.StrictNotEquals="StrictNotEquals",l.LessEqual="LessEqual",l.GreaterEqual="GreaterEqual",l.And="And",l.Or="Or",l.Pipe="Pipe",l.NullishCoalesce="NullishCoalesce",l.OptionalChain="OptionalChain",l.Bang="Bang",l.At="At",l.Dollar="Dollar",l.Question="Question",l))(me||{});var xe={behavior:"Behavior",use:"Use",state:"State",on:"On",construct:"Construct",destruct:"Destruct",return:"Return",if:"If",else:"Else",for:"For",while:"While",try:"Try",catch:"Catch",true:"Boolean",false:"Boolean",null:"Null"},T=class{constructor(e){this.input=e}index=0;line=1;column=1;pendingTokens=[];templateMode=!1;templateExpressionMode=!1;templateBraceDepth=0;tokenize(){let e=[];for(;!this.eof();){if(this.pendingTokens.length>0){let r=this.pendingTokens.shift();if(r){e.push(r),this.trackTemplateBrace(r);continue}}if(this.templateMode){let r=this.readTemplateChunk();e.push(r);continue}let t=this.peek();if(this.isWhitespace(t)){e.push(this.readWhitespace());continue}if(t==="`"){this.next(),this.templateMode=!0;continue}if(t==="/"&&this.peek(1)==="/"){this.readLineComment();continue}if(t==="/"&&this.peek(1)==="*"){this.readBlockComment();continue}if(this.isAlpha(t)||t==="_"){e.push(this.readIdentifier());continue}if(this.isDigit(t)||t==="-"&&this.isDigit(this.peek(1))){e.push(this.readNumber());continue}if(t==='"'||t==="'"){e.push(this.readString());continue}let s=this.readPunctuator();if(s){e.push(s),this.trackTemplateBrace(s);continue}throw new Error(`Unexpected character '${t}' at ${this.line}:${this.column}`)}return e}readWhitespace(){let e=this.position(),t="";for(;!this.eof()&&this.isWhitespace(this.peek());)t+=this.next();return this.token("Whitespace",t,e)}readLineComment(){for(this.next(),this.next();!this.eof()&&this.peek()!==`
2
2
  `;)this.next()}readBlockComment(){for(this.next(),this.next();!this.eof();){if(this.peek()==="*"&&this.peek(1)==="/"){this.next(),this.next();return}this.next()}}readIdentifier(){let e=this.position(),t="";for(;!this.eof()&&(this.isAlphaNumeric(this.peek())||this.peek()==="_"||this.peek()==="-");)t+=this.next();let s=xe[t];return s?this.token(s,t,e):this.token("Identifier",t,e)}readNumber(){let e=this.position(),t="";for(this.peek()==="-"&&(t+=this.next());!this.eof()&&this.isDigit(this.peek());)t+=this.next();if(this.peek()===".")for(t+=this.next();!this.eof()&&this.isDigit(this.peek());)t+=this.next();return this.token("Number",t,e)}readString(){let e=this.next(),t=this.position(),s="";for(;!this.eof();){let r=this.next();if(r==="\\"){let i=this.next();s+=i;continue}if(r===e)return this.token("String",s,t);s+=r}throw new Error(`Unterminated string at ${t.line}:${t.column}`)}readTemplateChunk(){let e=this.position(),t="";for(;!this.eof();){let s=this.peek();if(s==="`")return this.next(),this.templateMode=!1,this.token("Template",t,e);if(s==="$"&&this.peek(1)==="{"){let r=this.position();this.next();let i=this.position();return this.next(),this.templateMode=!1,this.templateExpressionMode=!0,this.templateBraceDepth=0,this.pendingTokens.push(this.token("Dollar","$",r)),this.pendingTokens.push(this.token("LBrace","{",i)),this.token("Template",t,e)}if(s==="\\"){this.next();let r=this.next();t+=r;continue}t+=this.next()}throw new Error(`Unterminated template literal at ${e.line}:${e.column}`)}readPunctuator(){let e=this.position(),t=this.peek(),s=this.peek(1);if(t==="="&&s==="="&&this.peek(2)==="=")return this.next(),this.next(),this.next(),this.token("TripleEquals","===",e);if(t==="="&&s==="=")return this.next(),this.next(),this.token("DoubleEquals","==",e);if(t==="="&&s===">")return this.next(),this.next(),this.token("Arrow","=>",e);if(t==="!"&&s==="="&&this.peek(2)==="=")return this.next(),this.next(),this.next(),this.token("StrictNotEquals","!==",e);if(t==="!"&&s==="=")return this.next(),this.next(),this.token("NotEquals","!=",e);if(t==="<"&&s==="=")return this.next(),this.next(),this.token("LessEqual","<=",e);if(t===">"&&s==="=")return this.next(),this.next(),this.token("GreaterEqual",">=",e);if(t==="&"&&s==="&")return this.next(),this.next(),this.token("And","&&",e);if(t==="|"&&s==="|")return this.next(),this.next(),this.token("Or","||",e);if(t==="?"&&s==="?")return this.next(),this.next(),this.token("NullishCoalesce","??",e);if(t==="?"&&s===".")return this.next(),this.next(),this.token("OptionalChain","?.",e);if(t==="|"&&s===">")return this.next(),this.next(),this.token("Pipe","|>",e);if(t==="."&&s==="."&&this.peek(2)===".")return this.next(),this.next(),this.next(),this.token("Ellipsis","...",e);let i={"{":"LBrace","}":"RBrace","(":"LParen",")":"RParen","[":"LBracket","]":"RBracket",":":"Colon",";":"Semicolon",",":"Comma",".":"Dot","#":"Hash",">":"Greater","<":"Less","+":"Plus","-":"Minus","~":"Tilde","*":"Star","/":"Slash","%":"Percent","=":"Equals","!":"Bang","@":"At",$:"Dollar","?":"Question"}[t];return i?(this.next(),this.token(i,t,e)):null}trackTemplateBrace(e){this.templateExpressionMode&&(e.type==="LBrace"?this.templateBraceDepth+=1:e.type==="RBrace"&&(this.templateBraceDepth-=1,this.templateBraceDepth<=0&&(this.templateExpressionMode=!1,this.templateMode=!0)))}token(e,t,s){return{type:e,value:t,start:s,end:this.position()}}position(){return{index:this.index,line:this.line,column:this.column}}peek(e=0){return this.input[this.index+e]??""}next(){let e=this.input[this.index++]??"";return e===`
3
3
  `?(this.line+=1,this.column=1):this.column+=1,e}eof(){return this.index>=this.input.length}isWhitespace(e){return e===" "||e===" "||e===`
4
- `||e==="\r"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}isDigit(e){return e>="0"&&e<="9"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}};var u=class{constructor(e){this.type=e}async prepare(e){}async evaluate(e){}};async function ce(c,e){let t=c.scope;if(!t||!t.createChild)return e.evaluate(c);let s=c.scope;c.scope=t.createChild();try{return await e.evaluate(c)}finally{c.scope=s}}var j=class extends u{constructor(t,s=[]){super("Program");this.behaviors=t;this.uses=s}},G=class extends u{constructor(t,s){super("Use");this.name=t;this.alias=s}},y=class extends u{constructor(t){super("Block");this.statements=t}async evaluate(t){for(let s of this.statements){if(t.returning)break;s&&typeof s.evaluate=="function"&&await s.evaluate(t)}}},K=class extends u{constructor(t){super("Selector");this.selectorText=t}},C=class extends u{constructor(t,s){super("Behavior");this.selector=t;this.body=s}},Q=class extends u{constructor(t,s,r){super("StateEntry");this.name=t;this.value=s;this.important=r}},_=class extends u{constructor(t){super("StateBlock");this.entries=t}},b=class extends u{constructor(t,s,r,i=[]){super("OnBlock");this.eventName=t;this.args=s;this.body=r;this.modifiers=i}},B=class extends u{constructor(t,s){super("Assignment");this.target=t;this.value=s}async evaluate(t){if(!t.scope||!t.scope.setPath)return;let s=await this.value.evaluate(t);if(this.target instanceof m&&this.target.name.startsWith("root.")&&t.rootScope){let r=this.target.name.slice(5);return t.rootScope.setPath?.(`self.${r}`,s),s}return this.assignTarget(t,this.target,s),s}assignTarget(t,s,r){if(!(!t.scope||!t.scope.setPath)){if(s instanceof m){t.scope.setPath(s.name,r);return}if(s instanceof H){let i=Array.isArray(r)?r:[],n=0;for(let a of s.elements){if(a instanceof I){t.scope.setPath(a.target.name,i.slice(n));return}if(a===null){n+=1;continue}this.assignTarget(t,a,i[n]),n+=1}return}if(s instanceof M){let i=r&&typeof r=="object"?r:{},n=new Set;for(let a of s.entries){if("rest"in a){let o={};for(let p of Object.keys(i))n.has(p)||(o[p]=i[p]);t.scope.setPath(a.rest.name,o);continue}n.add(a.key),this.assignTarget(t,a.target,i[a.key])}return}}}},D=class extends u{constructor(t){super("Return");this.value=t}async evaluate(t){return t.returning||(t.returnValue=this.value?await this.value.evaluate(t):void 0,t.returning=!0),t.returnValue}},Z=class extends u{constructor(t,s,r){super("If");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){if(await this.test.evaluate(t))return ce(t,this.consequent);if(this.alternate)return ce(t,this.alternate)}},J=class extends u{constructor(t,s){super("While");this.test=t;this.body=s}async evaluate(t){let s=t.scope;t.scope?.createChild&&(t.scope=t.scope.createChild());try{for(;await this.test.evaluate(t)&&(await this.body.evaluate(t),!t.returning););}finally{t.scope=s}}},Y=class extends u{constructor(t,s,r,i){super("For");this.init=t;this.test=s;this.update=r;this.body=i}async evaluate(t){this.init&&await this.init.evaluate(t);let s=t.scope,r=t.scope;for(t.scope?.createChild&&(r=t.scope.createChild());(!this.test||await this.test.evaluate(t))&&(t.scope=r,await this.body.evaluate(t),!t.returning);)t.scope=s,this.update&&await this.update.evaluate(t);t.scope=s}},X=class extends u{constructor(t,s,r){super("Try");this.body=t;this.errorName=s;this.handler=r}async evaluate(t){try{return await ce(t,this.body)}catch(s){if(t.returning)return t.returnValue;let r=t.scope,i=t.scope;t.scope?.createChild&&(i=t.scope.createChild()),t.scope=i;let n=t.scope,a;n&&(a=n.getPath(this.errorName),n.setPath&&n.setPath(`self.${this.errorName}`,s)),await this.handler.evaluate(t),n&&n.setPath&&i===r&&n.setPath(this.errorName,a),t.scope=r}}},L=class extends u{constructor(t,s,r,i=!1){super("FunctionDeclaration");this.name=t;this.params=s;this.body=r;this.isAsync=i}},N=class extends u{constructor(t,s,r=!1){super("FunctionExpression");this.params=t;this.body=s;this.isAsync=r}async evaluate(t){let s=t.scope,r=t.globals,i=t.element;return async(...n)=>{let a=s?.createChild?s.createChild():s,o={scope:a,rootScope:t.rootScope,...r?{globals:r}:{},...i?{element:i}:{},returnValue:void 0,returning:!1};if(a){let p=new Map;await this.applyParams(a,p,o,n),await this.body.evaluate(o),a===s&&this.restoreParams(a,p)}else await this.body.evaluate(o);return o.returnValue}}async applyParams(t,s,r,i){if(!t||!t.setPath)return;let n=0;for(let a of this.params){let o=a.name;if(!o)continue;if(s.set(o,t.getPath(o)),a.rest){t.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let p=i[n];p===void 0&&a.defaultValue&&(p=await a.defaultValue.evaluate(r)),t.setPath(`self.${o}`,p),n+=1}}restoreParams(t,s){if(!(!t||!t.setPath))for(let r of this.params){let i=r.name;i&&t.setPath(i,s.get(i))}}},F=class extends u{constructor(t,s,r,i,n){super("Declaration");this.target=t;this.operator=s;this.value=r;this.flags=i;this.flagArgs=n}},m=class extends u{constructor(t){super("Identifier");this.name=t}async evaluate(t){if(this.name.startsWith("root.")&&t.rootScope){let s=this.name.slice(5);return t.rootScope.getPath(`self.${s}`)}if(t.scope){let s=t.scope.getPath(this.name),r=this.name.split(".")[0];if(this.name.startsWith("parent.")||this.name.startsWith("root.")||this.name.startsWith("self.")||s!==void 0||r&&t.scope.hasKey?.(r))return s}return t.globals?t.globals[this.name]:void 0}},R=class extends u{constructor(t){super("SpreadElement");this.value=t}},I=class extends u{constructor(t){super("RestElement");this.target=t}},H=class extends u{constructor(t){super("ArrayPattern");this.elements=t}},M=class extends u{constructor(t){super("ObjectPattern");this.entries=t}},k=class extends u{constructor(t){super("Literal");this.value=t}async evaluate(){return this.value}},ee=class extends u{constructor(t){super("TemplateExpression");this.parts=t}async evaluate(t){let s="";for(let r of this.parts){let i=await r.evaluate(t);s+=i==null?"":String(i)}return s}},O=class extends u{constructor(t,s){super("UnaryExpression");this.operator=t;this.argument=s}async evaluate(t){let s=await this.argument.evaluate(t);return this.operator==="!"?!s:this.operator==="-"?-s:s}},v=class extends u{constructor(t,s,r){super("BinaryExpression");this.operator=t;this.left=s;this.right=r}async evaluate(t){if(this.operator==="&&")return await this.left.evaluate(t)&&await this.right.evaluate(t);if(this.operator==="||")return await this.left.evaluate(t)||await this.right.evaluate(t);if(this.operator==="??")return await this.left.evaluate(t)??await this.right.evaluate(t);let s=await this.left.evaluate(t),r=await this.right.evaluate(t);if(this.operator==="+")return s+r;if(this.operator==="-")return s-r;if(this.operator==="*")return s*r;if(this.operator==="/")return s/r;if(this.operator==="%")return s%r;if(this.operator==="==")return s==r;if(this.operator==="!=")return s!=r;if(this.operator==="===")return s===r;if(this.operator==="!==")return s!==r;if(this.operator==="<")return s<r;if(this.operator===">")return s>r;if(this.operator==="<=")return s<=r;if(this.operator===">=")return s>=r}},te=class extends u{constructor(t,s,r){super("TernaryExpression");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){return await this.test.evaluate(t)?this.consequent.evaluate(t):this.alternate.evaluate(t)}},S=class c extends u{constructor(t,s,r=!1){super("MemberExpression");this.target=t;this.property=s;this.optional=r}async evaluate(t){return(await this.resolve(t))?.value}async resolve(t){let s=this.getIdentifierPath();if(s){let i=this.resolveFromScope(t,s);if(i)return i;let n=this.resolveFromGlobals(t,s);if(n)return n}let r=await this.target.evaluate(t);return r==null?{value:void 0,target:r,optional:this.optional}:{value:r[this.property],target:r,optional:this.optional}}getIdentifierPath(){let t=this.getTargetIdentifierPath();return t?{path:`${t.path}.${this.property}`,root:t.root}:void 0}getTargetIdentifierPath(){if(this.target instanceof m){let t=this.target.name,s=t.split(".")[0];return s?{path:t,root:s}:void 0}if(this.target instanceof c)return this.target.getIdentifierPath()}resolveFromScope(t,s){if(!t.scope)return;if(s.path.startsWith("root.")&&t.rootScope){let o=s.path.slice(5),p=t.rootScope.getPath(`self.${o}`),h=o.split(".").slice(0,-1).join("."),d=h?t.rootScope.getPath(`self.${h}`):t.rootScope;return{value:p,target:d,optional:this.optional}}let r=t.scope.getPath(s.path);if(!(s.path.startsWith("parent.")||s.path.startsWith("root.")||s.path.startsWith("self."))&&r===void 0&&!t.scope.hasKey?.(s.root))return;let n=this.getTargetPath(s.path),a=n?t.scope.getPath(n):void 0;return{value:r,target:a,optional:this.optional}}resolveFromGlobals(t,s){let r=t.globals??{};if(!s.root||!(s.root in r))return;let i=r[s.root],n,a=s.path.split(".");for(let o=1;o<a.length;o+=1){n=i;let p=a[o];if(!p)return{value:void 0,target:n,optional:this.optional};i=i?.[p]}return{value:i,target:n,optional:this.optional}}getTargetPath(t){let s=t.split(".");if(!(s.length<=1))return s.slice(0,-1).join(".")}},w=class extends u{constructor(t,s){super("CallExpression");this.callee=t;this.args=s}async evaluate(t){let s=await this.resolveCallee(t),r=s?.fn??await this.callee.evaluate(t);if(typeof r!="function")return;let i=[];for(let n of this.args)i.push(await n.evaluate(t));return r.apply(s?.thisArg,i)}async resolveCallee(t){if(this.callee instanceof S){let p=await this.callee.resolve(t);return p?{fn:p.value,thisArg:p.target}:void 0}if(!(this.callee instanceof m))return;let s=this.callee.name,r=t.globals??{},i=s.split("."),n=i[0];if(!n||!(n in r)){if(i.length>1&&t.scope){let p=i.slice(0,-1).join("."),h=i[i.length-1];if(!h)return;let d=t.scope.getPath(p);return d==null?void 0:{fn:d?.[h],thisArg:d}}return}let a=r[n],o;for(let p=1;p<i.length;p+=1){o=a;let h=i[p];if(!h)return;a=a?.[h]}return{fn:a,thisArg:o}}},se=class extends u{constructor(t){super("ArrayExpression");this.elements=t}async evaluate(t){let s=[];for(let r of this.elements){if(r instanceof R){let i=await r.value.evaluate(t);if(i==null)continue;if(typeof i[Symbol.iterator]=="function")for(let a of i)s.push(a);else s.push(i);continue}s.push(await r.evaluate(t))}return s}},re=class extends u{constructor(t){super("ObjectExpression");this.entries=t}async evaluate(t){let s={};for(let r of this.entries){if("spread"in r){let i=await r.spread.evaluate(t);i!=null&&Object.assign(s,i);continue}if("computed"in r&&r.computed){let i=await r.keyExpr.evaluate(t);s[String(i)]=await r.value.evaluate(t)}else s[r.key]=await r.value.evaluate(t)}return s}},ie=class extends u{constructor(t,s){super("IndexExpression");this.target=t;this.index=s}async evaluate(t){let s=await this.target.evaluate(t);if(s==null)return;let r=await this.index.evaluate(t);if(r!=null)return s[r]}},x=class extends u{constructor(t,s){super("Directive");this.kind=t;this.name=s}async evaluate(t){let s=t.element;if(!s)return`${this.kind}:${this.name}`;if(this.kind==="attr")return this.name==="value"&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement)?s.value:this.name==="checked"&&s instanceof HTMLInputElement?s.checked:this.name==="html"&&s instanceof HTMLElement?s.innerHTML:s.getAttribute(this.name)??void 0;if(this.kind==="style"&&s instanceof HTMLElement)return s.style.getPropertyValue(this.name)??void 0}},q=class extends u{constructor(t){super("AwaitExpression");this.argument=t}async evaluate(t){return await await this.argument.evaluate(t)}},ne=class extends u{constructor(t,s){super("Query");this.direction=t;this.selector=s}async evaluate(t){let s=this.selector.trim();if(!s)return[];if(this.direction==="ancestor"){let i=[],n=t.element?.parentElement;for(;n;)n.matches(s)&&i.push(n),n=n.parentElement;return i}let r=this.direction==="descendant"?t.element??(typeof document<"u"?document:void 0):typeof document<"u"?document:void 0;return!r||!("querySelectorAll"in r)?[]:Array.from(r.querySelectorAll(s))}};var ae=class{constructor(e){this.tokens=e}index=0;peek(e=0){return this.tokens[this.index+e]??null}next(){let e=this.tokens[this.index++];if(!e)throw new Error("Unexpected end of input");return e}eof(){return this.index>=this.tokens.length}match(e){return this.peek()?.type===e?(this.next(),!0):!1}expect(e){let t=this.next();if(t.type!==e)throw new Error(`Expected ${e} but got ${t.type}`);return t}skipWhitespace(){for(;this.peek()?.type==="Whitespace";)this.next()}peekNonWhitespace(e=0){let t=0;for(let s=this.index;s<this.tokens.length;s++){let r=this.tokens[s];if(r.type!=="Whitespace"){if(t===e)return r;t+=1}}return null}};var W=class c{stream;source;customFlags;allowImplicitSemicolon=!1;awaitStack=[];constructor(e,t){this.source=e,this.customFlags=t?.customFlags??new Set;let s=new T(e);this.stream=new ae(s.tokenize())}static parseInline(e){return new c(`{${e}}`).parseInlineBlock()}parseProgram(){return this.wrapErrors(()=>{let e=[],t=[];for(this.stream.skipWhitespace();!this.stream.eof();){let s=this.stream.peek();if(!s)break;s.type==="Use"?t.push(this.parseUseStatement()):e.push(this.parseBehavior()),this.stream.skipWhitespace()}return new j(e,t)})}parseInlineBlock(){return this.wrapErrors(()=>(this.stream.skipWhitespace(),this.allowImplicitSemicolon=!0,this.parseBlock({allowDeclarations:!1})))}parseBehavior(){return this.wrapErrors(()=>{this.stream.skipWhitespace(),this.stream.expect("Behavior");let e=this.parseSelector(),t=this.parseBlock({allowDeclarations:!0});return new C(e,t)})}parseSelector(){let e="",t=!1;for(;;){let s=this.stream.peek();if(!s||s.type==="LBrace")break;if(s.type==="Whitespace"){this.stream.next(),t&&e[e.length-1]!==" "&&(e+=" ");continue}t=!0,e+=this.stream.next().value}if(!e.trim())throw new Error("Behavior selector is required");return new K(e.trim())}parseUseStatement(){return this.wrapErrors(()=>{this.stream.expect("Use"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace();let t=e,s=this.stream.peek();return s?.type==="Identifier"&&s.value==="as"&&(this.stream.next(),this.stream.skipWhitespace(),t=this.stream.expect("Identifier").value),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new G(e,t)})}wrapErrors(e){try{return e()}catch(t){throw t instanceof Error&&!/\(line\s+\d+, column\s+\d+\)/i.test(t.message)?new Error(this.formatError(t.message)):t}}formatError(e){let t=this.stream.peek()??this.stream.peekNonWhitespace(0);if(!t)return`Parse error: ${e}`;let s=t.start.line,r=t.start.column,i=this.getLineSnippet(s,r);return`Parse error (line ${s}, column ${r}): ${e}
4
+ `||e==="\r"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}isDigit(e){return e>="0"&&e<="9"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}};var u=class{constructor(e){this.type=e}async prepare(e){}async evaluate(e){}};async function pe(p,e){let t=p.scope;if(!t||!t.createChild)return e.evaluate(p);let s=p.scope;p.scope=t.createChild();try{return await e.evaluate(p)}finally{p.scope=s}}var j=class extends u{constructor(t,s=[]){super("Program");this.behaviors=t;this.uses=s}},G=class extends u{constructor(t,s,r={},i={}){super("Use");this.name=t;this.alias=s;this.flags=r;this.flagArgs=i}},y=class extends u{constructor(t){super("Block");this.statements=t}async evaluate(t){for(let s of this.statements){if(t.returning)break;s&&typeof s.evaluate=="function"&&await s.evaluate(t)}}},K=class extends u{constructor(t){super("Selector");this.selectorText=t}},C=class extends u{constructor(t,s){super("Behavior");this.selector=t;this.body=s}},Q=class extends u{constructor(t,s,r){super("StateEntry");this.name=t;this.value=s;this.important=r}},_=class extends u{constructor(t){super("StateBlock");this.entries=t}},b=class extends u{constructor(t,s,r,i=[]){super("OnBlock");this.eventName=t;this.args=s;this.body=r;this.modifiers=i}},B=class extends u{constructor(t,s,r="="){super("Assignment");this.target=t;this.value=s;this.operator=r}async evaluate(t){if(!t.scope||!t.scope.setPath)return;let s=await this.value.evaluate(t);if(this.operator!=="=")return this.applyCompoundAssignment(t,s);if(this.target instanceof m&&this.target.name.startsWith("root.")&&t.rootScope){let r=this.target.name.slice(5);return t.rootScope.setPath?.(`self.${r}`,s),s}return this.assignTarget(t,this.target,s),s}applyCompoundAssignment(t,s){if(!t.scope||!t.scope.setPath)return;if(!(this.target instanceof m))throw new Error("Compound assignment requires a simple identifier");let r=this.target.name.startsWith("root."),i=r&&t.rootScope?t.rootScope:t.scope,n=r?this.target.name.slice(5):this.target.name,a=r?`self.${n}`:n,o=i?.getPath?i.getPath(a):void 0,c;return this.operator==="+="?c=o+s:this.operator==="-="?c=o-s:this.operator==="*="?c=o*s:c=o/s,i?.setPath?.(a,c),c}assignTarget(t,s,r){if(!(!t.scope||!t.scope.setPath)){if(s instanceof m){t.scope.setPath(s.name,r);return}if(s instanceof H){let i=Array.isArray(r)?r:[],n=0;for(let a of s.elements){if(a instanceof M){t.scope.setPath(a.target.name,i.slice(n));return}if(a===null){n+=1;continue}this.assignTarget(t,a,i[n]),n+=1}return}if(s instanceof I){let i=r&&typeof r=="object"?r:{},n=new Set;for(let a of s.entries){if("rest"in a){let o={};for(let c of Object.keys(i))n.has(c)||(o[c]=i[c]);t.scope.setPath(a.rest.name,o);continue}n.add(a.key),this.assignTarget(t,a.target,i[a.key])}return}}}},D=class extends u{constructor(t){super("Return");this.value=t}async evaluate(t){return t.returning||(t.returnValue=this.value?await this.value.evaluate(t):void 0,t.returning=!0),t.returnValue}},Z=class extends u{constructor(t,s,r){super("If");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){if(await this.test.evaluate(t))return pe(t,this.consequent);if(this.alternate)return pe(t,this.alternate)}},J=class extends u{constructor(t,s){super("While");this.test=t;this.body=s}async evaluate(t){let s=t.scope;t.scope?.createChild&&(t.scope=t.scope.createChild());try{for(;await this.test.evaluate(t)&&(await this.body.evaluate(t),!t.returning););}finally{t.scope=s}}},Y=class extends u{constructor(t,s,r,i){super("For");this.init=t;this.test=s;this.update=r;this.body=i}async evaluate(t){this.init&&await this.init.evaluate(t);let s=t.scope,r=t.scope;for(t.scope?.createChild&&(r=t.scope.createChild());(!this.test||await this.test.evaluate(t))&&(t.scope=r,await this.body.evaluate(t),!t.returning);)t.scope=s,this.update&&await this.update.evaluate(t);t.scope=s}},X=class extends u{constructor(t,s,r){super("Try");this.body=t;this.errorName=s;this.handler=r}async evaluate(t){try{return await pe(t,this.body)}catch(s){if(t.returning)return t.returnValue;let r=t.scope,i=t.scope;t.scope?.createChild&&(i=t.scope.createChild()),t.scope=i;let n=t.scope,a;n&&(a=n.getPath(this.errorName),n.setPath&&n.setPath(`self.${this.errorName}`,s)),await this.handler.evaluate(t),n&&n.setPath&&i===r&&n.setPath(this.errorName,a),t.scope=r}}},L=class extends u{constructor(t,s,r,i=!1){super("FunctionDeclaration");this.name=t;this.params=s;this.body=r;this.isAsync=i}},S=class extends u{constructor(t,s,r=!1){super("FunctionExpression");this.params=t;this.body=s;this.isAsync=r}async evaluate(t){let s=t.scope,r=t.globals,i=t.element;return async(...n)=>{let a=s?.createChild?s.createChild():s,o={scope:a,rootScope:t.rootScope,...r?{globals:r}:{},...i?{element:i}:{},returnValue:void 0,returning:!1};if(a){let c=new Map;await this.applyParams(a,c,o,n),await this.body.evaluate(o),a===s&&this.restoreParams(a,c)}else await this.body.evaluate(o);return o.returnValue}}async applyParams(t,s,r,i){if(!t||!t.setPath)return;let n=0;for(let a of this.params){let o=a.name;if(!o)continue;if(s.set(o,t.getPath(o)),a.rest){t.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let c=i[n];c===void 0&&a.defaultValue&&(c=await a.defaultValue.evaluate(r)),t.setPath(`self.${o}`,c),n+=1}}restoreParams(t,s){if(!(!t||!t.setPath))for(let r of this.params){let i=r.name;i&&t.setPath(i,s.get(i))}}},F=class extends u{constructor(t,s,r,i,n){super("Declaration");this.target=t;this.operator=s;this.value=r;this.flags=i;this.flagArgs=n}},m=class extends u{constructor(t){super("Identifier");this.name=t}async evaluate(t){if(this.name.startsWith("root.")&&t.rootScope){let s=this.name.slice(5);return t.rootScope.getPath(`self.${s}`)}if(t.scope){let s=t.scope.getPath(this.name),r=this.name.split(".")[0];if(this.name.startsWith("parent.")||this.name.startsWith("root.")||this.name.startsWith("self.")||s!==void 0||r&&t.scope.hasKey?.(r))return s}return t.globals?t.globals[this.name]:void 0}},R=class extends u{constructor(t){super("SpreadElement");this.value=t}},M=class extends u{constructor(t){super("RestElement");this.target=t}},H=class extends u{constructor(t){super("ArrayPattern");this.elements=t}},I=class extends u{constructor(t){super("ObjectPattern");this.entries=t}},k=class extends u{constructor(t){super("Literal");this.value=t}async evaluate(){return this.value}},ee=class extends u{constructor(t){super("TemplateExpression");this.parts=t}async evaluate(t){let s="";for(let r of this.parts){let i=await r.evaluate(t);s+=i==null?"":String(i)}return s}},O=class extends u{constructor(t,s){super("UnaryExpression");this.operator=t;this.argument=s}async evaluate(t){let s=await this.argument.evaluate(t);return this.operator==="!"?!s:this.operator==="-"?-s:s}},v=class extends u{constructor(t,s,r){super("BinaryExpression");this.operator=t;this.left=s;this.right=r}async evaluate(t){if(this.operator==="&&")return await this.left.evaluate(t)&&await this.right.evaluate(t);if(this.operator==="||")return await this.left.evaluate(t)||await this.right.evaluate(t);if(this.operator==="??")return await this.left.evaluate(t)??await this.right.evaluate(t);let s=await this.left.evaluate(t),r=await this.right.evaluate(t);if(this.operator==="+")return s+r;if(this.operator==="-")return s-r;if(this.operator==="*")return s*r;if(this.operator==="/")return s/r;if(this.operator==="%")return s%r;if(this.operator==="==")return s==r;if(this.operator==="!=")return s!=r;if(this.operator==="===")return s===r;if(this.operator==="!==")return s!==r;if(this.operator==="<")return s<r;if(this.operator===">")return s>r;if(this.operator==="<=")return s<=r;if(this.operator===">=")return s>=r}},te=class extends u{constructor(t,s,r){super("TernaryExpression");this.test=t;this.consequent=s;this.alternate=r}async evaluate(t){return await this.test.evaluate(t)?this.consequent.evaluate(t):this.alternate.evaluate(t)}},N=class p extends u{constructor(t,s,r=!1){super("MemberExpression");this.target=t;this.property=s;this.optional=r}async evaluate(t){return(await this.resolve(t))?.value}async resolve(t){let s=this.getIdentifierPath();if(s){let i=this.resolveFromScope(t,s);if(i)return i;let n=this.resolveFromGlobals(t,s);if(n)return n}let r=await this.target.evaluate(t);return r==null?{value:void 0,target:r,optional:this.optional}:{value:r[this.property],target:r,optional:this.optional}}getIdentifierPath(){let t=this.getTargetIdentifierPath();return t?{path:`${t.path}.${this.property}`,root:t.root}:void 0}getTargetIdentifierPath(){if(this.target instanceof m){let t=this.target.name,s=t.split(".")[0];return s?{path:t,root:s}:void 0}if(this.target instanceof p)return this.target.getIdentifierPath()}resolveFromScope(t,s){if(!t.scope)return;if(s.path.startsWith("root.")&&t.rootScope){let o=s.path.slice(5),c=t.rootScope.getPath(`self.${o}`),h=o.split(".").slice(0,-1).join("."),f=h?t.rootScope.getPath(`self.${h}`):t.rootScope;return{value:c,target:f,optional:this.optional}}let r=t.scope.getPath(s.path);if(!(s.path.startsWith("parent.")||s.path.startsWith("root.")||s.path.startsWith("self."))&&r===void 0&&!t.scope.hasKey?.(s.root))return;let n=this.getTargetPath(s.path),a=n?t.scope.getPath(n):void 0;return{value:r,target:a,optional:this.optional}}resolveFromGlobals(t,s){let r=t.globals??{};if(!s.root||!(s.root in r))return;let i=r[s.root],n,a=s.path.split(".");for(let o=1;o<a.length;o+=1){n=i;let c=a[o];if(!c)return{value:void 0,target:n,optional:this.optional};i=i?.[c]}return{value:i,target:n,optional:this.optional}}getTargetPath(t){let s=t.split(".");if(!(s.length<=1))return s.slice(0,-1).join(".")}},w=class extends u{constructor(t,s){super("CallExpression");this.callee=t;this.args=s}async evaluate(t){let s=await this.resolveCallee(t),r=s?.fn??await this.callee.evaluate(t);if(typeof r!="function")return;let i=[];for(let n of this.args)i.push(await n.evaluate(t));return r.apply(s?.thisArg,i)}async resolveCallee(t){if(this.callee instanceof N){let c=await this.callee.resolve(t);return c?{fn:c.value,thisArg:c.target}:void 0}if(!(this.callee instanceof m))return;let s=this.callee.name,r=t.globals??{},i=s.split("."),n=i[0];if(!n||!(n in r)){if(i.length>1&&t.scope){let c=i.slice(0,-1).join("."),h=i[i.length-1];if(!h)return;let f=t.scope.getPath(c);return f==null?void 0:{fn:f?.[h],thisArg:f}}return}let a=r[n],o;for(let c=1;c<i.length;c+=1){o=a;let h=i[c];if(!h)return;a=a?.[h]}return{fn:a,thisArg:o}}},se=class extends u{constructor(t){super("ArrayExpression");this.elements=t}async evaluate(t){let s=[];for(let r of this.elements){if(r instanceof R){let i=await r.value.evaluate(t);if(i==null)continue;if(typeof i[Symbol.iterator]=="function")for(let a of i)s.push(a);else s.push(i);continue}s.push(await r.evaluate(t))}return s}},re=class extends u{constructor(t){super("ObjectExpression");this.entries=t}async evaluate(t){let s={};for(let r of this.entries){if("spread"in r){let i=await r.spread.evaluate(t);i!=null&&Object.assign(s,i);continue}if("computed"in r&&r.computed){let i=await r.keyExpr.evaluate(t);s[String(i)]=await r.value.evaluate(t)}else s[r.key]=await r.value.evaluate(t)}return s}},ie=class extends u{constructor(t,s){super("IndexExpression");this.target=t;this.index=s}async evaluate(t){let s=await this.target.evaluate(t);if(s==null)return;let r=await this.index.evaluate(t);if(r!=null)return s[r]}},x=class extends u{constructor(t,s){super("Directive");this.kind=t;this.name=s}async evaluate(t){let s=t.element;if(!s)return`${this.kind}:${this.name}`;if(this.kind==="attr")return this.name==="value"&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement)?s.value:this.name==="checked"&&s instanceof HTMLInputElement?s.checked:this.name==="html"&&s instanceof HTMLElement?s.innerHTML:s.getAttribute(this.name)??void 0;if(this.kind==="style"&&s instanceof HTMLElement)return s.style.getPropertyValue(this.name)??void 0}},U=class extends u{constructor(t){super("AwaitExpression");this.argument=t}async evaluate(t){return await await this.argument.evaluate(t)}},ne=class extends u{constructor(t,s){super("Query");this.direction=t;this.selector=s}async evaluate(t){let s=this.selector.trim();if(!s)return[];if(this.direction==="ancestor"){let i=[],n=t.element?.parentElement;for(;n;)n.matches(s)&&i.push(n),n=n.parentElement;return i}let r=this.direction==="descendant"?t.element??(typeof document<"u"?document:void 0):typeof document<"u"?document:void 0;return!r||!("querySelectorAll"in r)?[]:Array.from(r.querySelectorAll(s))}};var ae=class{constructor(e){this.tokens=e}index=0;peek(e=0){return this.tokens[this.index+e]??null}next(){let e=this.tokens[this.index++];if(!e)throw new Error("Unexpected end of input");return e}eof(){return this.index>=this.tokens.length}match(e){return this.peek()?.type===e?(this.next(),!0):!1}expect(e){let t=this.next();if(t.type!==e)throw new Error(`Expected ${e} but got ${t.type}`);return t}skipWhitespace(){for(;this.peek()?.type==="Whitespace";)this.next()}peekNonWhitespace(e=0){let t=0;for(let s=this.index;s<this.tokens.length;s++){let r=this.tokens[s];if(r.type!=="Whitespace"){if(t===e)return r;t+=1}}return null}};var A=class p{stream;source;customFlags;allowImplicitSemicolon=!1;awaitStack=[];constructor(e,t){this.source=e,this.customFlags=t?.customFlags??new Set;let s=new T(e);this.stream=new ae(s.tokenize())}static parseInline(e){return new p(`{${e}}`).parseInlineBlock()}parseProgram(){return this.wrapErrors(()=>{let e=[],t=[];for(this.stream.skipWhitespace();!this.stream.eof();){let s=this.stream.peek();if(!s)break;s.type==="Use"?t.push(this.parseUseStatement()):e.push(this.parseBehavior()),this.stream.skipWhitespace()}return new j(e,t)})}parseInlineBlock(){return this.wrapErrors(()=>(this.stream.skipWhitespace(),this.allowImplicitSemicolon=!0,this.parseBlock({allowDeclarations:!1})))}parseBehavior(){return this.wrapErrors(()=>{this.stream.skipWhitespace(),this.stream.expect("Behavior");let e=this.parseSelector(),t=this.parseBlock({allowDeclarations:!0});return new C(e,t)})}parseSelector(){let e="",t=!1;for(;;){let s=this.stream.peek();if(!s||s.type==="LBrace")break;if(s.type==="Whitespace"){this.stream.next(),t&&e[e.length-1]!==" "&&(e+=" ");continue}t=!0,e+=this.stream.next().value}if(!e.trim())throw new Error("Behavior selector is required");return new K(e.trim())}parseUseStatement(){return this.wrapErrors(()=>{this.stream.expect("Use"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace();let t=e,s=this.stream.peek();s?.type==="Identifier"&&s.value==="as"&&(this.stream.next(),this.stream.skipWhitespace(),t=this.stream.expect("Identifier").value);let{flags:r,flagArgs:i}=this.parseUseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new G(e,t,r,i)})}parseUseFlags(){let e={},t={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let s=this.stream.expect("Identifier").value;if(s!=="wait")throw new Error(`Unknown flag ${s}`);if(e.wait=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Number"),i=Number(r.value),n;if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next(),this.stream.skipWhitespace();let a=this.stream.expect("Number");n=Number(a.value),this.stream.skipWhitespace()}this.stream.expect("RParen"),t.wait={timeoutMs:i,...n!==void 0?{intervalMs:n}:{}}}}return{flags:e,flagArgs:t}}wrapErrors(e){try{return e()}catch(t){throw t instanceof Error&&!/\(line\s+\d+, column\s+\d+\)/i.test(t.message)?new Error(this.formatError(t.message)):t}}formatError(e){let t=this.stream.peek()??this.stream.peekNonWhitespace(0);if(!t)return`Parse error: ${e}`;let s=t.start.line,r=t.start.column,i=this.getLineSnippet(s,r);return`Parse error (line ${s}, column ${r}): ${e}
5
5
  ${i}`}getLineSnippet(e,t){let r=this.source.split(/\r?\n/)[e-1]??"",i=`${" ".repeat(Math.max(t-1,0))}^`;return`${r}
6
- ${i}`}parseBlock(e){let t=e?.allowDeclarations??!1;this.stream.skipWhitespace(),this.stream.expect("LBrace");let s=[],r=t,i=!1,n=!1,a=!1;for(;;){this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Unterminated block");if(o.type==="RBrace"){this.stream.next();break}if(t&&o.type==="Behavior"&&(a=!0),t&&a&&o.type!=="Behavior")throw new Error("Nested behaviors must appear after construct, function, and on blocks");if(t&&this.isFunctionDeclarationStart()){i||(n=!0),s.push(this.parseFunctionDeclaration());continue}if(t&&this.isFunctionExpressionAssignmentStart()){if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseAssignment());continue}if(this.isDeclarationStart()){if(!t)throw new Error("Declarations are only allowed at the behavior root");if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseDeclaration())}else{if(r&&(r=!1),t&&o.type==="On"&&!i&&(n=!0),t&&o.type==="Construct"){if(n)throw new Error("Construct blocks must appear before functions and on blocks");i=!0}s.push(this.parseStatement())}}return new y(s)}parseStatement(e){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unexpected end of input");let s=e?.allowBlocks??!0,r=e?.allowReturn??!1;if(t.type==="Return"){if(!r)throw new Error("Return is only allowed inside functions");return this.parseReturnStatement()}if(s&&t.type==="On")return this.parseOnBlock();if(s&&t.type==="If")return this.parseIfBlock();if(s&&t.type==="For")return this.parseForBlock();if(s&&t.type==="While")return this.parseWhileBlock();if(s&&t.type==="Try")return this.parseTryBlock();if(s&&t.type==="Construct")return this.parseConstructBlock();if(s&&t.type==="Destruct")return this.parseDestructBlock();if(s&&t.type==="Behavior")return this.parseBehavior();if(this.isAwaitAllowed()&&t.type==="Identifier"&&t.value==="await")return this.parseExpressionStatement();if(this.isAssignmentStart())return this.parseAssignment();if(this.isExpressionStatementStart())return this.parseExpressionStatement();throw new Error(`Unexpected token ${t.type}`)}parseStateBlock(){this.stream.expect("State"),this.stream.skipWhitespace(),this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated state block");if(t.type==="RBrace"){this.stream.next();break}let s=this.stream.expect("Identifier");this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let r=this.parseExpression();this.stream.skipWhitespace();let i=!1;if(this.stream.peek()?.type==="Bang"){this.stream.next(),this.stream.skipWhitespace();let n=this.stream.next();if(n.type==="Identifier"&&n.value==="important")i=!0;else throw new Error("Expected 'important' after '!'")}this.stream.skipWhitespace(),this.stream.expect("Semicolon"),e.push(new Q(s.value,r,i))}return new _(e)}parseOnBlock(){this.stream.expect("On"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace(),this.stream.expect("LParen");let t=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated on() arguments");if(i.type==="RParen"){this.stream.next();break}if(i.type==="Identifier"){t.push(this.stream.next().value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next();continue}throw new Error(`Unexpected token in on() args: ${i.type}`)}let s=this.parseOnModifiers(),r=this.parseBlock({allowDeclarations:!1});return new b(e,t,r,s)}parseOnModifiers(){let e=[];for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let t=this.stream.expect("Identifier").value;e.push(t)}return e}parseAssignment(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace(),this.stream.expect("Equals"),this.stream.skipWhitespace();let t=this.parseExpression();return this.consumeStatementTerminator(),new B(e,t)}parseExpression(){return this.parsePipeExpression()}parsePipeExpression(){let e=this.parseTernaryExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Pipe";){this.stream.next(),this.stream.skipWhitespace();let t=!1,s=this.stream.peek();this.isAwaitAllowed()&&s?.type==="Identifier"&&s.value==="await"&&(this.stream.next(),this.stream.skipWhitespace(),t=!0);let r=this.parseCallExpression(),i=this.buildPipeCall(e,r);e=t?new q(i):i}return e}buildPipeCall(e,t){if(t instanceof w)return new w(t.callee,[e,...t.args]);if(t instanceof m||t instanceof S)return new w(t,[e]);throw new Error("Pipe operator requires a function call")}parseTernaryExpression(){let e=this.parseNullishExpression();if(this.stream.skipWhitespace(),this.stream.peek()?.type!=="Question")return e;this.stream.next(),this.stream.skipWhitespace();let t=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let s=this.parseExpression();return new te(e,t,s)}parseNullishExpression(){let e=this.parseLogicalOrExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="NullishCoalesce";){this.stream.next(),this.stream.skipWhitespace();let t=this.parseLogicalOrExpression();e=new v("??",e,t)}return e}parseLogicalOrExpression(){let e=this.parseLogicalAndExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Or")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseLogicalAndExpression();this.stream.skipWhitespace(),e=new v("||",e,s)}return e}parseLogicalAndExpression(){let e=this.parseEqualityExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="And")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseEqualityExpression();this.stream.skipWhitespace(),e=new v("&&",e,s)}return e}parseEqualityExpression(){let e=this.parseComparisonExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="DoubleEquals"&&t.type!=="NotEquals"&&t.type!=="TripleEquals"&&t.type!=="StrictNotEquals")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseComparisonExpression();this.stream.skipWhitespace();let i="==";s.type==="NotEquals"?i="!=":s.type==="TripleEquals"?i="===":s.type==="StrictNotEquals"&&(i="!=="),e=new v(i,e,r)}return e}parseComparisonExpression(){let e=this.parseAdditiveExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Less"&&t.type!=="Greater"&&t.type!=="LessEqual"&&t.type!=="GreaterEqual")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseAdditiveExpression();this.stream.skipWhitespace();let i="<";s.type==="Greater"?i=">":s.type==="LessEqual"?i="<=":s.type==="GreaterEqual"&&(i=">="),e=new v(i,e,r)}return e}parseMultiplicativeExpression(){let e=this.parseUnaryExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Star"&&t.type!=="Slash"&&t.type!=="Percent")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseUnaryExpression();this.stream.skipWhitespace();let i="*";s.type==="Slash"?i="/":s.type==="Percent"&&(i="%"),e=new v(i,e,r)}return e}parseAdditiveExpression(){let e=this.parseMultiplicativeExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Plus"&&t.type!=="Minus")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseMultiplicativeExpression();this.stream.skipWhitespace(),e=new v(s.type==="Plus"?"+":"-",e,r)}return e}parseUnaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="Bang"){this.stream.next();let t=this.parseUnaryExpression();return new O("!",t)}if(e.type==="Minus"){this.stream.next();let t=this.parseUnaryExpression();return new O("-",t)}if(this.isAwaitAllowed()&&e.type==="Identifier"&&e.value==="await"){this.stream.next();let t=this.parseUnaryExpression();return new q(t)}return this.parseCallExpression()}parseCallExpression(){let e=this.parsePrimaryExpression();for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)break;if(t.type==="LParen"){this.stream.next();let s=[];for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated call expression");if(r.type==="RParen"){this.stream.next();break}if(s.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,s);continue}if(t.type==="OptionalChain"){this.stream.next(),this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Expected property or call after ?.");if(s.type==="LParen"){this.stream.next();let r=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated call expression");if(i.type==="RParen"){this.stream.next();break}if(r.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,r);continue}if(s.type==="Identifier"){let r=this.stream.next();e=new S(e,r.value,!0);continue}throw new Error("Expected property or call after ?.")}if(t.type==="Dot"){this.stream.next();let s=this.stream.expect("Identifier");e=new S(e,s.value);continue}if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),e=new ie(e,s);continue}break}return e}parsePrimaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Question")return this.parseQueryExpression();if(e.type==="LBracket")return this.parseArrayExpression();if(e.type==="LBrace")return this.parseObjectExpression();if(e.type==="LParen"){if(this.isArrowFunctionStart())return this.parseArrowFunctionExpression();this.stream.next();let t=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}if(e.type==="Identifier")return this.isAsyncToken(e)&&this.isAsyncArrowFunctionStart()?(this.stream.next(),this.stream.skipWhitespace(),this.parseArrowFunctionExpression(!0)):new m(this.stream.next().value);if(e.type==="Boolean")return new k(this.stream.next().value==="true");if(e.type==="Null")return this.stream.next(),new k(null);if(e.type==="Number")return new k(Number(this.stream.next().value));if(e.type==="String")return new k(this.stream.next().value);if(e.type==="Template")return this.parseTemplateExpression();throw new Error(`Unsupported expression token ${e.type}`)}parseArrayExpression(){this.stream.expect("LBracket");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated array literal");if(t.type==="RBracket"){this.stream.next();break}if(t.type==="Ellipsis"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();e.push(new R(s))}else e.push(this.parseExpression());if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBracket"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array literal")}return new se(e)}parseTemplateExpression(){let e=[];for(;;){let t=this.stream.peek();if(!t)throw new Error("Unterminated template literal");if(t.type!=="Template")throw new Error("Expected template literal");let s=this.stream.next().value;s&&e.push(new k(s));let r=this.stream.peek();if(!r||r.type!=="Dollar")break;this.stream.next(),this.stream.expect("LBrace"),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBrace"),e.push(i)}return new ee(e)}parseObjectExpression(){this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated object literal");if(t.type==="RBrace"){this.stream.next();break}let s,r;if(t.type==="Ellipsis")this.stream.next(),this.stream.skipWhitespace(),r={spread:this.parseExpression()};else if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={keyExpr:i,value:s,computed:!0}}else if(t.type==="Identifier"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.peek()?.type==="Colon"?(this.stream.next(),this.stream.skipWhitespace(),s=this.parseExpression()):s=new m(i),r={key:i,value:s}}else if(t.type==="String"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={key:i,value:s}}else throw new Error(`Unexpected token in object literal: ${t.type}`);if(!r)throw new Error("Invalid object literal entry");if(e.push(r),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object literal")}return new re(e)}consumeStatementTerminator(){this.stream.skipWhitespace();let e=this.stream.peek();if(e?.type==="Semicolon"){this.stream.next();return}this.allowImplicitSemicolon&&e?.type==="RBrace"||this.stream.expect("Semicolon")}parseFunctionBlockWithAwait(e){this.stream.expect("LBrace");let t=[];this.awaitStack.push(e);try{for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function block");if(s.type==="RBrace"){this.stream.next();break}t.push(this.parseStatement({allowBlocks:!1,allowReturn:!0}))}}finally{this.awaitStack.pop()}return new y(t)}isAsyncToken(e){return e?.type==="Identifier"&&e.value==="async"}isAwaitAllowed(){return this.awaitStack.length===0?!1:this.awaitStack[this.awaitStack.length-1]===!0}parseArrowExpressionBody(e){this.awaitStack.push(e);try{let t=this.parseExpression();return new y([new D(t)])}finally{this.awaitStack.pop()}}parseAssignmentTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected assignment target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="LBracket")return this.parseArrayPattern();if(e.type==="LBrace")return this.parseObjectPattern();if(e.type==="Identifier")return new m(this.parseIdentifierPath());throw new Error(`Invalid assignment target ${e.type}`)}parseArrayPattern(){this.stream.expect("LBracket");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated array pattern");if(s.type==="RBracket"){this.stream.next();break}if(s.type==="Comma"){this.stream.next(),e.push(null);continue}if(s.type==="Ellipsis"){if(t)throw new Error("Array patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Identifier");e.push(new I(new m(r.value))),t=!0}else if(s.type==="LBracket")e.push(this.parseArrayPattern());else if(s.type==="LBrace")e.push(this.parseObjectPattern());else if(s.type==="Identifier")e.push(new m(this.parseIdentifierPath()));else throw new Error(`Unexpected token in array pattern: ${s.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array pattern")}if(t&&!(e[e.length-1]instanceof I))throw new Error("Rest element must be last in array pattern");return new H(e)}parseObjectPattern(){this.stream.expect("LBrace");let e=[],t;for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated object pattern");if(r.type==="RBrace"){this.stream.next();break}if(r.type==="Ellipsis"){if(t)throw new Error("Object patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let i=this.stream.expect("Identifier");if(t=new m(i.value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&(this.stream.next(),this.stream.skipWhitespace()),this.stream.peek()?.type!=="RBrace")throw new Error("Rest element must be last in object pattern");this.stream.next();break}else if(r.type==="Identifier"||r.type==="String"){let n=this.stream.next().value;this.stream.skipWhitespace();let a;if(this.stream.peek()?.type==="Colon"){this.stream.next(),this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Expected object pattern target");if(o.type==="LBracket")a=this.parseArrayPattern();else if(o.type==="LBrace")a=this.parseObjectPattern();else if(o.type==="Identifier")a=new m(this.parseIdentifierPath());else throw new Error(`Unexpected token in object pattern: ${o.type}`)}else a=new m(n);e.push({key:n,target:a})}else throw new Error(`Unexpected token in object pattern: ${r.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object pattern")}let s=t?[...e,{rest:t}]:e;return t&&e.length===0?new M([{rest:t}]):new M(s)}parseDeclaration(){let e=this.parseDeclarationTarget();this.stream.skipWhitespace();let t=this.parseDeclarationOperator();this.stream.skipWhitespace();let s=this.parseExpression(),{flags:r,flagArgs:i}=this.parseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new F(e,t,s,r,i)}parseDeclarationTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected declaration target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Identifier")return new m(this.stream.next().value);throw new Error(`Invalid declaration target ${e.type}`)}parseDeclarationOperator(){this.stream.expect("Colon");let e=this.stream.peek();return e?e.type==="Equals"?(this.stream.next(),":="):e.type==="Less"?(this.stream.next(),":<"):e.type==="Greater"?(this.stream.next(),":>"):":":":"}parseFlags(){let e={},t={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let s=this.stream.expect("Identifier").value;if(s==="important")e.important=!0;else if(s==="trusted")e.trusted=!0;else if(s==="debounce")if(e.debounce=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Number");t.debounce=Number(r.value),this.stream.skipWhitespace(),this.stream.expect("RParen")}else t.debounce=200;else if(this.customFlags.has(s)){e[s]=!0;let r=this.parseCustomFlagArg();r!==void 0&&(t[s]=r)}else throw new Error(`Unknown flag ${s}`)}return{flags:e,flagArgs:t}}parseCustomFlagArg(){if(this.stream.peek()?.type!=="LParen")return;this.stream.next(),this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated flag arguments");let t;if(e.type==="Number")t=Number(this.stream.next().value);else if(e.type==="String")t=this.stream.next().value;else if(e.type==="Boolean")t=this.stream.next().value==="true";else if(e.type==="Identifier")t=this.stream.next().value;else throw new Error(`Unsupported flag argument ${e.type}`);return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}isDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier")return this.stream.peekNonWhitespace(1)?.type==="Colon";if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&s?.type==="Colon"}return!1}isAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier"){let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.stream.peekNonWhitespace(t)?.type==="Equals"}if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&s?.type==="Equals"}if(e.type==="LBrace"||e.type==="LBracket"){let t=[],s=0;for(;;){let r=this.stream.peekNonWhitespace(s);if(!r)return!1;if(r.type==="LBrace"||r.type==="LBracket")t.push(r.type);else if((r.type==="RBrace"||r.type==="RBracket")&&(t.pop(),t.length===0))return this.stream.peekNonWhitespace(s+1)?.type==="Equals";s+=1}}return!1}isCallStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier")return!1;let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.stream.peekNonWhitespace(t)?.type==="LParen"}isExpressionStatementStart(){let e=this.stream.peekNonWhitespace(0);return e?e.type==="Identifier"?!0:e.type==="Number"||e.type==="String"||e.type==="Boolean"||e.type==="Null"||e.type==="LParen"||e.type==="LBracket"||e.type==="LBrace"||e.type==="At"||e.type==="Dollar"||e.type==="Question"||e.type==="Bang"||e.type==="Minus":!1}isFunctionDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;let t=0;if(this.isAsyncToken(e)){let r=this.stream.peekNonWhitespace(1);if(!r||r.type!=="Identifier")return!1;t=1}else if(e.type!=="Identifier")return!1;if(t+=1,this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="LBrace"}isArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="LParen")return!1;let t=1,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isAsyncArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!this.isAsyncToken(e)||this.stream.peekNonWhitespace(1)?.type!=="LParen")return!1;let t=2,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isFunctionExpressionAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier"||this.stream.peekNonWhitespace(1)?.type!=="Equals")return!1;let t=2;if(this.isAsyncToken(this.stream.peekNonWhitespace(t))&&(t+=1),this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}parseExpressionStatement(){let e=this.parseExpression();return this.consumeStatementTerminator(),e}parseIfBlock(){this.stream.expect("If"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace();let s;if(this.stream.peek()?.type==="Else")if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="If"){let r=this.parseIfBlock();s=new y([r])}else s=this.parseBlock({allowDeclarations:!1});return new Z(e,t,s)}parseWhileBlock(){this.stream.expect("While"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});return new J(e,t)}parseForBlock(){this.stream.expect("For"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e;this.stream.peek()?.type!=="Semicolon"&&(e=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let t;this.stream.peek()?.type!=="Semicolon"&&(t=this.parseExpression()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let s;this.stream.peek()?.type!=="RParen"&&(s=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("RParen");let r=this.parseBlock({allowDeclarations:!1});return new Y(e,t,s,r)}parseForClause(){return this.isAssignmentStart()?this.parseAssignmentExpression():this.parseExpression()}parseAssignmentExpression(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace(),this.stream.expect("Equals"),this.stream.skipWhitespace();let t=this.parseExpression();return new B(e,t)}parseTryBlock(){this.stream.expect("Try");let e=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace(),this.stream.expect("Catch"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.stream.expect("Identifier").value;this.stream.skipWhitespace(),this.stream.expect("RParen");let s=this.parseBlock({allowDeclarations:!1});return new X(e,t,s)}parseConstructBlock(){this.stream.expect("Construct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Construct",e}parseDestructBlock(){this.stream.expect("Destruct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Destruct",e}parseQueryExpression(){this.stream.expect("Question");let e="self";this.stream.peek()?.type==="Greater"?(this.stream.next(),e="descendant"):this.stream.peek()?.type==="Less"&&(this.stream.next(),e="ancestor"),this.stream.skipWhitespace(),this.stream.expect("LParen");let t=this.readSelectorUntil("RParen");return new ne(e,t)}parseFunctionDeclaration(){let e=!1,t=this.stream.peekNonWhitespace(0);this.isAsyncToken(t)&&(this.stream.next(),this.stream.skipWhitespace(),e=!0);let s=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let r=this.parseFunctionParams();this.stream.skipWhitespace();let i=this.parseFunctionBlockWithAwait(e);return new L(s,r,i,e)}parseFunctionBlock(){return this.parseFunctionBlockWithAwait(!1)}parseReturnStatement(){if(this.stream.expect("Return"),this.stream.skipWhitespace(),this.stream.peek()?.type==="Semicolon")return this.stream.next(),new D;let e=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new D(e)}parseArrowFunctionExpression(e=!1){let t=this.parseFunctionParams();if(this.stream.skipWhitespace(),this.stream.expect("Arrow"),this.stream.skipWhitespace(),this.stream.peek()?.type==="LBrace"){let r=this.parseFunctionBlockWithAwait(e);return new N(t,r,e)}let s=this.parseArrowExpressionBody(e);return new N(t,s,e)}parseFunctionParams(){this.stream.expect("LParen");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function parameters");if(s.type==="RParen"){this.stream.next();break}if(s.type==="Ellipsis"){if(t)throw new Error("Function parameters can only include one rest parameter");this.stream.next(),this.stream.skipWhitespace();let n=this.stream.expect("Identifier").value;if(e.push({name:n,rest:!0}),t=!0,this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma")throw new Error("Rest parameter must be last in function parameters");this.stream.expect("RParen");break}let r=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let i;if(this.stream.peek()?.type==="Equals"&&(this.stream.next(),this.stream.skipWhitespace(),i=this.parseExpression()),e.push(i?{name:r,defaultValue:i}:{name:r}),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in function parameters")}return e}readSelectorUntil(e){let t="",s=!1;for(;;){let r=this.stream.peek();if(!r)throw new Error("Unterminated selector");if(r.type===e){this.stream.next();break}if(r.type==="Whitespace"){this.stream.next(),s&&t[t.length-1]!==" "&&(t+=" ");continue}s=!0,t+=this.stream.next().value}return t.trim()}parseIdentifierPath(){let e=this.stream.expect("Identifier").value;for(;this.stream.peek()?.type==="Dot";){this.stream.next();let t=this.stream.expect("Identifier").value;e=`${e}.${t}`}return e}};var $=class c{constructor(e){this.parent=e;this.root=e?e.root:this}data=new Map;root;listeners=new Map;anyListeners=new Set;createChild(){return new c(this)}get(e){return this.getPath(e)}set(e,t){this.setPath(e,t)}hasKey(e){let s=e.split(".")[0];return s?this.data.has(s):!1}getPath(e){let t=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:s,targetPath:r}=this.resolveScope(e);if(!s||!r)return;let i=this.getLocalPathValue(s,r);if(t||i!==void 0)return i;let n=s.parent;for(;n;){let a=this.getLocalPathValue(n,r);if(a!==void 0)return a;n=n.parent}}setPath(e,t){let s=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:r,targetPath:i}=this.resolveScope(e);if(!r||!i)return;let n=s?r:this.findNearestScopeWithKey(r,i)??r,a=i.split("."),o=a[0];if(!o)return;if(a.length===1){n.data.set(o,t),n.emitChange(i);return}let p=n.data.get(o);(p==null||typeof p!="object")&&(p={},n.data.set(o,p));let h=p;for(let f=1;f<a.length-1;f+=1){let g=a[f];if(!g)return;(h[g]==null||typeof h[g]!="object")&&(h[g]={}),h=h[g]}let d=a[a.length-1];d&&(h[d]=t,n.emitChange(i))}on(e,t){let s=e.trim();if(!s)return;let r=this.listeners.get(s)??new Set;r.add(t),this.listeners.set(s,r)}off(e,t){let s=e.trim(),r=this.listeners.get(s);r&&(r.delete(t),r.size===0&&this.listeners.delete(s))}onAny(e){this.anyListeners.add(e)}offAny(e){this.anyListeners.delete(e)}emitChange(e){let t=e.trim();if(!t)return;this.listeners.get(t)?.forEach(r=>r());let s=t.split(".")[0];s&&s!==t&&this.listeners.get(s)?.forEach(r=>r()),this.anyListeners.forEach(r=>r())}resolveScope(e){let t=this,s=e;for(;s.startsWith("parent.");)t=t?.parent,s=s.slice(7);for(s.startsWith("root.")&&(t=t?.root,s=s.slice(5));s.startsWith("self.");)t=t??this,s=s.slice(5);return{targetScope:t,targetPath:s}}getLocalPathValue(e,t){let s=t.split("."),r=s[0];if(!r)return;let i=e.data.get(r);for(let n=1;n<s.length;n+=1){if(i==null)return;let a=s[n];if(!a)return;i=i[a]}return i}findNearestScopeWithKey(e,t){let s=t.split(".")[0];if(!s)return;let r=e;for(;r;){if(r.data.has(s))return r;r=r.parent}}};function Ee(c){return c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement?c.value:c.textContent??""}function ke(c,e){if(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement){c.value=e,c.setAttribute("value",e);return}if(c instanceof HTMLSelectElement){c.value=e;return}c instanceof HTMLElement&&c.querySelector("*")||(c.textContent=e)}function oe(c,e,t){let s=e.trim();if(!s)return;let r=Ee(c);t.set(s,r)}function pe(c,e,t){let s=e.trim();if(!s)return;let r=t.get(s);r!=null&&ke(c,String(r))}function ge(c,e){let t=c.trim();return t?!!e.get(t):!1}function le(c,e,t){c.style.display=ge(e,t)?"":"none"}function he(c,e,t){c.style.display=ge(e,t)?"":"none"}function we(c){return c.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"")}function A(c,e,t,s){let r=e.trim();if(!r)return;let i=t.get(r),n=i==null?"":String(i);c.innerHTML=s?n:we(n)}async function ye(c,e,t,s){if(!globalThis.fetch)throw new Error("fetch is not available");let r=await globalThis.fetch(e.url);if(!r||!r.ok)return;let i=await r.text(),n=be(c,e.targetSelector);if(!n){c.dispatchEvent(new CustomEvent("vsn:targetError",{detail:{selector:e.targetSelector}}));return}if(e.swap==="outer"){let a=document.createElement("div");A(a,"__html",{get:()=>i},e.trusted);let o=a.firstElementChild;o&&n.parentNode&&(n.parentNode.replaceChild(o,n),s?.(o));return}A(n,"__html",{get:()=>i},e.trusted),s?.(n)}function be(c,e){return e?c.ownerDocument.querySelector(e):c}function P(c,e){let t;return(...s)=>{t&&clearTimeout(t),t=setTimeout(()=>{t=void 0,c(...s)},e)}}var U=class c{static activeEngines=new WeakMap;scopes=new WeakMap;bindBindings=new WeakMap;ifBindings=new WeakMap;showBindings=new WeakMap;htmlBindings=new WeakMap;getBindings=new WeakMap;eachBindings=new WeakMap;lifecycleBindings=new WeakMap;behaviorRegistry=[];behaviorBindings=new WeakMap;behaviorListeners=new WeakMap;behaviorId=0;codeCache=new Map;behaviorCache=new Map;observer;observerRoot;attributeHandlers=[];globals={};importantFlags=new WeakMap;inlineDeclarations=new WeakMap;flagHandlers=new Map;pendingAdded=new Set;pendingRemoved=new Set;pendingUpdated=new Set;observerFlush;ignoredAdded=new WeakMap;diagnostics;logger;constructor(e={}){this.diagnostics=e.diagnostics??!1,this.logger=e.logger??console,this.registerGlobal("console",console),this.registerGlobal("list",{async map(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)r.push(await s(t[i],i));return r},async filter(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)await s(t[i],i)&&r.push(t[i]);return r},async reduce(t,s,r){if(!Array.isArray(t)||typeof s!="function")return r;let i=arguments.length>2,n=i?r:t[0],a=i?0:1;for(let o=a;o<t.length;o+=1)n=await s(n,t[o],o);return n}}),this.registerDefaultAttributeHandlers()}async mount(e){let t=e.ownerDocument,s=c.activeEngines.get(t);s&&s!==this&&s.disconnectObserver(),c.activeEngines.set(t,this);let r=[e,...Array.from(e.querySelectorAll("*"))];for(let i of r){if(!this.hasVsnAttributes(i))continue;let n=this.findParentScope(i);this.getScope(i,n),this.attachAttributes(i),this.runConstruct(i)}await this.applyBehaviors(e),this.attachObserver(e)}unmount(e){this.runDestruct(e),this.disconnectObserver()}registerBehaviors(e){let t=new W(e,{customFlags:new Set(this.flagHandlers.keys())}).parseProgram();for(let s of t.uses){let r=this.resolveGlobalPath(s.name);if(r===void 0){console.warn(`vsn: global '${s.name}' not found`);continue}this.registerGlobal(s.alias,r)}for(let s of t.behaviors)this.collectBehavior(s)}registerGlobal(e,t){this.globals[e]=t}registerGlobals(e){Object.assign(this.globals,e)}registerFlag(e,t={}){if(new Set(["important","trusted","debounce"]).has(e))throw new Error(`Flag '${e}' is reserved`);this.flagHandlers.set(e,t)}getRegistryStats(){return{behaviorCount:this.behaviorRegistry.length,behaviorCacheSize:this.behaviorCache.size}}registerAttributeHandler(e){this.attributeHandlers.push(e)}resolveGlobalPath(e){let t=e.split("."),s=t[0];if(!s)return;let r=globalThis[s];for(let i=1;i<t.length;i+=1){let n=t[i];if(!n)return;r=r?.[n]}return r}getScope(e,t){let s=this.scopes.get(e);if(s)return s;let r=new $(t??this.findParentScope(e));return this.scopes.set(e,r),r}evaluate(e){let t=this.getScope(e),s=this.bindBindings.get(e);s&&(s.direction==="from"||s.direction==="both")&&pe(e,s.expr,t);let r=this.ifBindings.get(e);r&&e instanceof HTMLElement&&le(e,r,t);let i=this.showBindings.get(e);i&&e instanceof HTMLElement&&he(e,i,t);let n=this.htmlBindings.get(e);n&&e instanceof HTMLElement&&(A(e,n.expr,t,n.trusted),n.trusted&&this.handleTrustedHtml(e))}attachObserver(e){this.observer||(this.observerRoot=e,this.observerFlush=P(()=>this.flushObserverQueue(),10),this.observer=new MutationObserver(t=>{for(let s of t){s.type==="attributes"&&s.target instanceof Element&&this.pendingUpdated.add(s.target);for(let r of Array.from(s.addedNodes))if(r&&r.nodeType===1){let i=r;if(this.ignoredAdded.has(i)){this.ignoredAdded.delete(i);continue}this.pendingAdded.add(i)}for(let r of Array.from(s.removedNodes))r&&r.nodeType===1&&this.pendingRemoved.add(r)}this.observerFlush?.()}),this.observer.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}))}disconnectObserver(){this.observer?.disconnect(),this.observer=void 0,this.observerRoot=void 0,this.pendingAdded.clear(),this.pendingRemoved.clear(),this.pendingUpdated.clear()}flushObserverQueue(){let e=Array.from(this.pendingRemoved);this.pendingRemoved.clear();for(let r of e)this.handleRemovedNode(r);let t=Array.from(this.pendingUpdated);this.pendingUpdated.clear();for(let r of t)this.handleUpdatedNode(r);let s=Array.from(this.pendingAdded);this.pendingAdded.clear();for(let r of s)this.handleAddedNode(r)}handleRemovedNode(e){this.lifecycleBindings.has(e)&&this.runDestruct(e),this.behaviorBindings.has(e)&&this.runBehaviorDestruct(e);for(let t of Array.from(e.querySelectorAll("*")))this.lifecycleBindings.has(t)&&this.runDestruct(t),this.behaviorBindings.has(t)&&this.runBehaviorDestruct(t)}handleAddedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t){if(!this.hasVsnAttributes(s))continue;let r=this.findParentScope(s);this.getScope(s,r),this.attachAttributes(s),this.runConstruct(s)}this.applyBehaviors(e)}handleUpdatedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)this.reapplyBehaviorsForElement(s)}async applyBehaviors(e){if(this.behaviorRegistry.length===0)return;let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)await this.reapplyBehaviorsForElement(s)}async reapplyBehaviorsForElement(e){if(this.behaviorRegistry.length===0)return;let t=this.behaviorBindings.get(e)??new Set,s=this.getScope(e),r=this.behaviorRegistry.filter(n=>e.matches(n.selector)).sort((n,a)=>n.specificity!==a.specificity?n.specificity-a.specificity:n.order-a.order);for(let n of r)t.has(n.id)||await this.applyBehaviorForElement(n,e,s,t);let i=new Set(r.map(n=>n.id));for(let n of this.behaviorRegistry)t.has(n.id)&&!i.has(n.id)&&this.unbindBehaviorForElement(n,e,s,t);this.behaviorBindings.set(e,t)}async applyBehaviorForElement(e,t,s,r){r.add(e.id);let i=this.getBehaviorRootScope(t,e);this.applyBehaviorFunctions(t,s,e.functions,i),await this.applyBehaviorDeclarations(t,s,e.declarations,i),e.construct&&await this.safeExecuteBlock(e.construct,s,t,i);for(let n of e.onBlocks)this.attachBehaviorOnHandler(t,n.event,n.body,n.modifiers,n.args,e.id,i);this.logDiagnostic("bind",t,e)}unbindBehaviorForElement(e,t,s,r){if(r.delete(e.id),e.destruct){let a=this.getBehaviorRootScope(t,e);this.safeExecuteBlock(e.destruct,s,t,a)}let i=this.behaviorListeners.get(t),n=i?.get(e.id);if(n){for(let a of n)a.target.removeEventListener(a.event,a.handler,a.options);i?.delete(e.id)}this.logDiagnostic("unbind",t,e)}runBehaviorDestruct(e){let t=this.behaviorBindings.get(e);if(!t)return;let s=this.getScope(e);for(let r of this.behaviorRegistry){if(!t.has(r.id)||!r.destruct)continue;let i=this.getBehaviorRootScope(e,r);this.safeExecuteBlock(r.destruct,s,e,i)}}attachAttributes(e){let t=this.getScope(e);for(let s of e.getAttributeNames()){if(!s.startsWith("vsn-"))continue;let r=e.getAttribute(s)??"";for(let i of this.attributeHandlers){if(!i.match(s))continue;if(i.handle(e,s,r,t)!==!1)break}}}setLifecycle(e,t){let s=this.lifecycleBindings.get(e)??{};this.lifecycleBindings.set(e,{...s,...t})}runConstruct(e){let t=this.lifecycleBindings.get(e);if(!t?.construct)return;let s=this.getScope(e);this.safeExecute(t.construct,s,e)}runDestruct(e){let t=this.lifecycleBindings.get(e);if(!t?.destruct)return;let s=this.getScope(e);this.safeExecute(t.destruct,s,e)}parseEachExpression(e){let[t,s]=e.split(/\s+as\s+/);if(!t||!s)return null;let r=t.trim(),i=s.split(",").map(o=>o.trim()).filter(Boolean);if(!r||i.length===0)return null;let n=i[0]??"",a=i[1];return{listExpr:r,itemName:n,...a?{indexName:a}:{}}}renderEach(e){let t=this.eachBindings.get(e);if(!t||!(e instanceof HTMLTemplateElement))return;let s=e.parentElement;if(!s)return;for(let a of t.rendered)this.handleRemovedNode(a),a.parentNode&&a.parentNode.removeChild(a);t.rendered=[];let r=this.getScope(e),i=r.get(t.listExpr);if(!Array.isArray(i))return;let n=[];i.forEach((a,o)=>{let p=e.content.cloneNode(!0),h=Array.from(p.children),d=new $(r);d.setPath(`self.${t.itemName}`,a),t.indexName&&d.setPath(`self.${t.indexName}`,o);for(let f of h)this.getScope(f,d);s.insertBefore(p,e);for(let f of h){this.ignoredAdded.set(f,!0),n.push(f),this.handleAddedNode(f),this.evaluate(f);for(let g of Array.from(f.querySelectorAll("*")))this.evaluate(g)}}),t.rendered=n}attachBindInputHandler(e,t){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let s=()=>{let r=this.getScope(e);oe(e,t,r)};e.addEventListener("input",s),e.addEventListener("change",s)}parseBindDirection(e){return e.includes(":from")?"from":e.includes(":to")?"to":"both"}hasVsnAttributes(e){return e.getAttributeNames().some(t=>t.startsWith("vsn-"))}markInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e)??new Set;s.add(t),this.inlineDeclarations.set(e,s)}isInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e);return s?s.has(t):!1}findParentScope(e){let t=e.parentElement;for(;t;){let s=this.scopes.get(t);if(s)return s;t=t.parentElement}}watch(e,t,s){let r=t.trim();if(!r)return;let i=r.split(".")[0];if(!i)return;let n=e;for(;n&&!n.hasKey(i);)n=n.parent;if(n){n.on(r,s);return}let a=e;for(;a;)a.on(r,s),a=a.parent}watchWithDebounce(e,t,s,r){r?this.watch(e,t,P(s,r)):this.watch(e,t,s)}watchAllScopes(e,t,s){let r=s?P(t,s):t,i=e;for(;i;)i.onAny(r),i=i.parent}parseOnAttribute(e,t){if(!e.startsWith("vsn-on:"))return null;let s=e.slice(7),[r,...i]=s.split("!");if(!r)return null;let n=this.parseEventDescriptor(r);if(!n.event)return null;let a,o=[];for(let d of i){if(d.startsWith("debounce")){let f=d.match(/debounce\((\d+)\)/);a=f?Number(f[1]):200;continue}o.push(d)}let p=[...o,...n.modifiers];return{event:n.event,code:t,...a!==void 0?{debounceMs:a}:{},...p.length>0?{modifiers:p}:{},...n.keyModifiers.length>0?{keyModifiers:n.keyModifiers}:{}}}parseEventDescriptor(e){let t=e.split(".").map(a=>a.trim()).filter(Boolean),s=t.shift()??"",r=[],i=[],n=new Set(["outside","self"]);for(let a of t)n.has(a)?r.push(a):i.push(a);return{event:s,keyModifiers:i,modifiers:r}}matchesKeyModifiers(e,t){if(!t||t.length===0)return!0;if(!(e instanceof KeyboardEvent))return!1;let s={shift:e.shiftKey,ctrl:e.ctrlKey,control:e.ctrlKey,alt:e.altKey,meta:e.metaKey},r={esc:"escape",escape:"escape",enter:"enter",tab:"tab",space:"space",spacebar:"space",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",arrowup:"arrowup",arrowdown:"arrowdown",arrowleft:"arrowleft",arrowright:"arrowright",delete:"delete",backspace:"backspace"},i=e.key?.toLowerCase()??"";i===" "&&(i="space");for(let n of t){let a=n.toLowerCase();if(a in s){if(!s[a])return!1;continue}let o=r[a]??a;if(i!==o)return!1}return!0}matchesTargetModifiers(e,t,s){if(!s||s.length===0)return!0;let r=t?.target;return!r||!(r instanceof Node)?!s.includes("self")&&!s.includes("outside"):!(s.includes("self")&&r!==e||s.includes("outside")&&e.contains(r))}describeElement(e){let t=e.tagName.toLowerCase(),s=e.id?`#${e.id}`:"",r=e.classList.length>0?`.${Array.from(e.classList).join(".")}`:"";return`${t}${s}${r}`}logDiagnostic(e,t,s){!this.diagnostics||!this.logger.info||this.logger.info(`vsn:${e}`,{element:this.describeElement(t),selector:s.selector,behaviorId:s.id})}emitError(e,t){let s=this.describeElement(e);this.logger.warn?.("vsn:error",{error:t,selector:s}),e.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:t,selector:s},bubbles:!0}))}attachOnHandler(e,t){let s=this.getListenerOptions(t.modifiers),r=t.modifiers?.includes("outside")?e.ownerDocument:e,i,n=async a=>{if(!e.isConnected){r.removeEventListener(t.event,i,s);return}if(!this.matchesKeyModifiers(a,t.keyModifiers)||!this.matchesTargetModifiers(e,a,t.modifiers))return;this.applyEventModifiers(a,t.modifiers);let o=this.getScope(e);try{await this.execute(t.code,o,e),this.evaluate(e)}catch(p){this.emitError(e,p)}};i=t.debounceMs?P(n,t.debounceMs):n,r.addEventListener(t.event,i,s)}attachBehaviorOnHandler(e,t,s,r,i,n,a){let o=this.parseEventDescriptor(t),p=r?[...r,...o.modifiers]:o.modifiers.length>0?[...o.modifiers]:void 0,h=p?.includes("outside")?e.ownerDocument:e,d=async z=>{if(!this.matchesKeyModifiers(z,o.keyModifiers)||!this.matchesTargetModifiers(e,z,p))return;this.applyEventModifiers(z,p);let V=this.getScope(e),de=new Map;if(i&&i.length>0){let E=i[0];E&&(de.set(E,V.getPath(E)),V.setPath(E,z))}let fe=!1;try{await this.executeBlock(s,V,e,a)}catch(E){fe=!0,this.emitError(e,E)}finally{for(let[E,ve]of de.entries())V.setPath(E,ve)}fe||this.evaluate(e)},f=this.getListenerOptions(p);h.addEventListener(o.event,d,f);let g=this.behaviorListeners.get(e)??new Map,ue=g.get(n)??[];ue.push({target:h,event:o.event,handler:d,options:f}),g.set(n,ue),this.behaviorListeners.set(e,g)}attachGetHandler(e,t=!1){let s=async()=>{let r=this.getBindings.get(e);if(r)try{await ye(e,r,this.getScope(e),i=>{r.trusted&&this.handleTrustedHtml(i)})}catch(i){console.warn("vsn:getError",i),e.dispatchEvent(new CustomEvent("vsn:getError",{detail:{error:i},bubbles:!0}))}};e.addEventListener("click",r=>{r.target===e&&s()}),t&&Promise.resolve().then(s)}applyEventModifiers(e,t){if(!(!e||!t||t.length===0))for(let s of t)s==="prevent"?e.preventDefault():s==="stop"&&e.stopPropagation()}getListenerOptions(e){if(!e||e.length===0)return;let t={};return e.includes("once")&&(t.once=!0),e.includes("passive")&&(t.passive=!0),e.includes("capture")&&(t.capture=!0),Object.keys(t).length>0?t:void 0}async execute(e,t,s,r){let i=this.codeCache.get(e);i||(i=W.parseInline(e),this.codeCache.set(e,i));let n={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await i.evaluate(n)}async executeBlock(e,t,s,r){let i={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await e.evaluate(i)}async safeExecute(e,t,s,r){try{await this.execute(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}async safeExecuteBlock(e,t,s,r){try{await this.executeBlock(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}collectBehavior(e,t,s){let r=t?`${t} ${e.selector.selectorText}`:e.selector.selectorText,i=s??t??e.selector.selectorText,n=this.getCachedBehavior(e);this.behaviorRegistry.push({id:this.behaviorId+=1,selector:r,rootSelector:i,specificity:this.computeSpecificity(r),order:this.behaviorRegistry.length,...n}),this.collectNestedBehaviors(e.body,r,i)}collectNestedBehaviors(e,t,s){for(let r of e.statements){if(r instanceof C){this.collectBehavior(r,t,s);continue}if(r instanceof b){this.collectNestedBehaviors(r.body,t,s);continue}r instanceof y&&this.collectNestedBehaviors(r,t,s)}}computeSpecificity(e){let t=e.match(/#[\w-]+/g)?.length??0,s=e.match(/\.[\w-]+/g)?.length??0,r=e.match(/\[[^\]]+\]/g)?.length??0,i=e.match(/:[\w-]+/g)?.length??0,n=e.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/g)?.length??0;return t*100+(s+r+i)*10+n}getBehaviorRootScope(e,t){let s=e.closest(t.rootSelector)??e;return this.getScope(s)}getImportantKey(e){if(e.target instanceof m)return`state:${e.target.name}`;if(e.target instanceof x)return`${e.target.kind}:${e.target.name}`}isImportant(e,t){let s=this.importantFlags.get(e);return s?s.has(t):!1}markImportant(e,t){let s=this.importantFlags.get(e)??new Set;s.add(t),this.importantFlags.set(e,s)}extractLifecycle(e){let t,s;for(let r of e.statements)r instanceof y&&(r.type==="Construct"?t=r:r.type==="Destruct"&&(s=r));return{...t?{construct:t}:{},...s?{destruct:s}:{}}}extractOnBlocks(e){let t=[];for(let s of e.statements)s instanceof b&&t.push({event:s.eventName,body:s.body,modifiers:s.modifiers,args:s.args});return t}extractDeclarations(e){let t=[];for(let s of e.statements)s instanceof F&&t.push(s);return t}extractFunctionDeclarations(e){let t=[];for(let s of e.statements){if(s instanceof L){t.push({name:s.name,params:s.params,body:s.body});continue}s instanceof B&&s.target instanceof m&&s.value instanceof N&&t.push({name:s.target.name,params:s.value.params,body:s.value.body})}return t}getCachedBehavior(e){let t=this.hashBehavior(e),s=this.behaviorCache.get(t);if(s)return s;let r=this.extractLifecycle(e.body),i={onBlocks:this.extractOnBlocks(e.body),declarations:this.extractDeclarations(e.body),functions:this.extractFunctionDeclarations(e.body),...r};return this.behaviorCache.set(t,i),i}hashBehavior(e){let t=this.normalizeNode(e),s=JSON.stringify(t);return this.hashString(s)}normalizeNode(e){if(!e||typeof e!="object")return e;let t=e.type??"Unknown";return t==="Behavior"?{type:t,selector:e.selector?.selectorText??"",body:this.normalizeNode(e.body)}:t==="Selector"?{type:t,selectorText:e.selectorText??""}:t==="Block"||t==="Construct"||t==="Destruct"?{type:t,statements:Array.isArray(e.statements)?e.statements.map(s=>this.normalizeNode(s)):[]}:t==="OnBlock"?{type:t,eventName:e.eventName??"",args:Array.isArray(e.args)?e.args:[],body:this.normalizeNode(e.body)}:t==="Declaration"?{type:t,target:this.normalizeNode(e.target),operator:e.operator??"",value:this.normalizeNode(e.value),flags:e.flags??{},flagArgs:e.flagArgs??{}}:t==="Assignment"?{type:t,target:this.normalizeNode(e.target),value:this.normalizeNode(e.value)}:t==="StateBlock"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>this.normalizeNode(s)):[]}:t==="StateEntry"?{type:t,name:e.name??"",value:this.normalizeNode(e.value),important:!!e.important}:t==="FunctionDeclaration"?{type:t,name:e.name??"",params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="FunctionExpression"?{type:t,params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="Return"?{type:t,value:this.normalizeNode(e.value??null)}:t==="If"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate??null)}:t==="While"?{type:t,test:this.normalizeNode(e.test),body:this.normalizeNode(e.body)}:t==="For"?{type:t,init:this.normalizeNode(e.init??null),test:this.normalizeNode(e.test??null),update:this.normalizeNode(e.update??null),body:this.normalizeNode(e.body)}:t==="Try"?{type:t,errorName:e.errorName??"",body:this.normalizeNode(e.body),handler:this.normalizeNode(e.handler)}:t==="Identifier"?{type:t,name:e.name??""}:t==="Literal"?{type:t,value:e.value}:t==="TemplateExpression"?{type:t,parts:Array.isArray(e.parts)?e.parts.map(s=>this.normalizeNode(s)):[]}:t==="UnaryExpression"?{type:t,operator:e.operator??"",argument:this.normalizeNode(e.argument)}:t==="BinaryExpression"?{type:t,operator:e.operator??"",left:this.normalizeNode(e.left),right:this.normalizeNode(e.right)}:t==="TernaryExpression"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate)}:t==="MemberExpression"?{type:t,target:this.normalizeNode(e.target),property:e.property??"",optional:!!e.optional}:t==="CallExpression"?{type:t,callee:this.normalizeNode(e.callee),args:Array.isArray(e.args)?e.args.map(s=>this.normalizeNode(s)):[]}:t==="AwaitExpression"?{type:t,argument:this.normalizeNode(e.argument)}:t==="Directive"?{type:t,kind:e.kind??"",name:e.name??""}:t==="Query"?{type:t,direction:e.direction??"",selector:e.selector??""}:t==="ArrayExpression"?{type:t,elements:Array.isArray(e.elements)?e.elements.map(s=>this.normalizeNode(s)):[]}:t==="ObjectExpression"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>({key:s?.key??"",computed:!!s?.computed,keyExpr:s?.keyExpr?this.normalizeNode(s.keyExpr):null,value:this.normalizeNode(s?.value)})):[]}:t==="IndexExpression"?{type:t,target:this.normalizeNode(e.target),index:this.normalizeNode(e.index)}:{type:t}}hashString(e){let t=5381;for(let s=0;s<e.length;s+=1)t=(t<<5)+t+e.charCodeAt(s),t|=0;return(t>>>0).toString(16)}applyBehaviorFunctions(e,t,s,r){for(let i of s)this.applyBehaviorFunction(e,t,i,r)}applyBehaviorFunction(e,t,s,r){let i=t.getPath(s.name);if(i!==void 0&&typeof i!="function")throw new Error(`Cannot override non-function '${s.name}' with a function`);let n=async(...a)=>{let o=t.createChild?t.createChild():t,p={scope:o,rootScope:r??o,globals:this.globals,element:e,returnValue:void 0,returning:!1},h=new Map;return await this.applyFunctionParams(o,s.params,h,p,a),await s.body.evaluate(p),o===t&&this.restoreFunctionParams(o,s.params,h),p.returnValue};t.setPath(s.name,n)}async applyFunctionParams(e,t,s,r,i){let n=0;for(let a of t){let o=a.name;if(!o)continue;if(s.set(o,e.getPath(o)),a.rest){e.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let p=i[n];p===void 0&&a.defaultValue&&(p=await a.defaultValue.evaluate(r)),e.setPath(`self.${o}`,p),n+=1}}restoreFunctionParams(e,t,s){for(let r of t){let i=r.name;i&&e.setPath(i,s.get(i))}}async applyBehaviorDeclarations(e,t,s,r){for(let i of s)await this.applyBehaviorDeclaration(e,t,i,r)}async applyBehaviorDeclaration(e,t,s,r){let i={scope:t,rootScope:r,element:e},n=s.operator,a=s.flags.debounce?s.flagArgs.debounce??200:void 0,o=this.getImportantKey(s);if(!s.flags.important&&o&&this.isImportant(e,o)||o&&this.isInlineDeclaration(e,o))return;if(this.applyCustomFlags(e,t,s),s.target instanceof m){let f=await s.value.evaluate(i);t.setPath(s.target.name,f),s.flags.important&&o&&this.markImportant(e,o);return}if(!(s.target instanceof x))return;let p=s.target,h=s.value instanceof m?s.value.name:void 0;if(n===":>"){h&&this.applyDirectiveToScope(e,p,h,t,a,r),s.flags.important&&o&&this.markImportant(e,o);return}if(n===":="&&h&&this.applyDirectiveToScope(e,p,h,t,a,r),!h){let f=await s.value.evaluate(i);this.setDirectiveValue(e,p,f,s.flags.trusted),(n===":<"||n===":=")&&this.applyDirectiveFromExpression(e,p,s.value,t,s.flags.trusted,a,r),s.flags.important&&o&&this.markImportant(e,o);return}let d=n===":<"||n===":=";this.applyDirectiveFromScope(e,p,h,t,s.flags.trusted,a,d,r),s.flags.important&&o&&this.markImportant(e,o)}applyCustomFlags(e,t,s){if(this.flagHandlers.size!==0)for(let[r,i]of this.flagHandlers)s.flags[r]&&i.onApply?.({name:r,args:s.flagArgs[r],element:e,scope:t,declaration:s})}applyDirectiveFromScope(e,t,s,r,i,n,a=!0,o){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let h=()=>{let d=s.startsWith("root.")&&o,f=d?o:r,g=d?`self.${s.slice(5)}`:s;A(e,g,f,!!i)};if(h(),i&&this.handleTrustedHtml(e),a){let d=s.startsWith("root.")&&o,f=d?o:r,g=d?s.slice(5):s;this.watchWithDebounce(f,g,h,n)}return}let p=()=>{let h=s.startsWith("root.")&&o,d=h?o:r,f=h?`self.${s.slice(5)}`:s,g=d.get(f);g!=null&&this.setDirectiveValue(e,t,g,i)};if(p(),a){let h=s.startsWith("root.")&&o,d=h?o:r,f=h?s.slice(5):s;this.watchWithDebounce(d,f,p,n)}}applyDirectiveFromExpression(e,t,s,r,i,n,a){let o=async()=>{let p={scope:r,rootScope:a,element:e},h=await s.evaluate(p);this.setDirectiveValue(e,t,h,i)};o(),this.watchAllScopes(r,()=>{o()},n)}applyDirectiveToScope(e,t,s,r,i,n){let a=s.startsWith("root.")&&n,o=a?n:r,p=a?`self.${s.slice(5)}`:s;if(t.kind==="attr"&&t.name==="value"){this.applyValueBindingToScope(e,p,i,o);return}if(t.kind==="attr"&&t.name==="checked"){this.applyCheckedBindingToScope(e,p,i,o);return}let h=this.getDirectiveValue(e,t);h!=null&&o.set(p,h)}applyCheckedBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement))return;let i=()=>{(r??this.getScope(e)).set(t,e.checked)},n=s?P(i,s):i;n(),e.addEventListener("change",n),e.addEventListener("input",n)}applyValueBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let i=()=>{let a=r??this.getScope(e);oe(e,t,a)},n=s?P(i,s):i;n(),e.addEventListener("input",n),e.addEventListener("change",n)}setDirectiveValue(e,t,s,r){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let i=s==null?"":String(s);e.innerHTML=r?i:i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),r&&this.handleTrustedHtml(e);return}if(t.kind==="attr"){if(t.name==="value"){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){e.value=s==null?"":String(s),e.setAttribute("value",e.value);return}if(e instanceof HTMLSelectElement){e.value=s==null?"":String(s);return}}if(t.name==="checked"&&e instanceof HTMLInputElement){let i=s===!0||s==="true"||s===1||s==="1";e.checked=i,i?e.setAttribute("checked",""):e.removeAttribute("checked");return}e.setAttribute(t.name,s==null?"":String(s));return}t.kind==="style"&&e instanceof HTMLElement&&e.style.setProperty(t.name,s==null?"":String(s))}getDirectiveValue(e,t){if(t.kind==="attr")return t.name==="value"&&(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)?e.value:t.name==="checked"&&e instanceof HTMLInputElement?e.checked:e.getAttribute(t.name)??void 0;if(t.kind==="style"&&e instanceof HTMLElement)return e.style.getPropertyValue(t.name)??void 0}handleTrustedHtml(e){let t=Array.from(e.querySelectorAll('script[type="text/vsn"]'));if(t.length===0)return;let s=t.map(r=>r.textContent??"").join(`
7
- `);s.trim()&&(this.registerBehaviors(s),this.applyBehaviors(e))}registerDefaultAttributeHandlers(){this.registerAttributeHandler({id:"vsn-bind",match:e=>e.startsWith("vsn-bind"),handle:(e,t,s,r)=>{let i=this.parseBindDirection(t);this.bindBindings.set(e,{expr:s,direction:i}),(i==="to"||i==="both")&&this.markInlineDeclaration(e,`state:${s}`),(i==="to"||i==="both")&&(oe(e,s,r),this.attachBindInputHandler(e,s)),(i==="from"||i==="both")&&this.watch(r,s,()=>pe(e,s,r))}}),this.registerAttributeHandler({id:"vsn-if",match:e=>e==="vsn-if",handle:(e,t,s,r)=>{this.ifBindings.set(e,s),e instanceof HTMLElement&&le(e,s,r),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-show",match:e=>e==="vsn-show",handle:(e,t,s,r)=>{this.showBindings.set(e,s),e instanceof HTMLElement&&he(e,s,r),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-html",match:e=>e.startsWith("vsn-html"),handle:(e,t,s,r)=>{let i=t.includes("!trusted");this.htmlBindings.set(e,{expr:s,trusted:i}),this.markInlineDeclaration(e,"attr:html"),e instanceof HTMLElement&&(A(e,s,r,i),i&&this.handleTrustedHtml(e)),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-each",match:e=>e==="vsn-each",handle:(e,t,s,r)=>{let i=this.parseEachExpression(s);i&&(this.eachBindings.set(e,{...i,rendered:[]}),this.renderEach(e),this.watch(r,i.listExpr,()=>this.renderEach(e)))}}),this.registerAttributeHandler({id:"vsn-get",match:e=>e.startsWith("vsn-get"),handle:(e,t)=>{let s=t.includes("!trusted"),r=t.includes("!load"),i=e.getAttribute(t)??"",n=e.getAttribute("vsn-target")??void 0,a=e.getAttribute("vsn-swap")??"inner",o={url:i,swap:a,trusted:s,...n?{targetSelector:n}:{}};this.getBindings.set(e,o),this.attachGetHandler(e,r)}}),this.registerAttributeHandler({id:"vsn-construct",match:e=>e==="vsn-construct",handle:(e,t,s)=>{this.setLifecycle(e,{construct:s})}}),this.registerAttributeHandler({id:"vsn-destruct",match:e=>e==="vsn-destruct",handle:(e,t,s)=>{this.setLifecycle(e,{destruct:s})}}),this.registerAttributeHandler({id:"vsn-on",match:e=>e.startsWith("vsn-on:"),handle:(e,t,s)=>{let r=this.parseOnAttribute(t,s);r&&this.attachOnHandler(e,r)}})}};var Be="0.1.0";function ft(c){return new W(c).parseProgram()}function Ne(c=document){if(typeof document>"u")return null;let e=new U,t=typeof performance<"u"&&performance.now?performance.now():Date.now(),s=()=>{let r=c instanceof Document?c.body:c;if(r){let i=Array.from(document.querySelectorAll('script[type="text/vsn"]')).map(o=>o.textContent??"").join(`
8
- `);i.trim()&&e.registerBehaviors(i),e.mount(r);let n=typeof performance<"u"&&performance.now?performance.now():Date.now(),a=Math.round(n-t);console.log(`Took ${a}ms to start up VSN.js. https://www.vsnjs.com/ v${Be}`)}};return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s,{once:!0}):s(),e}typeof document<"u"&&document.querySelector("script[auto-mount]")&&Ne();export{se as ArrayExpression,H as ArrayPattern,B as AssignmentNode,q as AwaitExpression,u as BaseNode,C as BehaviorNode,v as BinaryExpression,y as BlockNode,w as CallExpression,F as DeclarationNode,x as DirectiveExpression,U as Engine,Y as ForNode,L as FunctionDeclarationNode,N as FunctionExpression,m as IdentifierExpression,Z as IfNode,ie as IndexExpression,T as Lexer,k as LiteralExpression,S as MemberExpression,re as ObjectExpression,M as ObjectPattern,b as OnBlockNode,W as Parser,j as ProgramNode,ne as QueryExpression,I as RestElement,D as ReturnNode,K as SelectorNode,R as SpreadElement,_ as StateBlockNode,Q as StateEntryNode,ee as TemplateExpression,te as TernaryExpression,me as TokenType,X as TryNode,O as UnaryExpression,G as UseNode,Be as VERSION,J as WhileNode,Ne as autoMount,ft as parseCFS};
6
+ ${i}`}parseBlock(e){let t=e?.allowDeclarations??!1;this.stream.skipWhitespace(),this.stream.expect("LBrace");let s=[],r=t,i=!1,n=!1,a=!1;for(;;){this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Unterminated block");if(o.type==="RBrace"){this.stream.next();break}if(t&&o.type==="Behavior"&&(a=!0),t&&a&&o.type!=="Behavior")throw new Error("Nested behaviors must appear after construct, function, and on blocks");if(t&&this.isFunctionDeclarationStart()){i||(n=!0),s.push(this.parseFunctionDeclaration());continue}if(t&&this.isFunctionExpressionAssignmentStart()){if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseAssignment());continue}if(this.isDeclarationStart()){if(!t)throw new Error("Declarations are only allowed at the behavior root");if(!r)throw new Error("Declarations must appear before blocks");s.push(this.parseDeclaration())}else{if(r&&(r=!1),t&&o.type==="On"&&!i&&(n=!0),t&&o.type==="Construct"){if(n)throw new Error("Construct blocks must appear before functions and on blocks");i=!0}s.push(this.parseStatement())}}return new y(s)}parseStatement(e){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unexpected end of input");let s=e?.allowBlocks??!0,r=e?.allowReturn??!1;if(t.type==="Return"){if(!r)throw new Error("Return is only allowed inside functions");return this.parseReturnStatement()}if(s&&t.type==="On")return this.parseOnBlock();if(s&&t.type==="If")return this.parseIfBlock();if(s&&t.type==="For")return this.parseForBlock();if(s&&t.type==="While")return this.parseWhileBlock();if(s&&t.type==="Try")return this.parseTryBlock();if(s&&t.type==="Construct")return this.parseConstructBlock();if(s&&t.type==="Destruct")return this.parseDestructBlock();if(s&&t.type==="Behavior")return this.parseBehavior();if(this.isAwaitAllowed()&&t.type==="Identifier"&&t.value==="await")return this.parseExpressionStatement();if(this.isAssignmentStart())return this.parseAssignment();if(this.isExpressionStatementStart())return this.parseExpressionStatement();throw new Error(`Unexpected token ${t.type}`)}parseStateBlock(){this.stream.expect("State"),this.stream.skipWhitespace(),this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated state block");if(t.type==="RBrace"){this.stream.next();break}let s=this.stream.expect("Identifier");this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let r=this.parseExpression();this.stream.skipWhitespace();let i=!1;if(this.stream.peek()?.type==="Bang"){this.stream.next(),this.stream.skipWhitespace();let n=this.stream.next();if(n.type==="Identifier"&&n.value==="important")i=!0;else throw new Error("Expected 'important' after '!'")}this.stream.skipWhitespace(),this.stream.expect("Semicolon"),e.push(new Q(s.value,r,i))}return new _(e)}parseOnBlock(){this.stream.expect("On"),this.stream.skipWhitespace();let e=this.parseIdentifierPath();this.stream.skipWhitespace(),this.stream.expect("LParen");let t=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated on() arguments");if(i.type==="RParen"){this.stream.next();break}if(i.type==="Identifier"){t.push(this.stream.next().value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&this.stream.next();continue}throw new Error(`Unexpected token in on() args: ${i.type}`)}let s=this.parseOnModifiers(),r=this.parseBlock({allowDeclarations:!1});return new b(e,t,r,s)}parseOnModifiers(){let e=[];for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let t=this.stream.expect("Identifier").value;e.push(t)}return e}parseAssignment(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace();let t=this.parseAssignmentOperator();this.stream.skipWhitespace();let s=this.parseExpression();return this.consumeStatementTerminator(),new B(e,s,t)}parseExpression(){return this.parsePipeExpression()}parsePipeExpression(){let e=this.parseTernaryExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Pipe";){this.stream.next(),this.stream.skipWhitespace();let t=!1,s=this.stream.peek();this.isAwaitAllowed()&&s?.type==="Identifier"&&s.value==="await"&&(this.stream.next(),this.stream.skipWhitespace(),t=!0);let r=this.parseCallExpression(),i=this.buildPipeCall(e,r);e=t?new U(i):i}return e}buildPipeCall(e,t){if(t instanceof w)return new w(t.callee,[e,...t.args]);if(t instanceof m||t instanceof N)return new w(t,[e]);throw new Error("Pipe operator requires a function call")}parseTernaryExpression(){let e=this.parseNullishExpression();if(this.stream.skipWhitespace(),this.stream.peek()?.type!=="Question")return e;this.stream.next(),this.stream.skipWhitespace();let t=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace();let s=this.parseExpression();return new te(e,t,s)}parseNullishExpression(){let e=this.parseLogicalOrExpression();for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="NullishCoalesce";){this.stream.next(),this.stream.skipWhitespace();let t=this.parseLogicalOrExpression();e=new v("??",e,t)}return e}parseLogicalOrExpression(){let e=this.parseLogicalAndExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Or")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseLogicalAndExpression();this.stream.skipWhitespace(),e=new v("||",e,s)}return e}parseLogicalAndExpression(){let e=this.parseEqualityExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="And")break;this.stream.skipWhitespace(),this.stream.next(),this.stream.skipWhitespace();let s=this.parseEqualityExpression();this.stream.skipWhitespace(),e=new v("&&",e,s)}return e}parseEqualityExpression(){let e=this.parseComparisonExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="DoubleEquals"&&t.type!=="NotEquals"&&t.type!=="TripleEquals"&&t.type!=="StrictNotEquals")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseComparisonExpression();this.stream.skipWhitespace();let i="==";s.type==="NotEquals"?i="!=":s.type==="TripleEquals"?i="===":s.type==="StrictNotEquals"&&(i="!=="),e=new v(i,e,r)}return e}parseComparisonExpression(){let e=this.parseAdditiveExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Less"&&t.type!=="Greater"&&t.type!=="LessEqual"&&t.type!=="GreaterEqual")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseAdditiveExpression();this.stream.skipWhitespace();let i="<";s.type==="Greater"?i=">":s.type==="LessEqual"?i="<=":s.type==="GreaterEqual"&&(i=">="),e=new v(i,e,r)}return e}parseMultiplicativeExpression(){let e=this.parseUnaryExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Star"&&t.type!=="Slash"&&t.type!=="Percent")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseUnaryExpression();this.stream.skipWhitespace();let i="*";s.type==="Slash"?i="/":s.type==="Percent"&&(i="%"),e=new v(i,e,r)}return e}parseAdditiveExpression(){let e=this.parseMultiplicativeExpression();for(this.stream.skipWhitespace();;){let t=this.stream.peekNonWhitespace(0);if(!t||t.type!=="Plus"&&t.type!=="Minus")break;this.stream.skipWhitespace();let s=this.stream.next();this.stream.skipWhitespace();let r=this.parseMultiplicativeExpression();this.stream.skipWhitespace(),e=new v(s.type==="Plus"?"+":"-",e,r)}return e}parseUnaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="Bang"){this.stream.next();let t=this.parseUnaryExpression();return new O("!",t)}if(e.type==="Minus"){this.stream.next();let t=this.parseUnaryExpression();return new O("-",t)}if(this.isAwaitAllowed()&&e.type==="Identifier"&&e.value==="await"){this.stream.next();let t=this.parseUnaryExpression();return new U(t)}return this.parseCallExpression()}parseCallExpression(){let e=this.parsePrimaryExpression();for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)break;if(t.type==="LParen"){this.stream.next();let s=[];for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated call expression");if(r.type==="RParen"){this.stream.next();break}if(s.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,s);continue}if(t.type==="OptionalChain"){this.stream.next(),this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Expected property or call after ?.");if(s.type==="LParen"){this.stream.next();let r=[];for(;;){this.stream.skipWhitespace();let i=this.stream.peek();if(!i)throw new Error("Unterminated call expression");if(i.type==="RParen"){this.stream.next();break}if(r.push(this.parseExpression()),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in call arguments")}e=new w(e,r);continue}if(s.type==="Identifier"){let r=this.stream.next();e=new N(e,r.value,!0);continue}throw new Error("Expected property or call after ?.")}if(t.type==="Dot"){this.stream.next();let s=this.stream.expect("Identifier");e=new N(e,s.value);continue}if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),e=new ie(e,s);continue}break}return e}parsePrimaryExpression(){this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Expected expression");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Question")return this.parseQueryExpression();if(e.type==="LBracket")return this.parseArrayExpression();if(e.type==="LBrace")return this.parseObjectExpression();if(e.type==="LParen"){if(this.isArrowFunctionStart())return this.parseArrowFunctionExpression();this.stream.next();let t=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}if(e.type==="Identifier")return this.isAsyncToken(e)&&this.isAsyncArrowFunctionStart()?(this.stream.next(),this.stream.skipWhitespace(),this.parseArrowFunctionExpression(!0)):new m(this.stream.next().value);if(e.type==="Boolean")return new k(this.stream.next().value==="true");if(e.type==="Null")return this.stream.next(),new k(null);if(e.type==="Number")return new k(Number(this.stream.next().value));if(e.type==="String")return new k(this.stream.next().value);if(e.type==="Template")return this.parseTemplateExpression();throw new Error(`Unsupported expression token ${e.type}`)}parseArrayExpression(){this.stream.expect("LBracket");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated array literal");if(t.type==="RBracket"){this.stream.next();break}if(t.type==="Ellipsis"){this.stream.next(),this.stream.skipWhitespace();let s=this.parseExpression();e.push(new R(s))}else e.push(this.parseExpression());if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBracket"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array literal")}return new se(e)}parseTemplateExpression(){let e=[];for(;;){let t=this.stream.peek();if(!t)throw new Error("Unterminated template literal");if(t.type!=="Template")throw new Error("Expected template literal");let s=this.stream.next().value;s&&e.push(new k(s));let r=this.stream.peek();if(!r||r.type!=="Dollar")break;this.stream.next(),this.stream.expect("LBrace"),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBrace"),e.push(i)}return new ee(e)}parseObjectExpression(){this.stream.expect("LBrace");let e=[];for(;;){this.stream.skipWhitespace();let t=this.stream.peek();if(!t)throw new Error("Unterminated object literal");if(t.type==="RBrace"){this.stream.next();break}let s,r;if(t.type==="Ellipsis")this.stream.next(),this.stream.skipWhitespace(),r={spread:this.parseExpression()};else if(t.type==="LBracket"){this.stream.next(),this.stream.skipWhitespace();let i=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RBracket"),this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={keyExpr:i,value:s,computed:!0}}else if(t.type==="Identifier"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.peek()?.type==="Colon"?(this.stream.next(),this.stream.skipWhitespace(),s=this.parseExpression()):s=new m(i),r={key:i,value:s}}else if(t.type==="String"){let i=this.stream.next().value;this.stream.skipWhitespace(),this.stream.expect("Colon"),this.stream.skipWhitespace(),s=this.parseExpression(),r={key:i,value:s}}else throw new Error(`Unexpected token in object literal: ${t.type}`);if(!r)throw new Error("Invalid object literal entry");if(e.push(r),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object literal")}return new re(e)}consumeStatementTerminator(){this.stream.skipWhitespace();let e=this.stream.peek();if(e?.type==="Semicolon"){this.stream.next();return}this.allowImplicitSemicolon&&e?.type==="RBrace"||this.stream.expect("Semicolon")}parseFunctionBlockWithAwait(e){this.stream.expect("LBrace");let t=[];this.awaitStack.push(e);try{for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function block");if(s.type==="RBrace"){this.stream.next();break}t.push(this.parseStatement({allowBlocks:!1,allowReturn:!0}))}}finally{this.awaitStack.pop()}return new y(t)}isAsyncToken(e){return e?.type==="Identifier"&&e.value==="async"}isAwaitAllowed(){return this.awaitStack.length===0?!1:this.awaitStack[this.awaitStack.length-1]===!0}parseArrowExpressionBody(e){this.awaitStack.push(e);try{let t=this.parseExpression();return new y([new D(t)])}finally{this.awaitStack.pop()}}parseAssignmentTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected assignment target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="LBracket")return this.parseArrayPattern();if(e.type==="LBrace")return this.parseObjectPattern();if(e.type==="Identifier")return new m(this.parseIdentifierPath());throw new Error(`Invalid assignment target ${e.type}`)}parseArrayPattern(){this.stream.expect("LBracket");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated array pattern");if(s.type==="RBracket"){this.stream.next();break}if(s.type==="Comma"){this.stream.next(),e.push(null);continue}if(s.type==="Ellipsis"){if(t)throw new Error("Array patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Identifier");e.push(new M(new m(r.value))),t=!0}else if(s.type==="LBracket")e.push(this.parseArrayPattern());else if(s.type==="LBrace")e.push(this.parseObjectPattern());else if(s.type==="Identifier")e.push(new m(this.parseIdentifierPath()));else throw new Error(`Unexpected token in array pattern: ${s.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RBracket"){this.stream.next();break}throw new Error("Expected ',' or ']' in array pattern")}if(t&&!(e[e.length-1]instanceof M))throw new Error("Rest element must be last in array pattern");return new H(e)}parseObjectPattern(){this.stream.expect("LBrace");let e=[],t;for(;;){this.stream.skipWhitespace();let r=this.stream.peek();if(!r)throw new Error("Unterminated object pattern");if(r.type==="RBrace"){this.stream.next();break}if(r.type==="Ellipsis"){if(t)throw new Error("Object patterns can only include one rest element");this.stream.next(),this.stream.skipWhitespace();let i=this.stream.expect("Identifier");if(t=new m(i.value),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"&&(this.stream.next(),this.stream.skipWhitespace()),this.stream.peek()?.type!=="RBrace")throw new Error("Rest element must be last in object pattern");this.stream.next();break}else if(r.type==="Identifier"||r.type==="String"){let n=this.stream.next().value;this.stream.skipWhitespace();let a;if(this.stream.peek()?.type==="Colon"){this.stream.next(),this.stream.skipWhitespace();let o=this.stream.peek();if(!o)throw new Error("Expected object pattern target");if(o.type==="LBracket")a=this.parseArrayPattern();else if(o.type==="LBrace")a=this.parseObjectPattern();else if(o.type==="Identifier")a=new m(this.parseIdentifierPath());else throw new Error(`Unexpected token in object pattern: ${o.type}`)}else a=new m(n);e.push({key:n,target:a})}else throw new Error(`Unexpected token in object pattern: ${r.type}`);if(this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="RBrace"){this.stream.next();break}continue}if(this.stream.peek()?.type==="RBrace"){this.stream.next();break}throw new Error("Expected ',' or '}' in object pattern")}let s=t?[...e,{rest:t}]:e;return t&&e.length===0?new I([{rest:t}]):new I(s)}parseDeclaration(){let e=this.parseDeclarationTarget();this.stream.skipWhitespace();let t=this.parseDeclarationOperator();this.stream.skipWhitespace();let s=this.parseExpression(),{flags:r,flagArgs:i}=this.parseFlags();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new F(e,t,s,r,i)}parseDeclarationTarget(){let e=this.stream.peek();if(!e)throw new Error("Expected declaration target");if(e.type==="At"||e.type==="Dollar"){let t=e.type==="At"?"attr":"style";this.stream.next();let s=this.stream.expect("Identifier");return new x(t,s.value)}if(e.type==="Identifier")return new m(this.stream.next().value);throw new Error(`Invalid declaration target ${e.type}`)}parseDeclarationOperator(){this.stream.expect("Colon");let e=this.stream.peek();return e?e.type==="Equals"?(this.stream.next(),":="):e.type==="Less"?(this.stream.next(),":<"):e.type==="Greater"?(this.stream.next(),":>"):":":":"}parseFlags(){let e={},t={};for(;this.stream.skipWhitespace(),this.stream.peek()?.type==="Bang";){this.stream.next();let s=this.stream.expect("Identifier").value;if(s==="important")e.important=!0;else if(s==="trusted")e.trusted=!0;else if(s==="debounce")if(e.debounce=!0,this.stream.peek()?.type==="LParen"){this.stream.next(),this.stream.skipWhitespace();let r=this.stream.expect("Number");t.debounce=Number(r.value),this.stream.skipWhitespace(),this.stream.expect("RParen")}else t.debounce=200;else if(this.customFlags.has(s)){e[s]=!0;let r=this.parseCustomFlagArg();r!==void 0&&(t[s]=r)}else throw new Error(`Unknown flag ${s}`)}return{flags:e,flagArgs:t}}parseCustomFlagArg(){if(this.stream.peek()?.type!=="LParen")return;this.stream.next(),this.stream.skipWhitespace();let e=this.stream.peek();if(!e)throw new Error("Unterminated flag arguments");let t;if(e.type==="Number")t=Number(this.stream.next().value);else if(e.type==="String")t=this.stream.next().value;else if(e.type==="Boolean")t=this.stream.next().value==="true";else if(e.type==="Identifier")t=this.stream.next().value;else throw new Error(`Unsupported flag argument ${e.type}`);return this.stream.skipWhitespace(),this.stream.expect("RParen"),t}isDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier")return this.stream.peekNonWhitespace(1)?.type==="Colon";if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&s?.type==="Colon"}return!1}isAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;if(e.type==="Identifier"){let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.isAssignmentOperatorStart(t)}if(e.type==="At"||e.type==="Dollar"){let t=this.stream.peekNonWhitespace(1),s=this.stream.peekNonWhitespace(2);return t?.type==="Identifier"&&this.isAssignmentOperatorStart(2)}if(e.type==="LBrace"||e.type==="LBracket"){let t=[],s=0;for(;;){let r=this.stream.peekNonWhitespace(s);if(!r)return!1;if(r.type==="LBrace"||r.type==="LBracket")t.push(r.type);else if((r.type==="RBrace"||r.type==="RBracket")&&(t.pop(),t.length===0))return this.isAssignmentOperatorStart(s+1);s+=1}}return!1}isAssignmentOperatorStart(e){let t=this.stream.peekNonWhitespace(e);return t?t.type==="Equals"?!0:t.type==="Plus"||t.type==="Minus"||t.type==="Star"||t.type==="Slash"?this.stream.peekNonWhitespace(e+1)?.type==="Equals":!1:!1}isCallStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier")return!1;let t=1;for(;this.stream.peekNonWhitespace(t)?.type==="Dot"&&this.stream.peekNonWhitespace(t+1)?.type==="Identifier";)t+=2;return this.stream.peekNonWhitespace(t)?.type==="LParen"}isExpressionStatementStart(){let e=this.stream.peekNonWhitespace(0);return e?e.type==="Identifier"?!0:e.type==="Number"||e.type==="String"||e.type==="Boolean"||e.type==="Null"||e.type==="LParen"||e.type==="LBracket"||e.type==="LBrace"||e.type==="At"||e.type==="Dollar"||e.type==="Question"||e.type==="Bang"||e.type==="Minus":!1}isFunctionDeclarationStart(){let e=this.stream.peekNonWhitespace(0);if(!e)return!1;let t=0;if(this.isAsyncToken(e)){let r=this.stream.peekNonWhitespace(1);if(!r||r.type!=="Identifier")return!1;t=1}else if(e.type!=="Identifier")return!1;if(t+=1,this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="LBrace"}isArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="LParen")return!1;let t=1,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isAsyncArrowFunctionStart(){let e=this.stream.peekNonWhitespace(0);if(!this.isAsyncToken(e)||this.stream.peekNonWhitespace(1)?.type!=="LParen")return!1;let t=2,s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}isFunctionExpressionAssignmentStart(){let e=this.stream.peekNonWhitespace(0);if(!e||e.type!=="Identifier"||this.stream.peekNonWhitespace(1)?.type!=="Equals")return!1;let t=2;if(this.isAsyncToken(this.stream.peekNonWhitespace(t))&&(t+=1),this.stream.peekNonWhitespace(t)?.type!=="LParen")return!1;t+=1;let s=1;for(;;){let r=this.stream.peekNonWhitespace(t);if(!r)return!1;if(r.type==="LParen")s+=1;else if(r.type==="RParen"&&(s-=1,s===0)){t+=1;break}t+=1}return this.stream.peekNonWhitespace(t)?.type==="Arrow"}parseExpressionStatement(){let e=this.parseExpression();return this.consumeStatementTerminator(),e}parseIfBlock(){this.stream.expect("If"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace();let s;if(this.stream.peek()?.type==="Else")if(this.stream.next(),this.stream.skipWhitespace(),this.stream.peek()?.type==="If"){let r=this.parseIfBlock();s=new y([r])}else s=this.parseBlock({allowDeclarations:!1});return new Z(e,t,s)}parseWhileBlock(){this.stream.expect("While"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e=this.parseExpression();this.stream.skipWhitespace(),this.stream.expect("RParen");let t=this.parseBlock({allowDeclarations:!1});return new J(e,t)}parseForBlock(){this.stream.expect("For"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let e;this.stream.peek()?.type!=="Semicolon"&&(e=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let t;this.stream.peek()?.type!=="Semicolon"&&(t=this.parseExpression()),this.stream.skipWhitespace(),this.stream.expect("Semicolon"),this.stream.skipWhitespace();let s;this.stream.peek()?.type!=="RParen"&&(s=this.parseForClause()),this.stream.skipWhitespace(),this.stream.expect("RParen");let r=this.parseBlock({allowDeclarations:!1});return new Y(e,t,s,r)}parseForClause(){return this.isAssignmentStart()?this.parseAssignmentExpression():this.parseExpression()}parseAssignmentExpression(){let e=this.parseAssignmentTarget();this.stream.skipWhitespace();let t=this.parseAssignmentOperator();this.stream.skipWhitespace();let s=this.parseExpression();return new B(e,s,t)}parseAssignmentOperator(){let e=this.stream.peek();if(!e)throw new Error("Expected assignment operator");if(e.type==="Equals")return this.stream.next(),"=";if(e.type==="Plus"||e.type==="Minus"||e.type==="Star"||e.type==="Slash"){let t=this.stream.next();return this.stream.expect("Equals"),t.type==="Plus"?"+=":t.type==="Minus"?"-=":t.type==="Star"?"*=":"/="}throw new Error("Expected assignment operator")}parseTryBlock(){this.stream.expect("Try");let e=this.parseBlock({allowDeclarations:!1});this.stream.skipWhitespace(),this.stream.expect("Catch"),this.stream.skipWhitespace(),this.stream.expect("LParen"),this.stream.skipWhitespace();let t=this.stream.expect("Identifier").value;this.stream.skipWhitespace(),this.stream.expect("RParen");let s=this.parseBlock({allowDeclarations:!1});return new X(e,t,s)}parseConstructBlock(){this.stream.expect("Construct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Construct",e}parseDestructBlock(){this.stream.expect("Destruct");let e=this.parseBlock({allowDeclarations:!1});return e.type="Destruct",e}parseQueryExpression(){this.stream.expect("Question");let e="self";this.stream.peek()?.type==="Greater"?(this.stream.next(),e="descendant"):this.stream.peek()?.type==="Less"&&(this.stream.next(),e="ancestor"),this.stream.skipWhitespace(),this.stream.expect("LParen");let t=this.readSelectorUntil("RParen");return new ne(e,t)}parseFunctionDeclaration(){let e=!1,t=this.stream.peekNonWhitespace(0);this.isAsyncToken(t)&&(this.stream.next(),this.stream.skipWhitespace(),e=!0);let s=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let r=this.parseFunctionParams();this.stream.skipWhitespace();let i=this.parseFunctionBlockWithAwait(e);return new L(s,r,i,e)}parseFunctionBlock(){return this.parseFunctionBlockWithAwait(!1)}parseReturnStatement(){if(this.stream.expect("Return"),this.stream.skipWhitespace(),this.stream.peek()?.type==="Semicolon")return this.stream.next(),new D;let e=this.parseExpression();return this.stream.skipWhitespace(),this.stream.expect("Semicolon"),new D(e)}parseArrowFunctionExpression(e=!1){let t=this.parseFunctionParams();if(this.stream.skipWhitespace(),this.stream.expect("Arrow"),this.stream.skipWhitespace(),this.stream.peek()?.type==="LBrace"){let r=this.parseFunctionBlockWithAwait(e);return new S(t,r,e)}let s=this.parseArrowExpressionBody(e);return new S(t,s,e)}parseFunctionParams(){this.stream.expect("LParen");let e=[],t=!1;for(;;){this.stream.skipWhitespace();let s=this.stream.peek();if(!s)throw new Error("Unterminated function parameters");if(s.type==="RParen"){this.stream.next();break}if(s.type==="Ellipsis"){if(t)throw new Error("Function parameters can only include one rest parameter");this.stream.next(),this.stream.skipWhitespace();let n=this.stream.expect("Identifier").value;if(e.push({name:n,rest:!0}),t=!0,this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma")throw new Error("Rest parameter must be last in function parameters");this.stream.expect("RParen");break}let r=this.stream.expect("Identifier").value;this.stream.skipWhitespace();let i;if(this.stream.peek()?.type==="Equals"&&(this.stream.next(),this.stream.skipWhitespace(),i=this.parseExpression()),e.push(i?{name:r,defaultValue:i}:{name:r}),this.stream.skipWhitespace(),this.stream.peek()?.type==="Comma"){this.stream.next();continue}if(this.stream.peek()?.type==="RParen"){this.stream.next();break}throw new Error("Expected ',' or ')' in function parameters")}return e}readSelectorUntil(e){let t="",s=!1;for(;;){let r=this.stream.peek();if(!r)throw new Error("Unterminated selector");if(r.type===e){this.stream.next();break}if(r.type==="Whitespace"){this.stream.next(),s&&t[t.length-1]!==" "&&(t+=" ");continue}s=!0,t+=this.stream.next().value}return t.trim()}parseIdentifierPath(){let e=this.stream.expect("Identifier").value;for(;this.stream.peek()?.type==="Dot";){this.stream.next();let t=this.stream.expect("Identifier").value;e=`${e}.${t}`}return e}};var $=class p{constructor(e){this.parent=e;this.root=e?e.root:this}data=new Map;root;listeners=new Map;anyListeners=new Set;createChild(){return new p(this)}get(e){return this.getPath(e)}set(e,t){this.setPath(e,t)}hasKey(e){let s=e.split(".")[0];return s?this.data.has(s):!1}getPath(e){let t=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:s,targetPath:r}=this.resolveScope(e);if(!s||!r)return;let i=this.getLocalPathValue(s,r);if(t||i!==void 0)return i;let n=s.parent;for(;n;){let a=this.getLocalPathValue(n,r);if(a!==void 0)return a;n=n.parent}}setPath(e,t){let s=e.startsWith("parent.")||e.startsWith("root.")||e.startsWith("self."),{targetScope:r,targetPath:i}=this.resolveScope(e);if(!r||!i)return;let n=s?r:this.findNearestScopeWithKey(r,i)??r,a=i.split("."),o=a[0];if(!o)return;if(a.length===1){n.data.set(o,t),n.emitChange(i);return}let c=n.data.get(o);(c==null||typeof c!="object")&&(c={},n.data.set(o,c));let h=c;for(let d=1;d<a.length-1;d+=1){let g=a[d];if(!g)return;(h[g]==null||typeof h[g]!="object")&&(h[g]={}),h=h[g]}let f=a[a.length-1];f&&(h[f]=t,n.emitChange(i))}on(e,t){let s=e.trim();if(!s)return;let r=this.listeners.get(s)??new Set;r.add(t),this.listeners.set(s,r)}off(e,t){let s=e.trim(),r=this.listeners.get(s);r&&(r.delete(t),r.size===0&&this.listeners.delete(s))}onAny(e){this.anyListeners.add(e)}offAny(e){this.anyListeners.delete(e)}emitChange(e){let t=e.trim();if(!t)return;this.listeners.get(t)?.forEach(r=>r());let s=t.split(".")[0];s&&s!==t&&this.listeners.get(s)?.forEach(r=>r()),this.anyListeners.forEach(r=>r())}resolveScope(e){let t=this,s=e;for(;s.startsWith("parent.");)t=t?.parent,s=s.slice(7);for(s.startsWith("root.")&&(t=t?.root,s=s.slice(5));s.startsWith("self.");)t=t??this,s=s.slice(5);return{targetScope:t,targetPath:s}}getLocalPathValue(e,t){let s=t.split("."),r=s[0];if(!r)return;let i=e.data.get(r);for(let n=1;n<s.length;n+=1){if(i==null)return;let a=s[n];if(!a)return;i=i[a]}return i}findNearestScopeWithKey(e,t){let s=t.split(".")[0];if(!s)return;let r=e;for(;r;){if(r.data.has(s))return r;r=r.parent}}};function Ee(p){return p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement?p.value:p.textContent??""}function ke(p,e){if(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement){p.value=e,p.setAttribute("value",e);return}if(p instanceof HTMLSelectElement){p.value=e;return}p instanceof HTMLElement&&p.querySelector("*")||(p.textContent=e)}function oe(p,e,t){let s=e.trim();if(!s)return;let r=Ee(p);t.set(s,r)}function ce(p,e,t){let s=e.trim();if(!s)return;let r=t.get(s);r!=null&&ke(p,String(r))}function ge(p,e){let t=p.trim();return t?!!e.get(t):!1}function le(p,e,t){p.style.display=ge(e,t)?"":"none"}function he(p,e,t){p.style.display=ge(e,t)?"":"none"}function we(p){return p.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"")}function W(p,e,t,s){let r=e.trim();if(!r)return;let i=t.get(r),n=i==null?"":String(i);p.innerHTML=s?n:we(n)}async function ye(p,e,t,s){if(!globalThis.fetch)throw new Error("fetch is not available");let r=await globalThis.fetch(e.url);if(!r||!r.ok)return;let i=await r.text(),n=be(p,e.targetSelector);if(!n){p.dispatchEvent(new CustomEvent("vsn:targetError",{detail:{selector:e.targetSelector}}));return}if(e.swap==="outer"){let a=document.createElement("div");W(a,"__html",{get:()=>i},e.trusted);let o=a.firstElementChild;o&&n.parentNode&&(n.parentNode.replaceChild(o,n),s?.(o));return}W(n,"__html",{get:()=>i},e.trusted),s?.(n)}function be(p,e){return e?p.ownerDocument.querySelector(e):p}function P(p,e){let t;return(...s)=>{t&&clearTimeout(t),t=setTimeout(()=>{t=void 0,p(...s)},e)}}var q=class p{static activeEngines=new WeakMap;scopes=new WeakMap;bindBindings=new WeakMap;ifBindings=new WeakMap;showBindings=new WeakMap;htmlBindings=new WeakMap;getBindings=new WeakMap;eachBindings=new WeakMap;lifecycleBindings=new WeakMap;behaviorRegistry=[];behaviorBindings=new WeakMap;behaviorListeners=new WeakMap;behaviorId=0;codeCache=new Map;behaviorCache=new Map;observer;observerRoot;attributeHandlers=[];globals={};importantFlags=new WeakMap;inlineDeclarations=new WeakMap;flagHandlers=new Map;pendingAdded=new Set;pendingRemoved=new Set;pendingUpdated=new Set;observerFlush;ignoredAdded=new WeakMap;diagnostics;logger;pendingUses=[];constructor(e={}){this.diagnostics=e.diagnostics??!1,this.logger=e.logger??console,this.registerGlobal("console",console),this.registerGlobal("list",{async map(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)r.push(await s(t[i],i));return r},async filter(t,s){if(!Array.isArray(t)||typeof s!="function")return[];let r=[];for(let i=0;i<t.length;i+=1)await s(t[i],i)&&r.push(t[i]);return r},async reduce(t,s,r){if(!Array.isArray(t)||typeof s!="function")return r;let i=arguments.length>2,n=i?r:t[0],a=i?0:1;for(let o=a;o<t.length;o+=1)n=await s(n,t[o],o);return n}}),this.registerDefaultAttributeHandlers()}async mount(e){let t=e.ownerDocument,s=p.activeEngines.get(t);s&&s!==this&&s.disconnectObserver(),p.activeEngines.set(t,this);let r=[e,...Array.from(e.querySelectorAll("*"))];for(let i of r){if(!this.hasVsnAttributes(i))continue;let n=this.findParentScope(i);this.getScope(i,n),this.attachAttributes(i),this.runConstruct(i)}await this.applyBehaviors(e),this.attachObserver(e)}unmount(e){this.runDestruct(e),this.disconnectObserver()}registerBehaviors(e){let t=new A(e,{customFlags:new Set(this.flagHandlers.keys())}).parseProgram();for(let s of t.uses){if(s.flags?.wait){this.pendingUses.push(this.waitForUseGlobal(s));continue}let r=this.resolveGlobalPath(s.name);if(r===void 0){console.warn(`vsn: global '${s.name}' not found`);continue}this.registerGlobal(s.alias,r)}for(let s of t.behaviors)this.collectBehavior(s)}registerGlobal(e,t){this.globals[e]=t}registerGlobals(e){Object.assign(this.globals,e)}registerFlag(e,t={}){if(new Set(["important","trusted","debounce"]).has(e))throw new Error(`Flag '${e}' is reserved`);this.flagHandlers.set(e,t)}getRegistryStats(){return{behaviorCount:this.behaviorRegistry.length,behaviorCacheSize:this.behaviorCache.size}}registerAttributeHandler(e){this.attributeHandlers.push(e)}resolveGlobalPath(e){let t=e.split("."),s=t[0];if(!s)return;let r=globalThis[s];for(let i=1;i<t.length;i+=1){let n=t[i];if(!n)return;r=r?.[n]}return r}async waitForUses(){for(;this.pendingUses.length>0;){let e=this.pendingUses;this.pendingUses=[],await Promise.all(e)}}waitForUseGlobal(e){let t=e.flagArgs?.wait??{},s=t.timeoutMs??1e4,r=t.intervalMs??100,i=1e3,n=this.resolveGlobalPath(e.name);return n!==void 0?(this.registerGlobal(e.alias,n),Promise.resolve()):s<=0?(this.emitUseError(e.name,new Error(`vsn: global '${e.name}' not found`)),Promise.resolve()):new Promise(a=>{let o=0,c=r,h=()=>{let f=this.resolveGlobalPath(e.name);if(f!==void 0){this.registerGlobal(e.alias,f),a();return}if(o>=s){this.emitUseError(e.name,new Error(`vsn: global '${e.name}' not found`)),a();return}let d=Math.min(c,s-o);setTimeout(()=>{o+=d,c=Math.min(c*2,i),h()},d)};h()})}getScope(e,t){let s=this.scopes.get(e);if(s)return s;let r=new $(t??this.findParentScope(e));return this.scopes.set(e,r),r}evaluate(e){let t=this.getScope(e),s=this.bindBindings.get(e);s&&(s.direction==="from"||s.direction==="both")&&ce(e,s.expr,t);let r=this.ifBindings.get(e);r&&e instanceof HTMLElement&&le(e,r,t);let i=this.showBindings.get(e);i&&e instanceof HTMLElement&&he(e,i,t);let n=this.htmlBindings.get(e);n&&e instanceof HTMLElement&&(W(e,n.expr,t,n.trusted),n.trusted&&this.handleTrustedHtml(e))}attachObserver(e){this.observer||(this.observerRoot=e,this.observerFlush=P(()=>this.flushObserverQueue(),10),this.observer=new MutationObserver(t=>{for(let s of t){s.type==="attributes"&&s.target instanceof Element&&this.pendingUpdated.add(s.target);for(let r of Array.from(s.addedNodes))if(r&&r.nodeType===1){let i=r;if(this.ignoredAdded.has(i)){this.ignoredAdded.delete(i);continue}this.pendingAdded.add(i)}for(let r of Array.from(s.removedNodes))r&&r.nodeType===1&&this.pendingRemoved.add(r)}this.observerFlush?.()}),this.observer.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class"]}))}disconnectObserver(){this.observer?.disconnect(),this.observer=void 0,this.observerRoot=void 0,this.pendingAdded.clear(),this.pendingRemoved.clear(),this.pendingUpdated.clear()}flushObserverQueue(){let e=Array.from(this.pendingRemoved);this.pendingRemoved.clear();for(let r of e)this.handleRemovedNode(r);let t=Array.from(this.pendingUpdated);this.pendingUpdated.clear();for(let r of t)this.handleUpdatedNode(r);let s=Array.from(this.pendingAdded);this.pendingAdded.clear();for(let r of s)this.handleAddedNode(r)}handleRemovedNode(e){this.lifecycleBindings.has(e)&&this.runDestruct(e),this.behaviorBindings.has(e)&&this.runBehaviorDestruct(e);for(let t of Array.from(e.querySelectorAll("*")))this.lifecycleBindings.has(t)&&this.runDestruct(t),this.behaviorBindings.has(t)&&this.runBehaviorDestruct(t)}handleAddedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t){if(!this.hasVsnAttributes(s))continue;let r=this.findParentScope(s);this.getScope(s,r),this.attachAttributes(s),this.runConstruct(s)}this.applyBehaviors(e)}handleUpdatedNode(e){let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)this.reapplyBehaviorsForElement(s)}async applyBehaviors(e){if(await this.waitForUses(),this.behaviorRegistry.length===0)return;let t=[e,...Array.from(e.querySelectorAll("*"))];for(let s of t)await this.reapplyBehaviorsForElement(s)}async reapplyBehaviorsForElement(e){if(this.behaviorRegistry.length===0)return;let t=this.behaviorBindings.get(e)??new Set,s=this.getScope(e),r=this.behaviorRegistry.filter(n=>e.matches(n.selector)).sort((n,a)=>n.specificity!==a.specificity?n.specificity-a.specificity:n.order-a.order);for(let n of r)t.has(n.id)||await this.applyBehaviorForElement(n,e,s,t);let i=new Set(r.map(n=>n.id));for(let n of this.behaviorRegistry)t.has(n.id)&&!i.has(n.id)&&this.unbindBehaviorForElement(n,e,s,t);this.behaviorBindings.set(e,t)}async applyBehaviorForElement(e,t,s,r){r.add(e.id);let i=this.getBehaviorRootScope(t,e);this.applyBehaviorFunctions(t,s,e.functions,i),await this.applyBehaviorDeclarations(t,s,e.declarations,i),e.construct&&await this.safeExecuteBlock(e.construct,s,t,i);for(let n of e.onBlocks)this.attachBehaviorOnHandler(t,n.event,n.body,n.modifiers,n.args,e.id,i);this.logDiagnostic("bind",t,e)}unbindBehaviorForElement(e,t,s,r){if(r.delete(e.id),e.destruct){let a=this.getBehaviorRootScope(t,e);this.safeExecuteBlock(e.destruct,s,t,a)}let i=this.behaviorListeners.get(t),n=i?.get(e.id);if(n){for(let a of n)a.target.removeEventListener(a.event,a.handler,a.options);i?.delete(e.id)}this.logDiagnostic("unbind",t,e)}runBehaviorDestruct(e){let t=this.behaviorBindings.get(e);if(!t)return;let s=this.getScope(e);for(let r of this.behaviorRegistry){if(!t.has(r.id)||!r.destruct)continue;let i=this.getBehaviorRootScope(e,r);this.safeExecuteBlock(r.destruct,s,e,i)}}attachAttributes(e){let t=this.getScope(e);for(let s of e.getAttributeNames()){if(!s.startsWith("vsn-"))continue;let r=e.getAttribute(s)??"";for(let i of this.attributeHandlers){if(!i.match(s))continue;if(i.handle(e,s,r,t)!==!1)break}}}setLifecycle(e,t){let s=this.lifecycleBindings.get(e)??{};this.lifecycleBindings.set(e,{...s,...t})}runConstruct(e){let t=this.lifecycleBindings.get(e);if(!t?.construct)return;let s=this.getScope(e);this.safeExecute(t.construct,s,e)}runDestruct(e){let t=this.lifecycleBindings.get(e);if(!t?.destruct)return;let s=this.getScope(e);this.safeExecute(t.destruct,s,e)}parseEachExpression(e){let[t,s]=e.split(/\s+as\s+/);if(!t||!s)return null;let r=t.trim(),i=s.split(",").map(o=>o.trim()).filter(Boolean);if(!r||i.length===0)return null;let n=i[0]??"",a=i[1];return{listExpr:r,itemName:n,...a?{indexName:a}:{}}}renderEach(e){let t=this.eachBindings.get(e);if(!t||!(e instanceof HTMLTemplateElement))return;let s=e.parentElement;if(!s)return;for(let a of t.rendered)this.handleRemovedNode(a),a.parentNode&&a.parentNode.removeChild(a);t.rendered=[];let r=this.getScope(e),i=r.get(t.listExpr);if(!Array.isArray(i))return;let n=[];i.forEach((a,o)=>{let c=e.content.cloneNode(!0),h=Array.from(c.children),f=new $(r);f.setPath(`self.${t.itemName}`,a),t.indexName&&f.setPath(`self.${t.indexName}`,o);for(let d of h)this.getScope(d,f);s.insertBefore(c,e);for(let d of h){this.ignoredAdded.set(d,!0),n.push(d),this.handleAddedNode(d),this.evaluate(d);for(let g of Array.from(d.querySelectorAll("*")))this.evaluate(g)}}),t.rendered=n}attachBindInputHandler(e,t){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let s=()=>{let r=this.getScope(e);oe(e,t,r)};e.addEventListener("input",s),e.addEventListener("change",s)}parseBindDirection(e){return e.includes(":from")?"from":e.includes(":to")?"to":"both"}hasVsnAttributes(e){return e.getAttributeNames().some(t=>t.startsWith("vsn-"))}markInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e)??new Set;s.add(t),this.inlineDeclarations.set(e,s)}isInlineDeclaration(e,t){let s=this.inlineDeclarations.get(e);return s?s.has(t):!1}findParentScope(e){let t=e.parentElement;for(;t;){let s=this.scopes.get(t);if(s)return s;t=t.parentElement}}watch(e,t,s){let r=t.trim();if(!r)return;let i=r.split(".")[0];if(!i)return;let n=e;for(;n&&!n.hasKey(i);)n=n.parent;if(n){n.on(r,s);return}let a=e;for(;a;)a.on(r,s),a=a.parent}watchWithDebounce(e,t,s,r){r?this.watch(e,t,P(s,r)):this.watch(e,t,s)}watchAllScopes(e,t,s){let r=s?P(t,s):t,i=e;for(;i;)i.onAny(r),i=i.parent}parseOnAttribute(e,t){if(!e.startsWith("vsn-on:"))return null;let s=e.slice(7),[r,...i]=s.split("!");if(!r)return null;let n=this.parseEventDescriptor(r);if(!n.event)return null;let a,o=[];for(let f of i){if(f.startsWith("debounce")){let d=f.match(/debounce\((\d+)\)/);a=d?Number(d[1]):200;continue}o.push(f)}let c=[...o,...n.modifiers];return{event:n.event,code:t,...a!==void 0?{debounceMs:a}:{},...c.length>0?{modifiers:c}:{},...n.keyModifiers.length>0?{keyModifiers:n.keyModifiers}:{}}}parseEventDescriptor(e){let t=e.split(".").map(a=>a.trim()).filter(Boolean),s=t.shift()??"",r=[],i=[],n=new Set(["outside","self"]);for(let a of t)n.has(a)?r.push(a):i.push(a);return{event:s,keyModifiers:i,modifiers:r}}matchesKeyModifiers(e,t){if(!t||t.length===0)return!0;if(!(e instanceof KeyboardEvent))return!1;let s={shift:e.shiftKey,ctrl:e.ctrlKey,control:e.ctrlKey,alt:e.altKey,meta:e.metaKey},r={esc:"escape",escape:"escape",enter:"enter",tab:"tab",space:"space",spacebar:"space",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright",arrowup:"arrowup",arrowdown:"arrowdown",arrowleft:"arrowleft",arrowright:"arrowright",delete:"delete",backspace:"backspace"},i=e.key?.toLowerCase()??"";i===" "&&(i="space");for(let n of t){let a=n.toLowerCase();if(a in s){if(!s[a])return!1;continue}let o=r[a]??a;if(i!==o)return!1}return!0}matchesTargetModifiers(e,t,s){if(!s||s.length===0)return!0;let r=t?.target;return!r||!(r instanceof Node)?!s.includes("self")&&!s.includes("outside"):!(s.includes("self")&&r!==e||s.includes("outside")&&e.contains(r))}describeElement(e){let t=e.tagName.toLowerCase(),s=e.id?`#${e.id}`:"",r=e.classList.length>0?`.${Array.from(e.classList).join(".")}`:"";return`${t}${s}${r}`}logDiagnostic(e,t,s){!this.diagnostics||!this.logger.info||this.logger.info(`vsn:${e}`,{element:this.describeElement(t),selector:s.selector,behaviorId:s.id})}emitError(e,t){let s=this.describeElement(e);this.logger.warn?.("vsn:error",{error:t,selector:s}),e.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:t,selector:s},bubbles:!0}))}emitUseError(e,t){let s=`use:${e}`;this.logger.warn?.("vsn:error",{error:t,selector:s});let r=globalThis.document;r&&typeof r.dispatchEvent=="function"&&r.dispatchEvent(new CustomEvent("vsn:error",{detail:{error:t,selector:s},bubbles:!0}))}attachOnHandler(e,t){let s=this.getListenerOptions(t.modifiers),r=t.modifiers?.includes("outside")?e.ownerDocument:e,i,n=async a=>{if(!e.isConnected){r.removeEventListener(t.event,i,s);return}if(!this.matchesKeyModifiers(a,t.keyModifiers)||!this.matchesTargetModifiers(e,a,t.modifiers))return;this.applyEventModifiers(a,t.modifiers);let o=this.getScope(e);try{await this.execute(t.code,o,e),this.evaluate(e)}catch(c){this.emitError(e,c)}};i=t.debounceMs?P(n,t.debounceMs):n,r.addEventListener(t.event,i,s)}attachBehaviorOnHandler(e,t,s,r,i,n,a){let o=this.parseEventDescriptor(t),c=r?[...r,...o.modifiers]:o.modifiers.length>0?[...o.modifiers]:void 0,h=c?.includes("outside")?e.ownerDocument:e,f=async z=>{if(!this.matchesKeyModifiers(z,o.keyModifiers)||!this.matchesTargetModifiers(e,z,c))return;this.applyEventModifiers(z,c);let V=this.getScope(e),fe=new Map;if(i&&i.length>0){let E=i[0];E&&(fe.set(E,V.getPath(E)),V.setPath(E,z))}let de=!1;try{await this.executeBlock(s,V,e,a)}catch(E){de=!0,this.emitError(e,E)}finally{for(let[E,ve]of fe.entries())V.setPath(E,ve)}de||this.evaluate(e)},d=this.getListenerOptions(c);h.addEventListener(o.event,f,d);let g=this.behaviorListeners.get(e)??new Map,ue=g.get(n)??[];ue.push({target:h,event:o.event,handler:f,options:d}),g.set(n,ue),this.behaviorListeners.set(e,g)}attachGetHandler(e,t=!1){let s=async()=>{let r=this.getBindings.get(e);if(r)try{await ye(e,r,this.getScope(e),i=>{r.trusted&&this.handleTrustedHtml(i)})}catch(i){console.warn("vsn:getError",i),e.dispatchEvent(new CustomEvent("vsn:getError",{detail:{error:i},bubbles:!0}))}};e.addEventListener("click",r=>{r.target===e&&s()}),t&&Promise.resolve().then(s)}applyEventModifiers(e,t){if(!(!e||!t||t.length===0))for(let s of t)s==="prevent"?e.preventDefault():s==="stop"&&e.stopPropagation()}getListenerOptions(e){if(!e||e.length===0)return;let t={};return e.includes("once")&&(t.once=!0),e.includes("passive")&&(t.passive=!0),e.includes("capture")&&(t.capture=!0),Object.keys(t).length>0?t:void 0}async execute(e,t,s,r){let i=this.codeCache.get(e);i||(i=A.parseInline(e),this.codeCache.set(e,i));let n={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await i.evaluate(n)}async executeBlock(e,t,s,r){let i={scope:t,rootScope:r,globals:this.globals,...s?{element:s}:{}};await e.evaluate(i)}async safeExecute(e,t,s,r){try{await this.execute(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}async safeExecuteBlock(e,t,s,r){try{await this.executeBlock(e,t,s,r)}catch(i){s&&this.emitError(s,i)}}collectBehavior(e,t,s){let r=t?`${t} ${e.selector.selectorText}`:e.selector.selectorText,i=s??t??e.selector.selectorText,n=this.getCachedBehavior(e);this.behaviorRegistry.push({id:this.behaviorId+=1,selector:r,rootSelector:i,specificity:this.computeSpecificity(r),order:this.behaviorRegistry.length,...n}),this.collectNestedBehaviors(e.body,r,i)}collectNestedBehaviors(e,t,s){for(let r of e.statements){if(r instanceof C){this.collectBehavior(r,t,s);continue}if(r instanceof b){this.collectNestedBehaviors(r.body,t,s);continue}r instanceof y&&this.collectNestedBehaviors(r,t,s)}}computeSpecificity(e){let t=e.match(/#[\w-]+/g)?.length??0,s=e.match(/\.[\w-]+/g)?.length??0,r=e.match(/\[[^\]]+\]/g)?.length??0,i=e.match(/:[\w-]+/g)?.length??0,n=e.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/g)?.length??0;return t*100+(s+r+i)*10+n}getBehaviorRootScope(e,t){let s=e.closest(t.rootSelector)??e;return this.getScope(s)}getImportantKey(e){if(e.target instanceof m)return`state:${e.target.name}`;if(e.target instanceof x)return`${e.target.kind}:${e.target.name}`}isImportant(e,t){let s=this.importantFlags.get(e);return s?s.has(t):!1}markImportant(e,t){let s=this.importantFlags.get(e)??new Set;s.add(t),this.importantFlags.set(e,s)}extractLifecycle(e){let t,s;for(let r of e.statements)r instanceof y&&(r.type==="Construct"?t=r:r.type==="Destruct"&&(s=r));return{...t?{construct:t}:{},...s?{destruct:s}:{}}}extractOnBlocks(e){let t=[];for(let s of e.statements)s instanceof b&&t.push({event:s.eventName,body:s.body,modifiers:s.modifiers,args:s.args});return t}extractDeclarations(e){let t=[];for(let s of e.statements)s instanceof F&&t.push(s);return t}extractFunctionDeclarations(e){let t=[];for(let s of e.statements){if(s instanceof L){t.push({name:s.name,params:s.params,body:s.body});continue}s instanceof B&&s.target instanceof m&&s.value instanceof S&&t.push({name:s.target.name,params:s.value.params,body:s.value.body})}return t}getCachedBehavior(e){let t=this.hashBehavior(e),s=this.behaviorCache.get(t);if(s)return s;let r=this.extractLifecycle(e.body),i={onBlocks:this.extractOnBlocks(e.body),declarations:this.extractDeclarations(e.body),functions:this.extractFunctionDeclarations(e.body),...r};return this.behaviorCache.set(t,i),i}hashBehavior(e){let t=this.normalizeNode(e),s=JSON.stringify(t);return this.hashString(s)}normalizeNode(e){if(!e||typeof e!="object")return e;let t=e.type??"Unknown";return t==="Behavior"?{type:t,selector:e.selector?.selectorText??"",body:this.normalizeNode(e.body)}:t==="Selector"?{type:t,selectorText:e.selectorText??""}:t==="Block"||t==="Construct"||t==="Destruct"?{type:t,statements:Array.isArray(e.statements)?e.statements.map(s=>this.normalizeNode(s)):[]}:t==="OnBlock"?{type:t,eventName:e.eventName??"",args:Array.isArray(e.args)?e.args:[],body:this.normalizeNode(e.body)}:t==="Declaration"?{type:t,target:this.normalizeNode(e.target),operator:e.operator??"",value:this.normalizeNode(e.value),flags:e.flags??{},flagArgs:e.flagArgs??{}}:t==="Assignment"?{type:t,target:this.normalizeNode(e.target),value:this.normalizeNode(e.value)}:t==="StateBlock"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>this.normalizeNode(s)):[]}:t==="StateEntry"?{type:t,name:e.name??"",value:this.normalizeNode(e.value),important:!!e.important}:t==="FunctionDeclaration"?{type:t,name:e.name??"",params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="FunctionExpression"?{type:t,params:Array.isArray(e.params)?e.params.map(s=>({name:s?.name??"",rest:!!s?.rest,defaultValue:this.normalizeNode(s?.defaultValue??null)})):[],body:this.normalizeNode(e.body),isAsync:!!e.isAsync}:t==="Return"?{type:t,value:this.normalizeNode(e.value??null)}:t==="If"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate??null)}:t==="While"?{type:t,test:this.normalizeNode(e.test),body:this.normalizeNode(e.body)}:t==="For"?{type:t,init:this.normalizeNode(e.init??null),test:this.normalizeNode(e.test??null),update:this.normalizeNode(e.update??null),body:this.normalizeNode(e.body)}:t==="Try"?{type:t,errorName:e.errorName??"",body:this.normalizeNode(e.body),handler:this.normalizeNode(e.handler)}:t==="Identifier"?{type:t,name:e.name??""}:t==="Literal"?{type:t,value:e.value}:t==="TemplateExpression"?{type:t,parts:Array.isArray(e.parts)?e.parts.map(s=>this.normalizeNode(s)):[]}:t==="UnaryExpression"?{type:t,operator:e.operator??"",argument:this.normalizeNode(e.argument)}:t==="BinaryExpression"?{type:t,operator:e.operator??"",left:this.normalizeNode(e.left),right:this.normalizeNode(e.right)}:t==="TernaryExpression"?{type:t,test:this.normalizeNode(e.test),consequent:this.normalizeNode(e.consequent),alternate:this.normalizeNode(e.alternate)}:t==="MemberExpression"?{type:t,target:this.normalizeNode(e.target),property:e.property??"",optional:!!e.optional}:t==="CallExpression"?{type:t,callee:this.normalizeNode(e.callee),args:Array.isArray(e.args)?e.args.map(s=>this.normalizeNode(s)):[]}:t==="AwaitExpression"?{type:t,argument:this.normalizeNode(e.argument)}:t==="Directive"?{type:t,kind:e.kind??"",name:e.name??""}:t==="Query"?{type:t,direction:e.direction??"",selector:e.selector??""}:t==="ArrayExpression"?{type:t,elements:Array.isArray(e.elements)?e.elements.map(s=>this.normalizeNode(s)):[]}:t==="ObjectExpression"?{type:t,entries:Array.isArray(e.entries)?e.entries.map(s=>({key:s?.key??"",computed:!!s?.computed,keyExpr:s?.keyExpr?this.normalizeNode(s.keyExpr):null,value:this.normalizeNode(s?.value)})):[]}:t==="IndexExpression"?{type:t,target:this.normalizeNode(e.target),index:this.normalizeNode(e.index)}:{type:t}}hashString(e){let t=5381;for(let s=0;s<e.length;s+=1)t=(t<<5)+t+e.charCodeAt(s),t|=0;return(t>>>0).toString(16)}applyBehaviorFunctions(e,t,s,r){for(let i of s)this.applyBehaviorFunction(e,t,i,r)}applyBehaviorFunction(e,t,s,r){let i=t.getPath(s.name);if(i!==void 0&&typeof i!="function")throw new Error(`Cannot override non-function '${s.name}' with a function`);let n=async(...a)=>{let o=t.createChild?t.createChild():t,c={scope:o,rootScope:r??o,globals:this.globals,element:e,returnValue:void 0,returning:!1},h=new Map;return await this.applyFunctionParams(o,s.params,h,c,a),await s.body.evaluate(c),o===t&&this.restoreFunctionParams(o,s.params,h),c.returnValue};t.setPath(s.name,n)}async applyFunctionParams(e,t,s,r,i){let n=0;for(let a of t){let o=a.name;if(!o)continue;if(s.set(o,e.getPath(o)),a.rest){e.setPath(`self.${o}`,i.slice(n)),n=i.length;continue}let c=i[n];c===void 0&&a.defaultValue&&(c=await a.defaultValue.evaluate(r)),e.setPath(`self.${o}`,c),n+=1}}restoreFunctionParams(e,t,s){for(let r of t){let i=r.name;i&&e.setPath(i,s.get(i))}}async applyBehaviorDeclarations(e,t,s,r){for(let i of s)await this.applyBehaviorDeclaration(e,t,i,r)}async applyBehaviorDeclaration(e,t,s,r){let i={scope:t,rootScope:r,element:e},n=s.operator,a=s.flags.debounce?s.flagArgs.debounce??200:void 0,o=this.getImportantKey(s);if(!s.flags.important&&o&&this.isImportant(e,o)||o&&this.isInlineDeclaration(e,o))return;if(this.applyCustomFlags(e,t,s),s.target instanceof m){let d=await s.value.evaluate(i);t.setPath(s.target.name,d),s.flags.important&&o&&this.markImportant(e,o);return}if(!(s.target instanceof x))return;let c=s.target,h=s.value instanceof m?s.value.name:void 0;if(n===":>"){h&&this.applyDirectiveToScope(e,c,h,t,a,r),s.flags.important&&o&&this.markImportant(e,o);return}if(n===":="&&h&&this.applyDirectiveToScope(e,c,h,t,a,r),!h){let d=await s.value.evaluate(i);this.setDirectiveValue(e,c,d,s.flags.trusted),(n===":<"||n===":=")&&this.applyDirectiveFromExpression(e,c,s.value,t,s.flags.trusted,a,r),s.flags.important&&o&&this.markImportant(e,o);return}let f=n===":<"||n===":=";this.applyDirectiveFromScope(e,c,h,t,s.flags.trusted,a,f,r),s.flags.important&&o&&this.markImportant(e,o)}applyCustomFlags(e,t,s){if(this.flagHandlers.size!==0)for(let[r,i]of this.flagHandlers)s.flags[r]&&i.onApply?.({name:r,args:s.flagArgs[r],element:e,scope:t,declaration:s})}applyDirectiveFromScope(e,t,s,r,i,n,a=!0,o){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let h=()=>{let f=s.startsWith("root.")&&o,d=f?o:r,g=f?`self.${s.slice(5)}`:s;W(e,g,d,!!i)};if(h(),i&&this.handleTrustedHtml(e),a){let f=s.startsWith("root.")&&o,d=f?o:r,g=f?s.slice(5):s;this.watchWithDebounce(d,g,h,n)}return}let c=()=>{let h=s.startsWith("root.")&&o,f=h?o:r,d=h?`self.${s.slice(5)}`:s,g=f.get(d);g!=null&&this.setDirectiveValue(e,t,g,i)};if(c(),a){let h=s.startsWith("root.")&&o,f=h?o:r,d=h?s.slice(5):s;this.watchWithDebounce(f,d,c,n)}}applyDirectiveFromExpression(e,t,s,r,i,n,a){let o=async()=>{let c={scope:r,rootScope:a,element:e},h=await s.evaluate(c);this.setDirectiveValue(e,t,h,i)};o(),this.watchAllScopes(r,()=>{o()},n)}applyDirectiveToScope(e,t,s,r,i,n){let a=s.startsWith("root.")&&n,o=a?n:r,c=a?`self.${s.slice(5)}`:s;if(t.kind==="attr"&&t.name==="value"){this.applyValueBindingToScope(e,c,i,o);return}if(t.kind==="attr"&&t.name==="checked"){this.applyCheckedBindingToScope(e,c,i,o);return}let h=this.getDirectiveValue(e,t);h!=null&&o.set(c,h)}applyCheckedBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement))return;let i=()=>{(r??this.getScope(e)).set(t,e.checked)},n=s?P(i,s):i;n(),e.addEventListener("change",n),e.addEventListener("input",n)}applyValueBindingToScope(e,t,s,r){if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement))return;let i=()=>{let a=r??this.getScope(e);oe(e,t,a)},n=s?P(i,s):i;n(),e.addEventListener("input",n),e.addEventListener("change",n)}setDirectiveValue(e,t,s,r){if(t.kind==="attr"&&t.name==="html"&&e instanceof HTMLElement){let i=s==null?"":String(s);e.innerHTML=r?i:i.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),r&&this.handleTrustedHtml(e);return}if(t.kind==="attr"){if(t.name==="value"){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){e.value=s==null?"":String(s),e.setAttribute("value",e.value);return}if(e instanceof HTMLSelectElement){e.value=s==null?"":String(s);return}}if(t.name==="checked"&&e instanceof HTMLInputElement){let i=s===!0||s==="true"||s===1||s==="1";e.checked=i,i?e.setAttribute("checked",""):e.removeAttribute("checked");return}e.setAttribute(t.name,s==null?"":String(s));return}t.kind==="style"&&e instanceof HTMLElement&&e.style.setProperty(t.name,s==null?"":String(s))}getDirectiveValue(e,t){if(t.kind==="attr")return t.name==="value"&&(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)?e.value:t.name==="checked"&&e instanceof HTMLInputElement?e.checked:e.getAttribute(t.name)??void 0;if(t.kind==="style"&&e instanceof HTMLElement)return e.style.getPropertyValue(t.name)??void 0}handleTrustedHtml(e){let t=Array.from(e.querySelectorAll('script[type="text/vsn"]'));if(t.length===0)return;let s=t.map(r=>r.textContent??"").join(`
7
+ `);s.trim()&&(this.registerBehaviors(s),this.applyBehaviors(e))}registerDefaultAttributeHandlers(){this.registerAttributeHandler({id:"vsn-bind",match:e=>e.startsWith("vsn-bind"),handle:(e,t,s,r)=>{let i=this.parseBindDirection(t);this.bindBindings.set(e,{expr:s,direction:i}),(i==="to"||i==="both")&&this.markInlineDeclaration(e,`state:${s}`),(i==="to"||i==="both")&&(oe(e,s,r),this.attachBindInputHandler(e,s)),(i==="from"||i==="both")&&this.watch(r,s,()=>ce(e,s,r))}}),this.registerAttributeHandler({id:"vsn-if",match:e=>e==="vsn-if",handle:(e,t,s,r)=>{this.ifBindings.set(e,s),e instanceof HTMLElement&&le(e,s,r),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-show",match:e=>e==="vsn-show",handle:(e,t,s,r)=>{this.showBindings.set(e,s),e instanceof HTMLElement&&he(e,s,r),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-html",match:e=>e.startsWith("vsn-html"),handle:(e,t,s,r)=>{let i=t.includes("!trusted");this.htmlBindings.set(e,{expr:s,trusted:i}),this.markInlineDeclaration(e,"attr:html"),e instanceof HTMLElement&&(W(e,s,r,i),i&&this.handleTrustedHtml(e)),this.watch(r,s,()=>this.evaluate(e))}}),this.registerAttributeHandler({id:"vsn-each",match:e=>e==="vsn-each",handle:(e,t,s,r)=>{let i=this.parseEachExpression(s);i&&(this.eachBindings.set(e,{...i,rendered:[]}),this.renderEach(e),this.watch(r,i.listExpr,()=>this.renderEach(e)))}}),this.registerAttributeHandler({id:"vsn-get",match:e=>e.startsWith("vsn-get"),handle:(e,t)=>{let s=t.includes("!trusted"),r=t.includes("!load"),i=e.getAttribute(t)??"",n=e.getAttribute("vsn-target")??void 0,a=e.getAttribute("vsn-swap")??"inner",o={url:i,swap:a,trusted:s,...n?{targetSelector:n}:{}};this.getBindings.set(e,o),this.attachGetHandler(e,r)}}),this.registerAttributeHandler({id:"vsn-construct",match:e=>e==="vsn-construct",handle:(e,t,s)=>{this.setLifecycle(e,{construct:s})}}),this.registerAttributeHandler({id:"vsn-destruct",match:e=>e==="vsn-destruct",handle:(e,t,s)=>{this.setLifecycle(e,{destruct:s})}}),this.registerAttributeHandler({id:"vsn-on",match:e=>e.startsWith("vsn-on:"),handle:(e,t,s)=>{let r=this.parseOnAttribute(t,s);r&&this.attachOnHandler(e,r)}})}};var Be="0.1.0";function yt(p){return new A(p).parseProgram()}function Se(p=document){if(typeof document>"u")return null;let e=new q,t=typeof performance<"u"&&performance.now?performance.now():Date.now(),s=()=>{let r=p instanceof Document?p.body:p;if(r){let i=Array.from(document.querySelectorAll('script[type="text/vsn"]')).map(o=>o.textContent??"").join(`
8
+ `);i.trim()&&e.registerBehaviors(i),e.mount(r);let n=typeof performance<"u"&&performance.now?performance.now():Date.now(),a=Math.round(n-t);console.log(`Took ${a}ms to start up VSN.js. https://www.vsnjs.com/ v${Be}`)}};return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s,{once:!0}):s(),e}typeof document<"u"&&document.querySelector("script[auto-mount]")&&Se();export{se as ArrayExpression,H as ArrayPattern,B as AssignmentNode,U as AwaitExpression,u as BaseNode,C as BehaviorNode,v as BinaryExpression,y as BlockNode,w as CallExpression,F as DeclarationNode,x as DirectiveExpression,q as Engine,Y as ForNode,L as FunctionDeclarationNode,S as FunctionExpression,m as IdentifierExpression,Z as IfNode,ie as IndexExpression,T as Lexer,k as LiteralExpression,N as MemberExpression,re as ObjectExpression,I as ObjectPattern,b as OnBlockNode,A as Parser,j as ProgramNode,ne as QueryExpression,M as RestElement,D as ReturnNode,K as SelectorNode,R as SpreadElement,_ as StateBlockNode,Q as StateEntryNode,ee as TemplateExpression,te as TernaryExpression,me as TokenType,X as TryNode,O as UnaryExpression,G as UseNode,Be as VERSION,J as WhileNode,Se as autoMount,yt as parseCFS};
9
9
  //# sourceMappingURL=index.min.js.map