@hyperfixi/core 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +8 -11
  2. package/dist/bundle-generator/index.js +25 -4
  3. package/dist/bundle-generator/index.mjs +25 -4
  4. package/dist/chunks/{bridge-BlRqsZT4.js → bridge-Clbh_xAj.js} +2 -2
  5. package/dist/chunks/browser-modular-DIOxQqhV.js +2 -0
  6. package/dist/chunks/{index-BDYQHwCF.js → index-DcxoRUBe.js} +2 -2
  7. package/dist/commands/index.js +22 -3
  8. package/dist/commands/index.mjs +22 -3
  9. package/dist/hyperfixi-classic-i18n.js +1 -1
  10. package/dist/hyperfixi-hx.js +1 -1
  11. package/dist/hyperfixi-hybrid-complete.js +1 -1
  12. package/dist/hyperfixi-minimal.js +1 -1
  13. package/dist/hyperfixi-multilingual.js +1 -1
  14. package/dist/hyperfixi-standard.js +1 -1
  15. package/dist/hyperfixi.js +1 -1
  16. package/dist/hyperfixi.mjs +1 -1
  17. package/dist/index.js +22 -3
  18. package/dist/index.min.js +1 -1
  19. package/dist/index.mjs +22 -3
  20. package/dist/lokascript-browser-classic-i18n.js +1 -1
  21. package/dist/lokascript-browser-minimal.js +1 -1
  22. package/dist/lokascript-browser-standard.js +1 -1
  23. package/dist/lokascript-browser.js +1 -1
  24. package/dist/lokascript-hybrid-complete.js +1 -1
  25. package/dist/lokascript-hybrid-hx.js +1 -1
  26. package/dist/lokascript-multilingual.js +1 -1
  27. package/dist/parser/hybrid/index.js +7 -0
  28. package/dist/parser/hybrid/index.mjs +7 -0
  29. package/dist/parser/hybrid/parser-core.js +7 -0
  30. package/dist/parser/hybrid/parser-core.mjs +7 -0
  31. package/dist/parser/hybrid/tokenizer.js +7 -0
  32. package/dist/parser/hybrid/tokenizer.mjs +7 -0
  33. package/dist/parser/hybrid-parser.js +7 -0
  34. package/dist/parser/hybrid-parser.mjs +7 -0
  35. package/package.json +1 -1
  36. package/dist/chunks/browser-modular-AbV0Ql4i.js +0 -2
@@ -1,2 +1,2 @@
1
- var hyperfixi=function(){"use strict";const t="then",e="else",r="end",n="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",v="behavior",g="global",b="the",E="start",w=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),A="at end of",S=["into","before","after","at",k,A,"at the start of","at the end of"],C=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),N=t=>w.has(t.toLowerCase()),T=t=>x.has(t.toLowerCase()),O=t=>C.has(t.toLowerCase()),L=t=>$.has(t.toLowerCase()),$=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),R=new Set(["me","it","you","result","my","its","your"]),I=new Set(["and","or","not","no"]),j=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),M=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),D=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var P;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(P||(P={}));const V=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function F(t,e=1){const r=t.position+e;return t.input.length>r?t.input[r]:""}function _(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function q(t){const e=t.input,r=e.length;for(;r>t.position;){const r=e[t.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;_(t)}}function H(t,e,r,n,s){const i=n??t.position-r.length,o=t.position;let a=t.column-r.length;if(void 0!==n){a=1;let e=-1;for(let r=0;n>r;r++)"\n"!==t.input[r]&&"\r"!==t.input[r]||(e=r);a=n-e}const c={kind:e,value:r,start:i,end:o,line:U(t,i),column:a};t.tokens.push(c)}function U(t,e){let r=1;for(let n=0;e>n&&t.input.length>n;n++){const e=t.input[n];"\n"===e?r++:"\r"===e&&(r++,t.input.length>n+1&&"\n"===t.input[n+1]&&n++)}return r}function z(t){const e=t.position;let r="";for(_(t),_(t);t.input.length>t.position&&"\n"!==t.input[t.position];)r+=_(t);H(t,P.COMMENT,"--"+r,e)}function W(t){const e=t.position,r=_(t);let n=r;for(;t.input.length>t.position;){const e=_(t);if(n+=e,e===r)break;"\\"===e&&t.input.length>t.position&&(n+=_(t))}H(t,P.STRING,n,e)}function J(t){const e=t.position;_(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){_(t);break}if("\\"===e){if(_(t),t.input.length>t.position){const e=_(t);switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=e}}}else r+=_(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-r.length}`);H(t,P.TEMPLATE,r,e)}function Z(t){const e=t.position;let r=_(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(r+=_(t);t.input.length>t.position;){const e=t.input[t.position];if(r+=_(t),"}"===e)break}H(t,P.SELECTOR,r,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if(!rt(e)&&"-"!==e&&"_"!==e&&":"!==e)break;r+=_(t)}H(t,P.SELECTOR,r,e)}}function G(t){const e=t.position;let r="";for(r+=_(t);t.input.length-1>t.position;){const e=t.input[t.position],n=t.input[t.position+1];if(r+=_(t),"/"===e&&">"===n){r+=_(t);break}}H(t,P.SELECTOR,r,e)}function X(t){const e=t.position;let r=_(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!rt(e)&&"_"!==e&&"-"!==e)break;r+=_(t)}H(t,P.SYMBOL,r,e)}function Y(t){const e=t.position;let r="";const n=t.input[t.position];if(("'"===n||"'"===n)&&"s"===F(t,1))return r="'s",_(t),_(t),void H(t,P.OPERATOR,r,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(r=i,_(t),_(t),_(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,_(t),_(t)):r=_(t),H(t,P.OPERATOR,r,e)}function K(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position&&"."===r[t.position]&&(t.position+1>=n||"."!==r[t.position+1]))for(s+=_(t);n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position){const e=r[t.position];if("e"===e||"E"===e){const e=n>t.position+1?r[t.position+1]:"",i=n>t.position+2?r[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=_(t),"+"!==r[t.position]&&"-"!==r[t.position]||(s+=_(t));n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}}}const i=t.position;let o="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=_(t)}B.has(o)?H(t,P.TIME,s+o,e):(t.position=i,H(t,P.NUMBER,s,e))}function Q(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=_(t)}const i=function(t,e,r){const n=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return!1;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===P.IDENTIFIER||i.kind===P.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}q(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=_(t)}if(o){const e=o.toLowerCase(),s=`${n} ${e}`,i=function(t,e,r,n){const s=e.toLowerCase(),i=r.toLowerCase();if("at"===s){const e=t.position;if("the"===i){q(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}const s=r.toLowerCase();if("start"===s||"end"===s){q(t);let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;e+=_(t)}if("of"===e.toLowerCase())return H(t,P.IDENTIFIER,`at the ${s} of`,n),!0}return t.position=e,!1}if("start"===i||"end"===i){q(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}return"of"===r.toLowerCase()?(H(t,P.IDENTIFIER,`at ${i} of`,n),!0):(t.position=e,!1)}}return!1}(t,n,e,r);if(i)return!0;const a=function(t,e,r){const n=t.position;let s=`${e} ${r}`,i=t.position;const o=[e,r];for(;8>o.length&&(q(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;e+=_(t)}if(!e)break;o.push(e.toLowerCase());const r=o.join(" ");j.has(r)&&(s=r,i=t.position)}return j.has(s)&&s!==`${e} ${r}`?(t.position=i,s):(t.position=n,null)}(t,n,e);if(a)return H(t,P.OPERATOR,a,r),!0;if(j.has(s))return H(t,P.OPERATOR,s,r),!0}return j.has(n)?(t.position=s,H(t,P.OPERATOR,e,r),!0):(t.position=s,!1)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||I.has(e)||V.has(t)||V.has(e)||j.has(e)?P.OPERATOR:P.IDENTIFIER}(s);H(t,o,s,e)}function tt(t){const e=t.position,r=t.input,n=r.length;_(t);let s="$";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=_(t)}H(t,P.IDENTIFIER,s,e)}function et(t){return/[a-zA-Z]/.test(t)}function rt(t){return/[a-zA-Z0-9]/.test(t)}function nt(t){let e=t.position+1,r=!1;for(;t.input.length>e;){const n=t.input[e];if("/"===n&&t.input.length>e+1&&">"===t.input[e+1])return r;if(rt(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=!0,e++;else{if(" "!==n&&"\t"!==n)return!1;e++}if(e-t.position>50)return!1}return!1}function st(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const it=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),ot=it,at=it,ct=it,lt=it,ut=it,ht=(...t)=>{ot&&console.log("🔧",...t)},ft=(...t)=>{at&&console.log("🎯",...t)},dt=(...t)=>{ct&&console.log("📝",...t)},pt=(...t)=>{lt&&console.log("🔍",...t)},mt=(...t)=>{ut&&console.log("🚀",...t)};let yt=!1,vt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(yt=!0,vt=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let gt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class bt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(bt.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const r=t.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)||!!/\*[a-zA-Z]/.test(t)}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const n=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,o=!i&&n.confidence>0;if(yt){const e={};if(n.command?.roles)for(const[t,r]of n.command.roles)e[t]=r.value;const a={input:t.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:n.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(t){if(!yt)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",r=Math.round(100*t.confidence),n=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),vt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});vt.dispatchEvent(e)}}(a),r=a,gt.totalParses++,r.semanticSuccess?gt.semanticSuccesses++:r.fallbackTriggered?gt.semanticFallbacks++:gt.traditionalParses++,gt.confidenceHistory.push(r.confidence),gt.confidenceHistory.length>100&&gt.confidenceHistory.shift(),gt.averageConfidence=gt.confidenceHistory.reduce((t,e)=>t+e,0)/gt.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:!1,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var r}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const r=[],n={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":r.push(i);break;case"destination":"put"===e.name?n.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?n.to=i:n.on=i;break;case"source":"fetch"===e.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[t]=i}}return{type:"command",name:e.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],r={},n=t.roles.get("loopType");n&&e.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(n?n.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(r.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],r=t.roles.get("destination");if(r)if("property-path"===r.type){const t=r;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(r));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=t.roles.get("patient");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],r=t.roles.get("condition");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:t.name,args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const r=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},n=()=>{r();const n=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(n,e)},s=()=>{const n=[];if(e++,r(),")"!==t[e])for(n.push(i()),r();","===t[e];)e++,r(),n.push(i()),r();return")"===t[e]&&e++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){r();const i=t[e];if("."===i){e++;const t=n();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function Et(t){return t.kind===P.IDENTIFIER&&w.has(t.value.toLowerCase())}function wt(t){return t.kind===P.IDENTIFIER&&D.has(t.value.toLowerCase())}function xt(t){return t.kind===P.IDENTIFIER&&M.has(t.value.toLowerCase())}function kt(t){return t.kind===P.IDENTIFIER&&R.has(t.value.toLowerCase())}function At(t){return j.has(t.value.toLowerCase())}function St(t){return t.kind===P.IDENTIFIER}function Ct(t){return t.kind===P.SELECTOR}function Nt(t){return t.kind===P.SELECTOR&&!t.value.startsWith("<")}function Tt(t){return t.kind===P.STRING||t.kind===P.NUMBER||t.kind===P.TEMPLATE}function Ot(t){return t.kind===P.IDENTIFIER}function Lt(t){return t.kind===P.TIME}function $t(t){return t.kind===P.SYMBOL}function Rt(t){return t.kind===P.COMMENT}function It(t){if(t.kind!==P.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(w.has(e)||D.has(e)||M.has(e)||R.has(e))}function jt(t){return t.kind===P.STRING}function Mt(t){return t.kind===P.NUMBER}function Dt(t){if(t.kind===P.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function Pt(t){return t.kind===P.TEMPLATE}function Vt(t){return t.kind===P.SELECTOR&&t.value.startsWith("<")}function Bt(t){return t.kind===P.SELECTOR&&t.value.startsWith("#")}function Ft(t){return t.kind===P.SELECTOR&&t.value.startsWith(".")}function _t(t){return t.kind===P.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function qt(t){if(t.kind!==P.OPERATOR)return!1;const e=t.value.toLowerCase();return!I.has(e)&&!j.has(e)}function Ht(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function Ut(t,e,r){return{type:"literal",value:t,raw:e,start:r.start,end:r.end,line:r.line,column:r.column}}function zt(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Wt(t,e,r,n){return{type:"binaryExpression",operator:t,left:e,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function Jt(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Zt(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Gt(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Xt(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Yt(t,e,r){return{type:"propertyOfExpression",property:t,target:e,start:r.start,end:r.end,line:r.line,column:r.column}}function Kt(t,e,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...r&&{source:r}}],start:t.start,end:t.end,line:t.line,column:t.column}}bt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Qt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function te(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const ee=[t,n,e,r];function re(t,e=[]){if(t.isAtEnd())return!0;for(const e of ee)if(t.check(e))return!0;for(const r of e)if(t.check(r))return!0;return!!t.checkIsCommand()}function ne(t,e=[]){if(!re(t,e))return t.parseExpression()}function se(t,e,r){return!!t.check(e)&&(t.advance(),r.push(t.createIdentifier(e)),!0)}function ie(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function oe(t,e){return!!t.check(e)&&(t.advance(),!0)}class ae{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new ae(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new ae(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new ae(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=!0){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new ae(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ce(t,e){const r=[];let n="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(n=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),n+=":",t.checkIdentifierLike()&&(n+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const r=t.savePosition();let n;if(t.checkIdentifierLike()){const e=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=e):t.restorePosition(r)}const s=t.parseExpression();if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:s}],start:s.start,end:s.end,line:s.line,column:s.column}:s),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),r.push({type:"functionCall",name:n,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else r.push({type:"string",value:n,start:s,end:t.getPosition().end,line:i,column:o})}const a=[...r];if(t.check("on")||t.check("to")){const e=t.advance().value;for(a.push(t.createIdentifier(e));!re(t);)a.push(t.parsePrimary())}return ae.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function le(t,e){const r=[];if(t.check(b)){const e=t.advance();if(r.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();r.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ue(n,s){const i=[];let o=!1;const a=n.savePosition();for(let e=0;500>e&&!n.isAtEnd();e++){const e=n.peek();if(e.value===t){o=!0;break}if(e.value===r||e.value===v||"def"===e.value||e.value===m)break;n.advance()}n.restorePosition(a);let c=!1;if(!o){const t=n.savePosition(),i=s.line,o=100;for(;!n.isAtEnd()&&o>n.current-t;){const t=n.peek(),s=t.value?.toLowerCase();if(s===v||"def"===s||s===m)break;if(s===e||s===r){t.line===i&&(c=!0);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==t.line&&t.line!==i){c=!0;break}n.advance()}n.restorePosition(t)}const l=o||c;let u;if(l)u=n.parseExpression();else{const e=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(t)&&r>i;){const t=n.savePosition();e.push(n.parseLogicalAnd()),n.savePosition()===t&&n.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&n.advance();const t=[];for(;!n.isAtEnd()&&!n.check(e)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}if(0===t.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(Jt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let a=!1;if(n.check(e))if(n.advance(),n.check("if")){const t=n.peek();n.advance();const e=ue(n,t);i.push(Jt([e],{start:t.start,end:n.getPosition().end,line:t.line,column:t.column})),a=!0}else{const t=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}i.push(Jt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}a||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const t=n.parseCommand();i.push(Jt([t],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return ae.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function he(t,e){const r=[],n={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(r.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();r.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();n.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function fe(t,e){const r=[],n=ne(t,[f]);n&&r.push(n),se(t,f,r);const s=ne(t);return s&&r.push(s),ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function de(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=ne(t,[n]);i&&r.push(i),se(t,n,r);const o=ne(t,[f,m,s]);if(o&&r.push(o),ie(t,[f,m],r)){const e=ne(t);e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=ne(t,[f,m]);if(i&&r.push(i),ie(t,[f,m],r)){const e=ne(t);e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function pe(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!S.includes(s.value))return t.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=A:"at"===i&&(t.check(E)||t.check(b)?(oe(t,b),t.check(E)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(r)&&(t.advance(),t.check(p)&&(t.advance(),i=A)));const a=t.parseExpression();return a?ae.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const me=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function ye(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(g)&&!t.check("local"))return null;const e=t.advance(),r=t.advance();return{type:"identifier",name:r.value,scope:e.value,start:e.start,end:r.end}}(s)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const r=t.parseExpression();if(!r)return t.restorePosition(e),null;if("binaryExpression"===r.type&&r.operator===p){const t=r.left,e=r.right;return Yt(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(h)?r:(t.restorePosition(e),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(n)||s.check(e)||s.check(r));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],r=i[3];return{expression:Yt(zt(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(h)),l&&u.push(l),ae.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function ve(t,e){const r=[];for(;!re(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ge(t){if(t.isAtEnd())return!0;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||re(t)}function be(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Ee(t){const e=[],r=t.getPosition();do{if(!t.checkIdentifierLike())break;const r=t.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:n,value:s})}while(t.match(",")&&!t.isAtEnd());const n=t.getPosition();return{type:"objectLiteral",properties:e,start:r.start,end:n.end,line:r.line,column:r.column}}const we=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),xe=new Set([")","]","}",","]);function ke(...t){const e=new Map;for(const r of t)for(const[t,n]of r){const r=e.get(t);e.set(t,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}return e}function Ae(t,e){return{infix:{bp:[t,t+1],handler:e??((e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t+1),start:e.start}))}}}function Se(t,e){return{infix:{bp:[t+1,t],handler:(e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t),start:e.start})}}}function Ce(t,e){return{prefix:{bp:t,handler:e??((e,r)=>({type:"unaryExpression",operator:e.value,operand:r.parseExpr(t),start:e.start}))}}}const Ne=new Map([["or",Ae(10)],["||",Ae(10)],["and",Ae(20)],["&&",Ae(20)],["==",Ae(30)],["!=",Ae(30)],["<",Ae(30)],[">",Ae(30)],["<=",Ae(30)],[">=",Ae(30)],["is",Ae(30)],["matches",Ae(30)],["contains",Ae(30)],["+",{...Ae(40),...Ce(80)}],["-",{...Ae(40),...Ce(80)}],["*",Ae(50)],["/",Ae(50)],["%",Ae(50)],["mod",Ae(50)],["^",Se(60)],["**",Se(60)],["as",Ae(70,(t,e,r)=>({type:"asExpression",expression:t,targetType:r.parseExpr(71),start:t.start}))],["not",Ce(80)],["!",Ce(80)],["no",Ce(80)]]),Te=new Map([["first",Ce(85,(t,e)=>({type:"positionalExpression",position:"first",operand:e.parseExpr(85),start:t.start}))],["last",Ce(85,(t,e)=>({type:"positionalExpression",position:"last",operand:e.parseExpr(85),start:t.start}))]]),Oe=new Map([[".",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"propertyAccess",object:t,property:r.advance().value,start:t.start})}}],["?.",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"optionalChain",object:t,property:r.advance().value,start:t.start})}}],["'s",{infix:{bp:[95,96],handler:(t,e,r)=>({type:"possessiveExpression",object:t,property:r.advance().value,start:t.start})}}]]),Le=new Map([["===",Ae(30)],["!==",Ae(30)],["is not",Ae(30)],["is a",Ae(30)],["is an",Ae(30)],["is not a",Ae(30)],["is not an",Ae(30)],["is in",Ae(30)],["is not in",Ae(30)],["has",Ae(30)],["have",Ae(30)],["match",Ae(30)],["include",Ae(30)],["includes",Ae(30)],["equals",Ae(30)],["does not contain",Ae(30)],["does not include",Ae(30)],["in",Ae(30)],["of",Ae(30)],["really",Ae(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["some",Ce(80)]]),$e=new Map([["=",Se(5)]]);ke(Ne,Te,Oe);const Re=ke(Ne,Le,$e);class Ie{constructor(t,e,r){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new bt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=r||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors]),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:!1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def"))break;{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){dt("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];dt(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){dt(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(dt("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),r++,dt(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),dt(`✅ PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return dt("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};dt("✅ PARSER: No more event handlers, at end of input");break}}return dt(`✅ PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const t=this.parseExpression();return this.error?{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,r=this.prattCache.get(e);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=Ie.PRATT_TABLE.get(n.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek(),r=Ie.PRATT_TABLE.get(e.value);if(!r?.infix){if(we.has(e.value)||xe.has(e.value))break;break}const[n]=r.infix.bp;if(t>n)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch{}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ie.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return!e||we.has(e.value)||xe.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseAssignment(){let t=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const e=this.previous().value,r=this.parseAssignment();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.match("or");){const e=this.previous().value,r=this.parseLogicalAnd();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalAnd(){let t=this.parseEquality();for(;this.match("and");){const e=this.previous().value,r=this.parseEquality();t=this.createBinaryExpression(e,t,r)}return t}parseEquality(){let t=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const e=this.previous().value;if(Ie.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,!1);continue}const r=this.parseComparison();t=this.createBinaryExpression(e,t,r)}return t}parseComparison(){let t=this.parseAddition();for(;this.matchComparisonOperator();){const e=this.previous().value;if(Ie.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,!1);continue}const r=this.parseAddition();t=this.createBinaryExpression(e,t,r)}return t}parseAddition(){let t=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const e=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${e}${this.peek().value}`),t;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseMultiplication();t=this.createBinaryExpression(e,t,r)}return t}parseMultiplication(){let t=this.parseUnary();for(;this.match("*","/","%","mod");){const e=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===e&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${e}${r}`),t}if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseUnary();t=this.createBinaryExpression(e,t,r)}return t}parseUnary(){if(this.match("not","no","exists","some","-","+")){const t=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression(t,e,!0)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression("does not exist",t,!0)}return this.parseImplicitBinary()}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):N(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):O(t)}createCommandFromIdentifier(t){const e=[],r=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:!1,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return T(t)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return pe(s,i);case"trigger":case"send":return ce(s,i);case"remove":return fe(s,i);case"toggle":return de(s,i);case"set":return ye(s,i);case"halt":return le(s,i);case"measure":return he(s,i);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start,i=function(t,e){const r=t.getInputSlice(e);if(!r)return e;let n=0;for(;r.length>n;){const t=r[n];if("'"!==t&&"’"!==t&&"‘"!==t)if('"'!==t)if("`"!==t)if("/"===t&&r.length>n+1&&"/"===r[n+1])for(n+=2;r.length>n&&"\n"!==r[n];)n++;else if("/"===t&&r.length>n+1&&"*"===r[n+1]){for(n+=2;r.length>n&&("*"!==r[n]||n+1>=r.length||"/"!==r[n+1]);)n++;n+=2}else{if(!("e"!==t&&"E"!==t||n+3>r.length||"end"!==r.slice(n,n+3).toLowerCase()||0!==n&&/[a-zA-Z0-9_]/.test(r[n-1])||r.length>n+3&&/[a-zA-Z0-9_]/.test(r[n+3])))return e+n;n++}else{for(n++;r.length>n&&"`"!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&'"'!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&r[n]!==t;)"\\"===r[n]&&n++,n++;n++}}return e+r.length}(t,s);for(;!t.isAtEnd()&&!t.check(r)&&t.peek().start<i;)t.advance();t.consume(r,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return ae.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(n))continue;if(s.check(t)||s.check(e)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return ae.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();me.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),r.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&r.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),r.push(t.createIdentifier("with"));const e=t.parseExpression();e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return ve(s,i)}}(this.getContext(),s)}parsePutCommand(t){return pe(this.getContext(),t)}parseSetCommand(t){return ye(this.getContext(),t)}parseHaltCommand(t){return le(this.getContext(),t)}parseMeasureCommand(t){return he(this.getContext(),t)}parseTriggerCommand(t){return ce(this.getContext(),t)}parseCommandListUntilEnd(){const t=[];for(dt("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){dt("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),n=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||n){dt(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(dt("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(dt("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(t){dt("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&dt("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){dt("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(dt("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)dt("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))dt("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){dt("📍 No separator and no command, breaking. Current token:",this.peek().value);break}dt("✅ Next token is a command, continuing without separator")}}if(dt('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw dt('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return dt('✅ Found "end", consuming it'),this.advance(),dt("✅ parseCommandListUntilEnd: Successfully parsed",t.length,"commands"),t}parseRepeatCommand(t){return function(t,e){const r=[];let n="forever",h=null,p=null,m=null,v=null,g=null,E=null;if(t.check(s)){t.advance(),n=s;const e=t.peek();St(e)&&(g=e.value,t.advance()),t.check(u)&&(t.advance(),v=t.parseExpression())}else if(t.check(u))t.advance(),n=s,g="it",v=t.parseExpression();else if(t.check(i))t.advance(),n=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),n=o,t.check(y)){t.advance(),n="until-event";const e=t.peek();if(dt("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!St(e)&&!xt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),dt("✅ Got event name:",h,"Next token:",t.peek().value),dt('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){dt('✅ Found "from", advancing...'),t.advance(),dt('📍 After consuming "from", current token:',t.peek().value),oe(t,b)&&dt('✅ Found "the", advancing...');const e=t.peek();dt("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),dt("✅ After parsePrimary, eventTarget:",p)}else dt('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),n=a):(E=t.parseExpression(),t.check(c)&&(t.advance(),n=c));let w=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),w=l)}else if(t.check(l)){t.advance();const e=t.peek();St(e)?(w=e.value,t.advance()):w=l}const x=t.parseCommandListUntilEnd();r.push({type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column});const k={start:e.start,end:e.end,line:e.line,column:e.column};return g&&r.push(Zt(g,k)),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push(Zt(h,k)),p&&r.push(p),w&&r.push(Zt(w,k)),r.push(Jt(x,{...k,end:k.end||0})),ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const r=[];let n=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!St(i))throw Error('Expected variable name after "for"');if(n=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();St(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return r.push(Zt(n,c)),r.push(s),o&&r.push(Zt(o,c)),r.push(Jt(a,{...c,end:c.end||0})),ae.from({...e,value:"repeat"}).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const r=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!re(t)){const n=t.parseExpression();return r.push(n),ae.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const n=[];do{const e=t.peek();if(!St(e))throw Error('Expected event name after "for"');const r=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!St(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(n.push({name:r,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),oe(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Xt(n.map(t=>Gt([{key:zt("name",i),value:Ut(t.name,`"${t.name}"`,i)},{key:zt("args",i),value:Xt(t.params.map(t=>Ut(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return ae.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const r=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=t.advance().value,s=t.previous();if(r.push(zt(n,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const n=[];for(;!t.isAtEnd()&&!t.check(")");){const e=t.savePosition();let r;if(t.checkIdentifierLike()){const n=t.peek().value;t.advance(),t.check(":")?(t.advance(),r=n):t.restorePosition(e)}const s=t.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),t.check(","))t.advance();else if(!t.check(")"))break}if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),n.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Gt(n.map(t=>({key:t.name?zt(t.name,s):Ut("_positional","_positional",s),value:t.value})),s))}}return ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const r=[],n={};let s=null;const i=t.peek();if(St(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const r=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);r&&(e+=r,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(n.to=o,t.check("over")){t.advance();const e=t.parsePrimary();n.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();n.with=e}return ae.from(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const r=[];if(t.match("{"))r.push(t.parseCSSObjectLiteral());else{const e=ne(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=ne(t);e&&r.push(e)}return ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return ue(this.getContext(),t)}parseRemoveCommand(t){return fe(this.getContext(),t)}parseToggleCommand(t){return de(this.getContext(),t)}parseRegularCommand(t){return ve(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifier("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,!0)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):e=$t(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&St(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),r=this.processEscapeSequences(e);return this.createLiteral(r,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=!0;break;case"false":e=!1;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value.slice(1,-2).trim();return this.createSelector(t)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(It)||this.matchPredicate(wt)||this.matchPredicate(kt)||this.matchPredicate(Et)||this.matchPredicate(xt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}return this.createIdentifier(t.value)}return"my"!==t.value||this.check(".")?"its"!==t.value||this.check(".")?"your"!==t.value||this.check(".")?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if($t(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.matchPredicate(It))e=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const t=this.previous().value,r=t.slice(1,-1);e=this.createLiteral(r,t)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(t.push({key:e,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(It))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);r=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();n.push(t.value),"$"===t.value&&this.check("{")&&(s=!0),"{"===t.value&&i++,"}"===t.value&&i--}const o=n.join(""),a=s?{type:"templateLiteral",value:o,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(o,o);if(e.push({key:r,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),r=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let t=1;for(;t>0&&!this.isAtEnd();){const e=this.advance();"("===e.value&&t++,")"===e.value&&t--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column},arguments:[],isConstructor:!0,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let r=e.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,r,n,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const r=t.callee.name,n=this.peek();if(!(Ie.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||It(n)&&!this.isCommand(n.value)||kt(n)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),Ie.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(r,t,s,i,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(dt("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return dt("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){dt("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[],e=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(e),dt("🔧 parseEventHandler: Parsed first event name: "+e);this.check("or");){this.advance(),dt("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),dt("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(dt("🔧 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,dt(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),dt("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=!0,dt("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=!0,dt("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=!0,dt("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),r=parseInt(e.value,10);if(isNaN(r))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=r,dt(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,dt(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else dt(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const r=this.advance(),n=(i=r.value).endsWith("ms")?parseInt(i,10):i.endsWith("seconds")||i.endsWith("s")?1e3*parseFloat(i):i.endsWith("minutes")?6e4*parseFloat(i):i.endsWith("hours")?36e5*parseFloat(i):i.endsWith("days")?864e5*parseFloat(i):parseInt(i,10);s[e]=n,dt(`🔧 parseEventHandler: Parsed '${t} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[e]=r,dt(`🔧 parseEventHandler: Parsed '${t} at ${r}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`)}var i;let o,a,c,l;if(Object.keys(s).length>0&&dt("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,dt(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,dt("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(dt("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),dt("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(dt(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(dt(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){dt("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())dt("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){dt("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const r=this.parseCommand();u.push(r);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),dt("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){dt("⚠️ Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const r={type:"command",name:e.left.name,args:[e.right],isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};u.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),f={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...n.length>0&&{params:n},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:h.start,end:h.end,line:h.line,column:h.column};return dt(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),f}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");r.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();It(t)?(r.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),r=n.has(e.value);this.checkIsCommand()&&!r||(t.push(e.value),i=e.value,this.advance())}}const o={type:"eventHandler",event:e,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...r.length>0&&{args:r},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,r=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(dt("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)dt("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){dt('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),r=this.getPosition(),n="Expected command, got: "+e.value;this.addError(n);const s=Kt(r,n,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return Qt.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return te(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!re(t,["catch","finally",...n.keywords])&&!te(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&te(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&te(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!te(t.peek(),n.keywords))break}const o=ae.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(dt(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(dt(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return dt("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),r=e.value.toLowerCase();if(t.includes(r))break;if(Et(e))break;this.advance()}}parseCommand(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const r={};let n=null;if(!t.isAtEnd()&&t.check("/")&&(n=function(t){const e=t.savePosition();let r="";for(;!t.isAtEnd()&&!ge(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(t)),n||(n=t.parsePrimary()),!n)return t.addError("fetch requires a URL"),ae.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(r.with=t.parsePrimary());for(let e=0;2>e&&!t.isAtEnd();e++)if(!t.check("as")||r.as){if(!t.check("with")||r.with)break;t.advance(),r.with=be(t)?Ee(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||oe(t,"a")||oe(t,"an"),r.as=t.parsePrimary();const s=ae.from(e).withArgs(n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),t);const r=this.parseMultiWordCommand(t,e);if(r)return r;const n=e.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(t);if("for"===n)return this.parseForCommand(t);if("if"===n||"unless"===n)return this.parseIfCommand(t);if("wait"===n)return this.parseWaitCommand(t);if("install"===n)return this.parseInstallCommand(t);if("transition"===n)return this.parseTransitionCommand(t);if("add"===n)return this.parseAddCommand(t);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||this.createErrorNode();const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const r=e.value,n="increment"===r?"+":"-";let s=!1;t.check(g)&&(s=!0,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${r} command`);o=e}else o=Ut(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=Wt(n,i,o,c),u=[a,zt(h,c),l];return ae.from(e).withName("set").withArgs(...u).withOriginalCommand(r).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!e.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:!1,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(t),e)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if("me"===t&&this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),!1);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const r="computed-"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(r),!1)}{if($t(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;L(e)&&dt(`💡 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return Ut(t,e,this.getPosition())}createIdentifier(t){return zt(t,this.getPosition())}createBinaryExpression(t,e,r){return Wt(t,e,r,this.getPosition())}createUnaryExpression(t,e,r){return function(t,e,r,n){return{type:"unaryExpression",operator:t,argument:e,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createCallExpression(t,e){return function(t,e,r){return{type:"callExpression",callee:t,arguments:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createMemberExpression(t,e,r){return function(t,e,r,n){return{type:"memberExpression",object:t,property:e,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,r){return{type:"possessiveExpression",object:t,property:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(dt(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return dt("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return dt(`✅ createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return dt(`✅ createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),!0;return!1}matchOperator(t){if(this.isAtEnd())return!1;const e=this.peek();return!(!qt(e)||e.value!==t||(this.advance(),0))}check(t){if(this.isAtEnd())return!1;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return!this.isAtEnd()&&t(this.peek())}matchPredicate(t){return!!this.checkPredicate(t)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Nt)}matchSelector(){return this.matchPredicate(Nt)}checkAnySelector(){return this.checkPredicate(Ct)}checkLiteral(){return this.checkPredicate(Tt)}checkIdentifierLike(){return this.checkPredicate(St)}checkIsCommand(){return this.checkPredicate(Et)}checkCommandTerminator(){return this.checkPredicate(Ht)}checkReference(){return this.checkPredicate(Ot)}checkTimeExpression(){return this.checkPredicate(Lt)}checkEvent(){return this.checkPredicate(xt)}checkContextVar(){return this.checkPredicate(kt)}checkComment(){return this.checkPredicate(Rt)}checkIdentifier(){return this.checkPredicate(It)}checkKeyword(){return this.checkPredicate(wt)}checkString(){return this.checkPredicate(jt)}matchString(){return this.matchPredicate(jt)}checkNumber(){return this.checkPredicate(Mt)}matchNumber(){return this.matchPredicate(Mt)}checkBoolean(){return this.checkPredicate(Dt)}matchBoolean(){return this.matchPredicate(Dt)}checkTemplateLiteral(){return this.checkPredicate(Pt)}matchTemplateLiteral(){return this.matchPredicate(Pt)}checkQueryReference(){return this.checkPredicate(Vt)}matchQueryReference(){return this.matchPredicate(Vt)}checkIdSelector(){return this.checkPredicate(Bt)}checkClassSelector(){return this.checkPredicate(Ft)}checkCssSelector(){return this.checkPredicate(_t)}checkBasicOperator(){return this.checkPredicate(qt)}matchBasicOperator(){return this.matchPredicate(qt)}matchTimeExpression(){return this.matchPredicate(Lt)}matchIdentifierLike(){return this.matchPredicate(St)}matchComparisonOperator(){return this.matchPredicate(At)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(It,t)}consumeIdentifierLike(t){return this.consumePredicate(St,t)}consumeEvent(t){return this.consumePredicate(xt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let r=e.start||0,n=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1,0===r&&this.current>0&&(r=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;r=t.start||0,n=t.line||1,s=t.column||1,0===r&&(r=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const r=this.tokens[e];if(r&&("+"===r.value||"-"===r.value)){t=r;break}}r=t.start||0,n=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;dt("⚠️ synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();n.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:t,end:this.previous().end,line:e,column:r}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>{const r=t.current+e;return r>=0&&t.tokens.length>r?t.tokens[r]:null},getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:!0,configurable:!0}),e}}function je(t,e){const r=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const r=t.length;for(;r>e.position&&(q(e),r>e.position);){const r=t[e.position];if("-"!==r||"-"!==F(e,1))if('"'!==r){if("'"===r||"'"===r){const t=F(e,1),r=e.tokens[e.tokens.length-1];if("s"!==t||!r||r.kind!==P.IDENTIFIER&&r.kind!==P.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(e);else{const t=e.position;_(e),_(e),H(e,P.OPERATOR,"'s",t)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===F(e,1)){const t=e.position;_(e),_(e),H(e,P.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=t&&t.kind===P.IDENTIFIER&&w.has(t.value.toLowerCase()),s=t&&t.kind===P.IDENTIFIER&&r.has(t.value.toLowerCase());if((!t||t.kind===P.OPERATOR&&")"!==t.value&&"]"!==t.value||n||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(et(F(e))||"{"===F(e))){Z(e);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const t=e.tokens[e.tokens.length-1],r=t&&t.kind===P.IDENTIFIER&&M.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==P.IDENTIFIER&&")"!==t.value&&"]"!==t.value||r)&&r?(H(e,P.SYMBOL,"["),_(e)):(H(e,P.OPERATOR,"["),_(e));continue}if("]"!==r){if("$"===r){const t=F(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){tt(e);continue}}st(r)?Y(e):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(H(e,P.UNKNOWN,r),_(e)):Q(e):K(e)}else H(e,P.OPERATOR,"]"),_(e)}else H(e,P.OPERATOR,"}"),_(e);else H(e,P.OPERATOR,"{"),_(e);else X(e)}else Z(e);else nt(e)?G(e):Y(e);else J(e)}else W(e);else z(e)}return e.tokens}(t);return new Ie(r,e,t).parse()}Ie.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),Ie.PRATT_TABLE=Re,Ie.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Me{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return!1;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const r of this.afterExecuteHooks)await r(t,e)}async runOnError(t,e){let r=e;for(const e of this.onErrorHooks){const n=await e(t,r);n instanceof Error&&(r=n)}return r}shouldIntercept(t,e){for(const r of this.interceptCommandHooks)if(r(t,e))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function De(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Pe(t){return{ok:!0,value:t}}function Ve(t){return{ok:!1,error:t}}function Be(t){return!0===t.ok}class Fe{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??!1}registerListener(t,e,r,n,s){this.addCleanup(t,{type:"listener",target:e,eventName:r,cleanup:()=>{e.removeEventListener(r,n,s),this.debugMode&&mt(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&mt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&mt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&mt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,r){this.addCleanup(t,{type:"custom",cleanup:e,description:r||"Custom cleanup"})}registerGlobal(t,e="custom",r){this.globalCleanups.push({type:e,cleanup:t,description:r||"Global cleanup"}),this.debugMode&&mt("CleanupRegistry: Registered global cleanup: "+(r||e))}addCleanup(t,e){const r=this.elementCleanups.get(t);r?r.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&mt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let r=0;for(const t of e){try{t.cleanup(),r++}catch(t){this.debugMode&&mt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&mt(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(t){let e=this.cleanupElement(t);const r=t.querySelectorAll("*");for(const t of r)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&mt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&mt(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}const _e=new Map;function qe(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||_e,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class He{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const r=t.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(r,e)}unregister(t){const e=t.toLowerCase(),r=this.sources.get(e);if(r){for(const[t,r]of this.subscriptions.entries())r.source===e&&(r.unsubscribe(),this.subscriptions.delete(t));return r.destroy?.(),this.sources.delete(e)}return!1}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,r){const n=this.get(t);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+t);n.initialize?.();const s=n.subscribe(e,r);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return!!e&&(e.unsubscribe(),this.subscriptions.delete(t))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,r]of this.sources.entries())if(r.supports?.(t)??r.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Ue{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,r){const n=t.toLowerCase();this.providers.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:e)}registerGlobal(t,e,r){const n=t.toLowerCase();this.globalProviders.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const t of n.dependencies)await this.resolve(t,e,r);const i=await n.provide(e);return n.cache&&r&&r.set(s,i),i}resolveSync(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(t){const e=this,r=new Map;return new Proxy(t,{get(t,n,s){if("string"==typeof n&&e.get(n))try{return e.resolveSync(n,t,r)}catch{return e.resolve(n,t,r)}return Reflect.get(t,n,s)},has:(t,r)=>!("string"!=typeof r||!e.has(r))||Reflect.has(t,r)})}async resolveAll(t){const e=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,t,e)}catch(t){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const ze=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,r]of this.types)if(r.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),r=this.types.get(e);return r?.hyperscriptType??"unknown"}coerce(t,e,r){const n=this.types.get(e);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(n.isType(t))return t;if(this.config.cacheCoercions){const r=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(t),i=n.coerceFrom?.[s];if(i){const n=i(t,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(t,e){const r=this.types.get(e);if(!r)return!1;if(r.isType(t))return!0;const n=this.inferType(t);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(t,e){const r=this.types.get(e);return r&&(t===e||r.coerceFrom?.[t])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e||"false"!==e&&"no"!==e&&"0"!==e&&""!==e&&e.length>0},Number:t=>0!==t,Null:()=>!1,Undefined:()=>!1,Array:t=>!!Array.isArray(t)&&t.length>0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const r=t;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,r)=>{e[r+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>!0,defaultValue:null,description:"Unknown/any value type"})}};function We(t){const e=ze.get("String");return e?e.isType(t):"string"==typeof t}function Je(t){const e=ze.get("Number");return e?e.isType(t):"number"==typeof t}function Ze(t){const e=ze.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ge(t){const e=ze.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Xe(t){const e=ze.get("Function");return e?e.isType(t):"function"==typeof t}function Ye(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Ke(t){return t instanceof Element}const Qe=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function tr(t,e){return Qe.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const er={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return!1;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>Ye(t)?t.tabIndex:void 0,hidden:t=>Ye(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t.getAttribute("name");r&&"value"in t&&e.append(r,t.value)}),e}(t)};function rr(t,e){if(e.startsWith("computed-")){const r=e.slice(9);return function(t){return t instanceof HTMLElement}(t)?getComputedStyle(t).getPropertyValue(r):void 0}if(e.startsWith("@"))return tr(t,e.slice(1));const r=er[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return tr(t,e);const n=t[e];return Xe(n)?n.bind(t):n}function nr(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t}function sr(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function ir(t,e){return e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):e.variables?.has(t)?e.variables.get(t):"me"===t?e.me:"it"===t?e.it:"result"===t?e.result:void 0}async function or(t,e){if(t.includes(".")){const r=t.split(".");let n=ir(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return ir(t,e)}async function ar(t,e){if(pt(`RESOLVE: Looking for '${t}' in context`,{hasInLocals:e.locals.has(t),localsKeys:Array.from(e.locals.keys()),value:e.locals.get(t)}),e.locals.has(t)){const r=e.locals.get(t);return pt(`RESOLVE: Found '${t}' in locals:`,r),r}if(e.globals&&e.globals.has(t)){const r=e.globals.get(t);return pt(`RESOLVE: Found '${t}' in globals:`,r),r}if(e.variables&&e.variables.has(t)){const r=e.variables.get(t);return pt(`RESOLVE: Found '${t}' in variables (legacy):`,r),r}const r=Number(t);if(!isNaN(r))return r;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const r=t.split("."),n=r[0];let s=null;if(e.locals.has(n)?s=e.locals.get(n):e.globals&&e.globals.has(n)?s=e.globals.get(n):e.variables&&e.variables.has(n)&&(s=e.variables.get(n)),null!=s){for(let t=1;r.length>t;t++){if(null==s)return void pt(`RESOLVE: Property access failed at '${r[t-1]}'`);s=s[r[t]]}return pt(`RESOLVE: Property access '${t}' =`,s),s}}return t}async function cr(t,e){pt("EVAL: Evaluating expression:",t);const r=t.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,t,n,s]=r;pt("EVAL: Parsed ternary:",{conditionExpr:t,trueExpr:n,falseExpr:s});const i=await ar(t.trim(),e);if(pt("EVAL: Ternary condition value:",i),i){const t=await ar(n.trim(),e);return pt("EVAL: Ternary returned true branch:",t),t}{const t=await ar(s.trim(),e);return pt("EVAL: Ternary returned false branch:",t),t}}const n=t.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,t,r,s]=n;pt("EVAL: Parsed arithmetic:",{left:t,operator:r,right:s});const i=await ar(t.trim(),e),o=await ar(s.trim(),e);pt("EVAL: Resolved values:",{leftValue:i,rightValue:o});const a=Number(i),c=Number(o);if(!isNaN(a)&&!isNaN(c)){let t;switch(r){case"+":t=a+c;break;case"-":t=a-c;break;case"*":t=a*c;break;case"/":t=a/c;break;case"%":t=a%c;break;default:t=a}return pt("EVAL: Arithmetic result:",t),t}}const s=await ar(t.trim(),e);return pt("EVAL: Fallback result:",s),s}function lr(t){if(Array.isArray(t)&&1===t.length&&(t=t[0]),null!==t&&"object"==typeof t&&"string"==typeof t.textContent){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?t:r}return 0}return t}async function ur(t,e,r,n,s){try{const i=s(await n(t.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const o=nr(t.property);if(!o||"string"!=typeof o)throw Error("Invalid method name: "+o);const a=i[o];if("function"!=typeof a)throw Error(`Property "${o}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(e.map(t=>n(t,r)));return a.apply(i,c)}catch(t){if(t instanceof Error)throw t;throw Error("Failed to evaluate method call: "+t)}}class hr{constructor(){this.expressionRegistry=new Map}registerCategory(t){Object.entries(t).forEach(([t,e])=>{this.expressionRegistry.set(t,e)})}unwrapSelectorResult(t){if(t instanceof NodeList&&t.length>0)return t[0];if(Array.isArray(t)&&t.length>0){const e=t[0];return"index"in t&&"input"in t?t:e instanceof Element||e instanceof Node?e:t}return t}async evaluate(t,e){if(!t)return pt("EVALUATOR: Received null/undefined node, returning null"),null;if(!t.type)throw console.error("EVALUATOR: Node missing type property:",t),Error("Node missing type property: "+JSON.stringify(t));switch(t.type){case"identifier":return this.evaluateIdentifier(t,e);case"literal":return this.evaluateLiteral(t,e);case"string":return t.value??"";case"memberExpression":return this.evaluateMemberExpression(t,e);case"binaryExpression":return this.evaluateBinaryExpression(t,e);case"unaryExpression":return this.evaluateUnaryExpression(t,e);case"callExpression":return this.evaluateCallExpression(t,e);case"selector":return this.evaluateSelector(t,e);case"dollarExpression":return this.evaluateDollarExpression(t,e);case"possessiveExpression":return this.evaluatePossessiveExpression(t,e);case"templateLiteral":return this.evaluateTemplateLiteral(t,e);case"arrayLiteral":return this.evaluateArrayLiteral(t,e);case"objectLiteral":return this.evaluateObjectLiteral(t,e);case"conditionalExpression":return this.evaluateConditionalExpression(t,e);case"cssSelector":return this.evaluateCSSSelector(t,e);case"propertyAccess":return this.evaluatePropertyAccess(t,e);case"propertyOfExpression":return this.evaluatePropertyOfExpression(t,e);case"contextReference":return this.evaluateContextReference(t,e);case"queryReference":return this.evaluateQueryReference(t,e);case"idSelector":return this.evaluateIdSelector(t,e);case"attributeAccess":return this.evaluateAttributeAccess(t,e);case"asExpression":return this.evaluateAsExpression(t,e);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return Pe(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ve({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ve({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ve({type:"break"});if(e.isContinue)return Ve({type:"continue"});if(e.isReturn)return Ve({type:"return",returnValue:e.returnValue})}throw t}}async evaluateArrayLiteral(t,e){const r=t.elements||[],n=[];for(const t of r){const r=await this.evaluate(t,e);n.push(r)}return n}async evaluateObjectLiteral(t,e){const r=t.properties||[],n={};for(const t of r){let r;r="identifier"===t.key.type?t.key.name:"literal"===t.key.type?t.key.value+"":await this.evaluate(t.key,e)+"";const s=await this.evaluate(t.value,e);n[r]=s}return n}async evaluateConditionalExpression(t,e){return await this.evaluate(t.test,e)?this.evaluate(t.consequent,e):t.alternate?this.evaluate(t.alternate,e):void 0}async evaluateTemplateLiteral(t,e){return async function(t,e){let r=t.value||"";pt("TEMPLATE LITERAL: Evaluating",{template:r,node:t});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let t=s.length-1;t>=0;t--){const{match:n,varName:i,index:o}=s[t],a=await or(i,e);pt(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,o)+((a??"")+"")+r.slice(o+n.length)}let o="",a=0;for(;r.length>a;){const t=r.indexOf("${",a);if(-1===t){o+=r.slice(a);break}o+=r.slice(a,t);let n=1,s=t+2;for(;r.length>s&&n>0;)"{"===r[s]&&n++,"}"===r[s]&&n--,n>0&&s++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(t+2,s);let c;pt("TEMPLATE: Evaluating expression:",i);const l=i.trim();e.locals.has(l)?(c=e.locals.get(l),pt(`TEMPLATE: Found in locals: ${l} =`,c)):e.globals&&e.globals.has(l)?(c=e.globals.get(l),pt(`TEMPLATE: Found in globals: ${l} =`,c)):e.variables&&e.variables.has(l)?(c=e.variables.get(l),pt(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await cr(i,e),pt(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return cr(t,e)}async resolveValue(t,e){return ar(t,e)}async evaluateIdentifier(t,e){const{name:r,scope:n}=t;if("me"===r||"my"===r||"I"===r)return e.me;if("you"===r||"your"===r)return e.you;if("it"===r||"its"===r)return e.it;if("result"===r)return e.result;if("event"===r)return e.event;const s=this.expressionRegistry.get(r);return s?s.evaluate(e):"local"===n?e.locals?.has(r)?e.locals.get(r):void 0:"global"===n?e.globals?.has(r)?e.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:e.locals?.has(r)?e.locals.get(r):e.globals?.has(r)?e.globals.get(r):e.variables?.has(r)?e.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(t,e){return t.value}async evaluateContextReference(t,e){const{contextType:r}=t;switch(r){case"me":return e.me;case"it":return e.result;case"you":return e.you;case"event":return e.event;case"body":return e.meta?.ownerDocument?.body||document?.body;case"detail":return e.event?.detail;case"target":return e.you||e.event?.target;case"sender":return e.event?.target;default:return e.locals&&e.locals.has(r)?e.locals.get(r):void pt("Unknown context reference type: "+r)}}async evaluateMemberExpression(t,e){const{object:r,property:n,computed:s}=t;if("identifier"===r.type&&["add","remove"].includes(r.name)){const t=r.name,s=nr(n);if(!e.me)throw Error('Context element "me" is null');return void("add"===t?e.me.classList.add(s):"remove"===t&&e.me.classList.remove(s))}let i=await this.evaluate(r,e);if(s)return i[await this.evaluate(n,e)];{const t=nr(n);if(Array.isArray(i)&&"string"==typeof t&&("length"===t||t in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof t){if(t.startsWith("computed-")){const e=t.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(e):void 0}if(t.startsWith("@")){const e=t.substring(1);return i&&"function"==typeof i.getAttribute?tr(i,e):void 0}if(i&&i instanceof Element){if("previous"===t||"prev"===t)return i.previousElementSibling;if("next"===t)return i.nextElementSibling}}const e=i?.[t];return"function"==typeof e?e.bind(i):e}}coerceArithmeticOperand(t){return lr(t)}async evaluateBinaryExpression(t,e){return async function(t,e,r,n,s){const{operator:i,left:o,right:a}=t;if("in"===i&&"selector"===o.type){let t=o.value;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i&&"queryReference"===o.type){let t=o.selector;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i){let t=null,s=null;if("positionalExpression"===o.type){t=o.operator;const n=o.argument;"cssSelector"===n?.type?s=n.selector:"selector"===n?.type?s=n.value:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}else if("memberExpression"!==o.type||"identifier"!==o.object?.type||"first"!==o.object.name&&"last"!==o.object.name){if("callExpression"===o.type&&"identifier"===o.callee?.type&&("first"===o.callee.name||"last"===o.callee.name)){t=o.callee.name;const n=o.arguments?.[0];"selector"===n?.type?s=n.value:"cssSelector"===n?.type?s=n.selector:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}}else t=o.object.name,"identifier"===o.property?.type&&o.property.name&&(s="."+o.property.name);if(t&&s){const i=n(await r(a,e));if(!i||"function"!=typeof i.querySelectorAll)return;const o=i.querySelectorAll(s),c=Array.from(o);return"first"===t?c.length>0?c[0]:void 0:"last"===t?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const t=await r(o,e),n=a.value||a.selector;if(t&&"function"==typeof t.matches)try{return t.matches(n)}catch{return!1}return!1}const c=await r(o,e),l=await r(a,e);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const t=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(t)}if("attributeAccess"===a.type||"attributeRef"===a.type){const t=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(t)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const t=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(t)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const t=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(t))}if("selector"===a.type||"queryReference"===a.type){let t=a.value||a.selector||"";t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());try{return null!==c.querySelector(t)}catch{return!1}}if("cssSelector"===a.type){const t=a.selector||"";try{return null!==c.querySelector(t)}catch{return!1}}}return Array.isArray(c)?c.includes(l):"string"==typeof c&&c.includes(l+"")}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const t=lr(c),r=lr(l);if("string"==typeof t||"string"==typeof r){const n=s.get("stringConcatenation");if(n){pt("Using string concatenation for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}else{const n=s.get("addition");if(n){pt("Using numeric addition for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}return t+r}case"-":return lr(c)-lr(l);case"*":return lr(c)*lr(l);case"/":return lr(c)/lr(l);case"%":case"mod":return lr(c)%lr(l);case"as":const t="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=s.get("as");return r?r.evaluate(e,c,t):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const t="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===t}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const t="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===t)}case"=":if("identifier"===o.type){const t=o.name;return"result"===t?e.result=l:"it"===t?e.it=l:"you"===t?e.you=l:e.locals.set(t,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):!(!c||"function"!=typeof c.matches)&&c.matches(l+"");case"match":case"matches":if(c&&"function"==typeof c.matches){const t="string"==typeof l?l:l+"";try{return c.matches(t)}catch{return!1}}return!1;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===o.type&&"selector"===a.type?{command:o.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(t,e){const{operator:r,argument:n}=t,s=await this.evaluate(n,e);switch(r){case"not":case"!":const t=this.expressionRegistry.get("not");return t?t.evaluate(e,s):!s;case"no":const n=this.expressionRegistry.get("no");return!!n&&n.evaluate(e,s);case"some":return null!=s&&("string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"!=typeof s||Object.keys(s).length>0);case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(e,s):null!=s;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(e,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(t,e){return async function(t,e,r,n,s,i){const{callee:o,arguments:a,isConstructor:c}=t;if(c){const t=o.name,n=e.globals?.get(t)||window[t];if("function"==typeof n)return new n(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown constructor: "+t)}if("memberExpression"===o.type||"propertyAccess"===o.type)return ur(o,a,e,r,n);const l=o.name||o,u=s.get(l);if(u){const t=["first","last","random","at"],n=["closest","previous","next"].includes(l),s=t.includes(l),o=await Promise.all(a.map(t=>n&&t&&"selector"===t.type&&"string"==typeof t.value?t.value:n&&t&&"identifier"===t.type&&"string"==typeof t.name?t.name:s&&t&&"selector"===t.type&&"string"==typeof t.value?i(t,e):r(t,e)));return u.evaluate(e,...o)}const h=e.globals?.get(l)||window[l];if("function"==typeof h)return h(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown function: "+l)}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(t,e,r){return ur(t,e,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(t,e){return function(t,e){let r=t.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.tagName)}(t,e)}evaluateAttributeAccess(t,e){return e.me&&"function"==typeof e.me.getAttribute?tr(e.me,t.attributeName):"@"+t.attributeName}async evaluateAsExpression(t,e){const r=await this.evaluate(t.expression,e),n=this.expressionRegistry.get("as");if(n)return n.evaluate(e,r,t.targetType);throw Error("Conversion type 'as' not registered")}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(t,e){const r=await this.evaluate(t.expression,e);if("identifier"===t.expression.type){const r=t.expression.name;return/^\d+$/.test(r)?r:e.locals?.has(r)?e.locals.get(r):"me"===r&&e.me?e.me:"you"===r&&e.you?e.you:"it"===r&&e.it?e.it:"result"===r&&e.result?e.result:"undefined"!=typeof window&&"window"===r?window:e.globals?.has(r)?e.globals.get(r):void 0}return r}async evaluatePossessiveExpression(t,e){const{object:r,property:n}=t,s=this.unwrapSelectorResult(await this.evaluate(r,e));if(!s)return;const i=nr(n);return"string"==typeof i&&Ke(s)?rr(s,i):s[i]}hasExpression(t){return this.expressionRegistry.has(t)}async evaluateCSSSelector(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return"id"===t.selectorType?null:[];if("id"===t.selectorType){const t=r.startsWith("#")?r.slice(1):r;return n.getElementById(t)}if("class"===t.selectorType){const t=r.replace(/:/g,"\\:"),e=n.querySelectorAll(t);return Array.from(e).filter(t=>t instanceof HTMLElement)}const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t instanceof HTMLElement)}(t,e)}async evaluateIdSelector(t,e){return function(t,e){const r=sr(e);if(!r)return null;const n=t.value.startsWith("#")?t.value.slice(1):t.value;return r.getElementById(n)}(t,e)}async evaluateQueryReference(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(t,e)}async evaluatePropertyAccess(t,e){const r=await this.evaluate(t.object,e),n=t.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let t;return t=Ke(r)?rr(r,s):r[s],"function"==typeof t?t.bind(r):t}catch(t){throw Error(`Error accessing property "${s}": ${t}`)}}async evaluatePropertyOfExpression(t,e){const r=t.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(t.target,e));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let t;return t=Ke(s)?rr(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const fr={1:"one",2:"two",3:"three",4:"four",5:"five"};function dr(t,e,r,n){if(t.length!==e){return`${r} requires exactly ${s=e,fr[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`}var s;return null}function pr(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function mr(t,e,r){return dr(t,1,e,r)??pr(t,0,e,r)}function yr(t,e){return dr(t,2,e,"left, right")}function vr(){return null}function gr(t,e,r,n){return t.length>e?`${r} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null}function br(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function Er(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const wr="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let xr;function kr(){return xr({validate:t=>({success:!0,data:t})})}function Ar(t,e){if(wr)return kr();const r=xr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:Er("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(e?.strict){const e=Object.keys(t),r=Object.keys(n).filter(t=>!e.includes(t));if(r.length>0)return{success:!1,error:Er("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[e,r]of Object.entries(t)){const t=n[e];if(!(e in n)&&!r.t)return{success:!1,error:Er("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:!1,error:Er("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:!0,data:s}}});return r.strict=()=>Ar(t,{strict:!0}),r}xr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:!0,data:e.data}:{success:!1,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:!0,validate:e=>null==e?{success:!0,data:void 0}:t(e)};return xr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&t>n.data.length?{success:!1,error:Er("runtime-error",`String must be at least ${t} characters long`)}:n}};return xr(r)}),t.max||(t.max=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&n.data.length>t?{success:!1,error:Er("runtime-error",`String must be at most ${t} characters long`)}:n}};return xr(r)}),t.default||(t.default=function(t){const e=this.validate.bind(this),r={...this,i:t,o:!0,validate:r=>void 0===r?{success:!0,data:t}:e(r)};return xr(r)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?t(s.data)?s:{success:!1,error:Er("runtime-error",e||"Refinement validation failed")}:s}};return xr(n)}),new Proxy(t,{get:(t,e,r)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,r):function(...t){return r}})};const Sr=t=>function(t={}){return wr?kr():xr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Er("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Er("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Er("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:!1,error:Er("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Er("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),Cr=t=>function(t={}){return wr?kr():xr({validate:e=>{const r=Number(e);return isNaN(r)?{success:!1,error:Er("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:!1,error:Er("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:!1,error:Er("runtime-error","Number must be at most "+t.max)}:{success:!0,data:r}}})}(t||{}),Nr=()=>wr?kr():xr({validate:t=>"boolean"!=typeof t?{success:!1,error:Er("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),Tr=t=>Ar(t),Or=t=>function(t){return wr?kr():xr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Er("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Er("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const r=[];for(let n=0;t.length>n;n++){const s=t[n].validate(e[n]);if(!s.success)return{success:!1,error:Er("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(t),Lr=()=>kr(),$r=()=>kr(),Rr=()=>function(t,e="Custom validation failed"){return wr?kr():xr({validate:r=>t(r)?{success:!0,data:r}:{success:!1,error:Er("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Ir{trackPerformance(t,e,r,n){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(t,e,r,n=(r?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:e,duration:Date.now()-e,success:r})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||Je(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,r,n,s=[]){return{success:!1,error:{name:t,type:e,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,r=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:r}],suggestions:r}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":Ge(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":We(t)?"String":Je(t)?"Number":Ze(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):We(t)?t.split(""):null==t?[]:Ge(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(Je(t)&&Number.isFinite(t))return t;if(We(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Ze(t)?t?1:0:null}}const jr=Tr({selector:Sr().min(1),single:Nr().optional().default(!1)});new class extends Ir{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Rr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=Rr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=Rr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.it,s={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=jr,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const r=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,n,r),n}let n;if(e.single)n=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));n=t.length>0?t:null}const s={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=e.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),!0}catch{return!1}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const Mr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:vr},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:vr},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:vr},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:vr},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:vr},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:t=>mr(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>mr(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:t=>mr(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:t=>mr(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let r=e[0];if(r&&"object"==typeof r&&"type"in r){const t=r;"identifier"===t.type&&t.name?r=t.name:"literal"===t.type&&"string"==typeof t.value&&(r=t.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return t.me?t.me.closest(r):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:vr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:vr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:vr},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>mr(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||t.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>br(t,1,2,"styleRef","property, optional element")??pr(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>dr(t,2,"possessiveStyleRef","possessor, property")??pr(t,0,"possessiveStyleRef","possessor")??pr(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>dr(t,2,"ofStyleRef","property, reference")??pr(t,0,"ofStyleRef","property")??pr(t,1,"ofStyleRef","reference")}};class Dr{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(Date.now()-e.timestamp<=this.ttl)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU();const r={result:e,timestamp:Date.now(),accessCount:1};this.cache.set(t,r),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[r,n]of this.accessOrder)e>n&&(e=n,t=r);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,r)=>t+(e-r.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const Pr=new class{constructor(){this.domQueryCache=new Dr(200,3e3),this.exprResultCache=new Dr(500,2e3),this.cssMatchCache=new Dr(100,5e3),this.formValueCache=new Dr(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(t);return this.domQueryCache.set(e,n),n}querySelectorAll(t){const e="querySelectorAll:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,n),n}getElementById(t){const e="getElementById:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(t);return this.domQueryCache.set(e,n),n}getElementsByClassName(t){const e="getElementsByClassName:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,n),n}matches(t,e){const r=`matches:${this.getElementCacheKey(t)}:${e}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(r,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),r=this.formValueCache.get("formValue:"+e);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(t,e){const r=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+r,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(t.cache.keys()))"string"==typeof r&&r.includes(e)&&t.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),r=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${r}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([r,n])=>{t-n.timestamp>e.ttl&&e.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{Pr.cleanup()},1e4);const Vr=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const r=performance.now()-e;return this.startTimes.delete(t),r}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=Pr.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Br(){Pr.cleanup(),Vr.getMetrics().memoryUsage>52428800&&Vr.reset()}let Fr=null;function _r(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const r=t.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${e} cannot be converted to number: "${t}"`);return n}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const r=t[0];if(Array.isArray(r))throw Error(e+" is a nested array, cannot convert to number");return _r(r,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);if(!isNaN(r))return r}}const r=t.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function qr(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?null:r}return"boolean"==typeof t?t?1:0:null==t?0:null}function Hr(t,e,r){if("==="===r)return t===e;if("!=="===r)return t!==e;if(null==t||null==e)return function(t,e,r){if(null==t&&null==e)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,r);const[n,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const r=parseFloat(t),n=parseFloat(e);return isNaN(r)||isNaN(n)?[t,e]:[r,n]}const r=qr(t),n=qr(e);return null!==r&&null!==n?[r,n]:[t+"",e+""]}(t,e);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return Ur(t,e);case"!=":return!Ur(t,e);default:return!1}}function Ur(t,e){if(t===e)return!0;if(typeof t==typeof e)return("string"==typeof t||"number"==typeof t)&&t===e;if("number"==typeof t&&"string"==typeof e){const r=parseFloat(e);return!isNaN(r)&&t===r}if("string"==typeof t&&"number"==typeof e){const r=parseFloat(t);return!isNaN(r)&&r===e}return"boolean"==typeof t?Ur(t?1:0,e):"boolean"==typeof e?Ur(t,e?1:0):t+""==e+""}function zr(t,e,r,n,s,i=!0,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),n}"undefined"!=typeof window&&function(t=3e4){Fr&&clearInterval(Fr),Fr=setInterval(Br,t)}();const Wr=Tr({left:Lr().describe("Left operand value"),right:Lr().describe("Right operand value")}).strict(),Jr=Tr({operand:Lr().describe("Operand value to negate")}).strict();function Zr(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Ir{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=Wr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,r,!0,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=Wr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,r,!0,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=Jr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,r,!0,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Gr=Or([Lr(),Lr()]),Xr=Or([Lr(),Sr()]),Yr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return zr(this,t,[e,r],e==r,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>yr(t,"equals"),inputSchema:Gr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Kr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e===r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"strictEquals")},Qr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!=r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"notEquals")},tn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!==r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"strictNotEquals")},en={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,"<");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"lessThan")},rn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,"<=");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"lessThanOrEqual")},nn={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,">");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"greaterThan")},sn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,">=");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"greaterThanOrEqual")},on={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return zr(this,t,[e,r],e&&r,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>yr(t,"and"),inputSchema:Gr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},an={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e||r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"or")},cn={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"not","operand")},ln={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||(We(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!Ge(e)||0!==Object.keys(e).length)),r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"isEmpty","value")},un={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:!(We(e)||e instanceof Node||e instanceof Element||!Ge(e)||0!==Object.keys(e).length)),r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"no","value")},hn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!await ln.evaluate(t,e);return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"isNotEmpty","value")},fn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null!=e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"exists","value")},dn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null==e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"doesNotExist","value")},pn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i;if(e&&r){if(Zr(e)&&Zr(r))return i=e.contains(r),n&&zr(this,t,[e,r],i,s),i;if(We(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Zr(r))return i=o.contains(r),n&&zr(this,t,[e,r],i,s),i;if(o&&We(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=!!a&&o.contains(a),n&&zr(this,t,[e,r],i,s),i}}if(We(r)&&r.match(/^[.#][\w-]+$/)&&Zr(e)){const o=document.querySelector(r);return i=!!o&&e.contains(o),n&&zr(this,t,[e,r],i,s),i}}return i=We(e)&&We(r)||Array.isArray(e)?e.includes(r):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(r):!(!Ge(e)||!We(r))&&r in e,n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"contains","container, value")},mn={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await pn.evaluate(t,e,r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"doesNotContain","container, value")},yn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!(!We(e)||!We(r))&&e.startsWith(r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"startsWith","str, prefix")},vn={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!(!We(e)||!We(r))&&e.endsWith(r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"endsWith","str, suffix")},gn={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,r){const n=Date.now();try{let s;if(e instanceof Element&&We(r)){const t=r;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return Pr.matches(t,e)}(e,t)}catch(t){s=!1}else s=!1}else if(We(e)&&We(r)){const t=e,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(t)}catch(e){s=t.includes(n)}}else s=!1;return zr(this,t,[e,r],s,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>dr(t,2,"matches","element, selector"),inputSchema:Xr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},bn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i=!1;if(e instanceof Element&&We(r)){const t=r;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"has","element, selector")},En={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await bn.evaluate(t,e,r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"doesNotHave","element, selector")},wn={equals:Yr,strictEquals:Kr,notEquals:Qr,strictNotEquals:tn,lessThan:en,lessThanOrEqual:rn,greaterThan:nn,greaterThanOrEqual:sn,and:on,or:an,not:cn,no:un,isEmpty:ln,isNotEmpty:hn,exists:fn,doesNotExist:dn,contains:pn,doesNotContain:mn,startsWith:yn,endsWith:vn,matches:gn,has:bn,doesNotHave:En};function xn(t,e,r,n,s="runtime-error"){return{success:!1,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function kn(t,e){return{success:!0,value:t,type:e}}function An(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const Sn={Array:(t,e)=>{try{return Array.isArray(t)?kn(t,"array"):t instanceof NodeList?kn(Array.from(t),"array"):kn(null==t?[]:[t],"array")}catch(t){return xn("Array","ARRAY_CONVERSION_FAILED",An("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?kn("","string"):We(t)?kn(t,"string"):Ge(t)?kn(JSON.stringify(t),"string"):kn(t+"","string")}catch(t){return xn("String","STRING_CONVERSION_FAILED",An("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Ze(t))return kn(t,"boolean");if(null==t)return kn(!1,"boolean");if(We(t)){const e=t.toLowerCase().trim();return kn("false"!==e&&"0"!==e&&""!==e,"boolean")}return Je(t)?kn(0!==t&&!isNaN(t),"boolean"):kn(!!t,"boolean")}catch(t){return xn("Boolean","BOOLEAN_CONVERSION_FAILED",An("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(Je(t))return kn(t,"number");if(null==t)return kn(0,"number");const e=Number(t);return isNaN(e)?xn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):kn(e,"number")}catch(t){return xn("Number","NUMBER_CONVERSION_FAILED",An("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=Sn.Number(t,e);return r.success?kn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=Sn.Number(t,e);return r.success?kn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return kn(t,"object");if(null==t)return kn(new Date(""),"object");if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return kn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?xn("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):kn(e,"object")}catch(t){return xn("Date","DATE_CONVERSION_FAILED",An("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return kn(JSON.stringify(t),"string")}catch(t){return xn("JSON","JSON_STRINGIFY_FAILED",An("Failed to convert value to JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(Ge(t))return kn(t,"object");if(We(t))try{return kn(JSON.parse(t),"object")}catch(t){return xn("Object","JSON_PARSE_FAILED",An("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return kn({},"object")}catch(t){return xn("Object","OBJECT_CONVERSION_FAILED",An("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return kn(On(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{const e=t;if(e.name){const t=Ln(e);void 0!==t&&(r[e.name]=t)}}),kn(r,"object")}return kn({},"object")}catch(t){return xn("FormValues","FORM_VALUES_EXTRACTION_FAILED",An("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Cn=Tr({value:$r(),type:Sr().min(1)}),Nn=Tr({value:$r(),type:Sr().min(1)});new class extends Ir{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=Cn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),o=n?parseInt(n[1],10):2,a=Sn.Number(s,t);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,r),c}let o=Sn[i];if(o){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[i.toLowerCase()];if(a&&(o=Sn[a],o)){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,r),c}catch(n){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Ir{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Nn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=We(s);break;case"number":a=Je(s)&&!isNaN(s);break;case"boolean":a=Ze(s);break;case"object":a=Ge(s);break;case"array":a=Array.isArray(s);break;case"function":a=Xe(s);break;case"date":a=s instanceof Date;break;case"element":a=s instanceof Element;break;case"node":a=s instanceof Node;break;case"node-list":a=s instanceof NodeList;break;case"empty":a=null==s||""===s||Array.isArray(s)&&0===s.length||Ge(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,r),c}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const Tn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":We(t)?t:Ge(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Ze(t))return t;if(null==t)return!1;if(We(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return Je(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(Je(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(Je(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!Je(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Tn.Number(t);return Math.trunc(e)},Float:t=>{const e=Tn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return new Date(e,r-1,n)}return new Date(t)},JSON:t=>{try{return JSON.stringify(t)}catch(t){return"{}"}},Object:t=>{if(Ge(t))return t;if(We(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{We(t)||(t=Tn.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>We(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Tn.String(t)).join(""):t instanceof Element?t.outerHTML:Tn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return On(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=Ln(t))}),r}return{}},"Values:Form":(t,e)=>{const r=Tn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=Tn.Values(t,e);return JSON.stringify(r)}};function On(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=Ln(r);void 0!==t&&(void 0!==e[r.name]?(Array.isArray(e[r.name])||(e[r.name]=[e[r.name]]),e[r.name].push(t)):e[r.name]=t)}}),e}function Ln(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const $n={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:t}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):2}:{}}(n);return Tn.Number(r).toFixed(t||2)}let s=Tn[n];if(s)return s(r,t);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(s=Tn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>dr(t,2,"as","value, type")??pr(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[r,n]=e;if(!We(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return We(r);case"number":return Je(r)&&!isNaN(r);case"boolean":return Ze(r);case"object":return Ge(r);case"array":return Array.isArray(r);case"function":return Xe(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||Ge(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>dr(t,2,"is","value, type")??pr(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>dr(t,1,"async","expression")}},Rn={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},In=Tr({collection:Lr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),jn=Tr({collection:Lr().describe("Collection to access"),index:Cr().describe("Index position to access")}).strict(),Mn=Tr({collection:Lr().describe("Collection to select random item from")}).strict();function Dn(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;const t=r.querySelector(e);if(t)return t;r=r.nextElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Dn(n,e):null}function Pn(t,e){let r=t.previousElementSibling;for(;r;){const t=Array.from(r.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(r.matches(e))return r;r=r.previousElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Pn(n,e):null}function Vn(t){let e=0,r=t;for(;r&&r.parentElement;)e+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,e+=1e3;return e}new class extends Ir{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=In,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=In,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=jn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:!0,value:o,type:Rn[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,r),a}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends Ir{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=Mn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(t,e,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const Bn={first:{name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const r=void 0!==e?e:t.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:We(r)?r.length>0?r[0]:null:Ge(r)&&"length"in r&&Je(r.length)&&r.length>0?r[0]:null},validate:t=>gr(t,1,"first","collection")},last:{name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const r=void 0!==e?e:t.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const t=r.children;return t.length>0?t[t.length-1]:null}return We(r)?r.length>0?r[r.length-1]:null:Ge(r)&&"length"in r&&Je(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>gr(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!Je(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(We(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Ge(i)&&"length"in i&&Je(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>br(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)},next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Dn(s,r):s.nextElementSibling:null},validate:t=>gr(t,2,"next","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Pn(s,r):s.previousElementSibling:null},validate:t=>gr(t,2,"previous","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=Vn(t);for(const t of n)if(Vn(t)>s)return t;return null}(i,r,o):null},validate:t=>br(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=Vn(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>Vn(e))return e}return null}(i,r,o):null},validate:t=>br(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}},Fn=new Set(["__proto__","constructor","prototype"]),_n={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[r,n]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return rr(r,n);if(Ge(r)){if(Fn.has(n))return;return r[n]}return r[n]}},validate:t=>dr(t,2,"possessive","element, property")??pr(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[r]=e;if(t.me){if("string"!=typeof r)throw Error("Property name must be a string");if(t.me instanceof Element)return rr(t.me,r);if(Ge(t.me)){if(Fn.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>mr(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[r]=e;if(null==t.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=t.it;if(n instanceof Element)return rr(n,r);if(Ge(n)){if(Fn.has(r))return;return n[r]}return n[r]},validate:t=>mr(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[r]=e;if(t.you){if("string"!=typeof r)throw Error("Property name must be a string");if(t.you instanceof Element)return rr(t.you,r);if(Ge(t.you)){if(Fn.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>mr(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[r,n]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return rr(n,r);if(Ge(n)){if(Fn.has(r))return;return n[r]}return n[r]}},validate:t=>dr(t,2,"of","property, object")??pr(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||t.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:t=>br(t,1,2,"attribute","attributeName, optional element")??pr(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[r,n,s]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||t.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:t=>br(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??pr(t,0,"attributeWithValue","attribute name")??pr(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:t=>mr(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:t=>mr(t,"idReference","idValue")}},qn=Tr({value:Sr().describe("String literal value")}).strict(),Hn=Tr({value:Cr().describe("Number literal value")}).strict(),Un=Tr({value:Nr().describe("Boolean literal value")}).strict(),zn=Tr({left:Lr().describe("Left operand"),right:Lr().describe("Right operand")}).strict();const Wn={stringLiteral:new class extends Ir{constructor(){super(...arguments),this.name="stringLiteral",this.category="Special",this.syntax="\"string\" or 'string'",this.description="String literals with template interpolation support",this.outputType="String",this.inputSchema=qn,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid){const e=this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(t,r,!1),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,r,!0,s),i}catch(e){return this.trackSimple(t,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let r=t.replace(/\$\{([^}]+)\}/g,(t,r)=>{try{const t=this.resolveExpression(r.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,r)=>{try{const t=this.resolveVariable(r,e);return void 0!==t?t+"":""}catch(t){return""}}),r}resolveExpression(t,e){if(t.includes(".")){const r=t.split(".");let n=this.resolveVariable(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Ir{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Hn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?Number.isFinite(e.value)?(this.trackSimple(t,r,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Ir{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Un,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?(this.trackSimple(t,r,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Ir{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=zn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=_r(e.left,"left operand")+_r(e.right,"right operand");return this.trackSimple(t,r,!0,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Ir{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=zn,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,r,!0,s),this.success(s,"string")}catch(e){return this.trackSimple(t,r,!1),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=zn.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(We(t))return t;if(Je(t))return""+t;if(Ze(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Ir{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=zn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=_r(e.left,"left operand")*_r(e.right,"right operand");return this.trackSimple(t,r,!0,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};class Jn extends hr{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Mr),this.registerCategory(wn),this.registerCategory($n),this.registerCategory(Bn),this.registerCategory(_n),this.registerCategory(Wn)}}class Zn{static toTyped(t){return{me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Gn{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new Jn,this.hookRegistry=r??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,r={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:r,event:t.event??void 0,executionContext:t}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(t,...e){const r=e[0],n=this.createHookContext(t,e,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(ht(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void ht(`CommandAdapterV2: '${this.name}' intercepted by hook`);t.locals||(t.locals=new Map),t.locals.set("__evaluator",this.expressionEvaluator);const s=Zn.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ht(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const e=r.modifiers,n=e?.when||e?.where;if(n&&!await this.expressionEvaluator.evaluate(n,t))return void ht(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:e||{},commandName:r.commandName},this.expressionEvaluator,t)}else i=e;else ht(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;return ht("CommandAdapterV2: Calling execute with parsed input:",i),o=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),ht("CommandAdapterV2: Command result:",o),Object.assign(t,Zn.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(es(t)||ht(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(n,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:!0,errors:[],suggestions:[]}}}class Xn{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=t,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);mt(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=e.toLowerCase();mt(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,t);const n=new Gn(t,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),w.add(r);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const r=e.toLowerCase();this.implementations.set(r,t),this.adapters.set(r,n),w.add(r)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const r=this.getAdapter(t);return r?r.validate(e):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Yn=null;function Kn(){return Yn||(Yn=function(t){const e=t?.commands??new Xn,r=t?.eventSources??new He,n=t?.context??new Ue,s=new Set,i={commands:e,eventSources:r,context:n,use(t){if(s.has(t.name))console.warn(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const r of t.commands)e.register(r);if(t.eventSources)for(const e of t.eventSources)r.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:r,options:s}of t.contextProviders)n.register(e,r,s);t.setup?.(i),s.add(t.name)}},reset(){s.clear()}};return i}()),Yn}class Qn{constructor(t={}){this.contextCache=new WeakMap;const e=Kn();this.options={enableContextProviders:t.enableContextProviders??!0,enableEventSources:t.enableEventSources??!0,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,mt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),mt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return mt("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return mt(`[RegistryIntegration] Found event source for '${t}'`),e;const r=this.eventSourceRegistry.findSourceForEvent(t);if(r){const e=this.eventSourceRegistry.get(r);return mt(`[RegistryIntegration] Found event source '${r}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(t,e,r);if(!n)throw Error(`Failed to subscribe to event source '${t}'`);return mt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,mt("[RegistryIntegration] Destroyed")}}function ts(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=!0,"returnValue"in t&&(e.returnValue=t.returnValue),e}function es(t){return t instanceof Error&&(null!==De(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function rs(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function ns(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const ss=new WeakMap;class is{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...t},this.registry=t.registry,this.expressionEvaluator=t.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=_e,this.hookRegistry=new Me,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Fe,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Qn("object"==typeof t.registryIntegration?t.registryIntegration:{}),mt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,r)=>await this.installBehaviorOnElement(t,e,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const r of t)for(const t of r.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&mt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),mt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){mt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,r)=>this.execute(t,r||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return mt("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(t,e);if(!Be(r))throw ts(r.error);return r.value}catch(t){throw t}return await this.processCommand(t,e);case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const r={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(r,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=t,n=await this.executeCommandSequenceWithResult(r.commands||[],e);if(!Be(n))throw ts(n.error);return n.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(t,e);if(!Be(r))throw ts(r.error);return r.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ht(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw es(t)||console.error(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),Error(o)}toSignal(t){const e=De(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ht(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Pe(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw console.error(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let r;for(const n of t){if(this.hasErrorDiagnostics(n)){const t=n.diagnostics?.[0];mt("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===n.type){const t=await this.processCommandWithResult(n,e);if(!Be(t)){const r=t.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==r.returnValue&&Object.assign(e,{it:r.returnValue,result:r.returnValue}),Pe(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!Be(t))return t;r=t.value}}return Pe(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return ns(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!Be(r))return r;const n=r.value;if(ns(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return Pe(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw t}}return Pe(n)}async executeCommandFromPattern(t,e,r){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},r)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let r;const n=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?n.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of n)try{await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}return r}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const r of t.commands)try{await this.execute(r,e)}catch(t){if(es(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let r;for(const n of t.commands)try{r=await this.execute(n,e)}catch(t){if(es(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return r}async executeObjectLiteral(t,e){const r={};if(!t.properties)return r;for(const n of t.properties){let t;t="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,e)+"";const s=await this.execute(n.value,e);r[t]=s}return r}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:o}),mt(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),mt(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(t,e,r){mt("BEHAVIOR: installBehaviorOnElement called: "+t);let n=this.behaviorRegistry.get(t);if(!n&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(n=this.behaviorRegistry.get(t)),!n))throw Error(`Behavior "${t}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return mt(`BEHAVIOR: Installing imperative behavior '${t}'`),n.install(e,r),void mt(`BEHAVIOR: Finished installing imperative behavior '${t}'`);mt("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(n.parameters)for(const t of n.parameters)i.locals.set(t,t in r?r[t]:void 0);for(const[t,e]of Object.entries(r))n.parameters?.includes(t)||i.locals.set(t,e);if(n.initBlock){mt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),mt("BEHAVIOR: Init block completed for "+t)}catch(e){if(mt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&es(e)))throw e}}if(mt(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${t}`),n.eventHandlers){const e=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}mt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:r,events:n,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=t,h=n&&n.length>0?n:[r];mt(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);mt(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else mt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void mt(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===r&&l)return void this.setupChangeObserver(l,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){mt(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${r}'`);const t=async t=>{const n=new Map(e.locals),i={...e,locals:n,it:t,event:t},o=this.enhanceContext(i);mt(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,t)}};try{const n=this.registryIntegration.subscribeToEventSource(p,{event:r,handler:t,target:i,selector:a},e);mt(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(t){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=is.createEventHandler(this,s,e,a,o);let y,v=null;if(u){let t=m;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>t(n),e)},v=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const e=u.throttle;let r=0;y=n=>{const s=Date.now();e>s-r||(r=s,t(n))}}else y=t}else y=m;const g=u?.once?{once:!0}:void 0;if(d){for(const t of h)d.addEventListener(t,y,g),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);v&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],v,"debounce-timeout"):this.cleanupRegistry.registerGlobal(v,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h)t.addEventListener(e,y,g),this.cleanupRegistry.registerListener(t,t,e,y);v&&this.cleanupRegistry.registerCustom(t,v,"debounce-timeout")}}static createEventHandler(t,e,r,n,s){return async i=>{const o=ss.get(i)??0;if(o>=100)return;if(ss.set(i,o+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{mt(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const r of s)l.locals.set(r,t[r]??e?.[r]??null)}for(const r of e)try{const e=rs(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(es(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw console.error("COMMAND FAILED:",t),t}}}setupMutationObserver(t,e,r,n){mt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ft(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...n,me:s,it:i,locals:new Map(n.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of r)try{await this.execute(t,c)}catch(t){if(es(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),mt("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,r){mt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(t,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(t=>this.isElement(t))),mt(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){ft("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",o);const a=this.enhanceContext(n);for(const t of e)try{await this.execute(t,a)}catch(t){if(es(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing change handler command:",t)}}});n.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,n),mt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const r=e.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return mt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}class os{constructor(t){this.observer=null,this.initialized=!1,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const r=qe(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function as(t,e,r,n,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?n.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),f=!1,d=r.length-1;d>=0;d--){var p={};for(var m in n)p[m]="access"===m?{}:n[m];for(var m in n.access)p.access[m]=n.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,r[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,n.name,h),f=!0}function cs(t,e,r){for(var n=arguments.length>2,s=0;e.length>s;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function ls(t,e,r){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function us(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function hs(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),r=t.indexOf("=");if(-1===r)return{name:t.trim()};const n=t.slice(0,r).trim();let s=t.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function fs(t,e){for(const r of t)e(r);return t}function ds(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function ps(t,e,r){const n=t.hasAttribute(e);void 0!==r?n&&t.getAttribute(e)===r?t.removeAttribute(e):t.setAttribute(e,r):n?t.removeAttribute(e):t.setAttribute(e,"")}function ms(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&vs(r)?[r]:[]}function ys(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function vs(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!ys(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function gs(t,e){return t.map(t=>{if(ys(t)){const r=function(t){const e=t.trim(),r=e.match(/^\{(.+)\}$/);return r?r[1].trim():e}(t),n=e.locals.get(r)??e.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const bs=Symbol("command:name"),Es=Symbol("command:category"),ws=Symbol("command:metadata");function xs(t){return function(e,r){const n=e;n[bs]=t.name,n[Es]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function ks(t){return function(e,r){const n=e,s=n[Es];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??!1,hasBody:t.hasBody??!1,version:"1.0.0",compatibility:t.compatibility};n[ws]=i,Object.defineProperty(e,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function As(t){return()=>new t}function Ss(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function Cs(t,e){if(Ss(t))return t;if(!t){const t=e.me;if(!t)throw Error("No target element - provide explicit target or ensure context.me is set");return Ts(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return Ts(e.me)}if("it"===r){if(!Ss(e.it))throw Error('Context reference "it" is not an HTMLElement');return e.it}if("you"===r){if(!e.you)throw Error('Context reference "you" is not available');return Ts(e.you)}const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!Ss(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function Ns(t,e){if(Array.isArray(t))return t.filter(Ss);if(t instanceof NodeList)return Array.from(t).filter(Ss);if(Ss(t))return[t];if(!t){const t=e.me;return t&&Ss(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&Ss(e.me)?[e.me]:[];if("it"===r)return Ss(e.it)?[e.it]:[];if("you"===r)return e.you&&Ss(e.you)?[e.you]:[];const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let t=r;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.querySelectorAll(t);return Array.from(e).filter(Ss)}}return[]}function Ts(t){if(Ss(t))return t;throw Error("Value is not an HTMLElement")}function Os(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!Ss(e.me))throw Error("context.me is not an HTMLElement");return e.me;case"its":case"it":if(!e.it)throw Error('No "it" value in context');if(!Ss(e.it))throw Error("context.it is not an HTMLElement");return e.it;case"your":case"you":if(!e.you)throw Error('No "you" element in context');if(!Ss(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const Ls=["on","from","to","in","with","at"];async function $s(t,e,r,n,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!Ls.includes(e.name.toLowerCase())})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Ss(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const t of o){const s=await e.evaluate(t,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(Ss(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(Ss);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(Ss);a.push(...t)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const n=e.querySelectorAll(t),i=Array.from(n).filter(Ss);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Ss(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function Rs(t){return"string"==typeof t&&t.trim().startsWith("*")}function Is(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const r=e.substring(1).trim();return r?{property:r}:null}(t);if(!e)return null;const r=e.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function js(t,e,r){t.style.setProperty(e,r)}const Ms=["dialog","details","summary","select"];function Ds(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Ps(t,e,r){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const r=Ds(t);return"string"==typeof r&&r.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return!1;const r=Ds(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:Ds(t),extractedFromNode:!0}:function(t){if(!t||"object"!=typeof t)return!1;if("attributeAccess"===t.type)return!0;if("selector"===t.type||"cssSelector"===t.type){const e=Ds(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:Ds(n)),extractedFromNode:!0}:{value:await e.evaluate(t,r),extractedFromNode:!1};var n}class Vs{async resolveTargets(t,e,r,n){return $s(t,e,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Ps(t,e,r)}parseClassNames(t){return ms(t)}isAttribute(t){return us(t.trim())}isCSSProperty(t){return Rs(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>Ss(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Bs=(()=>{let t,e,r=[ks({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"]}),xs({name:"add",category:"dom"})],n=[],s=Vs;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(t){const e=hs(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,r,t.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);r.length>0&&ds(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,fs(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":!function(t,e){ds(t,Object.entries(e),(t,[e,r])=>{t.style.setProperty(e,r)})}(t.targets,t.styles)}var r,n}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.value)return!1}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return!1;if(Array.isArray(e.styles))return!1;const r=e.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(t=>"string"==typeof t))return!1}return!0}},ls(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const Fs=As(Bs);function _s(t){return!!t.parentNode&&(t.remove(),!0)}let qs=(()=>{let t,e,r=[ks({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"]}),xs({name:"remove",category:"dom"})],n=[],s=Vs;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if(Ss(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&Ss(n[0]))return{type:"element",targets:n.filter(t=>Ss(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:hs(s).name,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);r.length>0&&ds(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,fs(t.targets,t=>{t.removeAttribute(r)});break;case"styles":!function(t,e){ds(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)_s(e)}var r}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return!1;return!0}},ls(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const Hs=As(qs);function Us(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function zs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Us(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Ws(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Js(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&ps(t,r)}}function Zs(t,e,r,n){const s=Js(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Gs(t,e,r,n){const s=Js(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:!0}),()=>{t.removeEventListener(n,i)}}function Xs(t,e,r){if(e.startsWith("@")){const n=e.substring(1);return void(!1===r?t.removeAttribute(n):t.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(e){case"textContent":return void(t.textContent=n);case"innerHTML":return void(t.innerHTML=n);case"innerText":return void(t.innerText=n);case"id":return void(t.id=n);case"className":return void(t.className=n);case"value":return void("value"in t&&(t.value=n));case"checked":return void("checked"in t&&(t.checked=!!r))}if(e.includes(".")){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++)if(s=s[n[t]],null==s)return;return void(s[n[n.length-1]]=r)}if(e.includes("-")||e in t.style)t.style.setProperty(e,n);else try{t[e]=r}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const Ys=/^the\s+(.+?)\s+of\s+(.+)$/i,Ks=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function Qs(t){return"string"==typeof t&&Ys.test(t)}function ti(t,e){const r=t.match(Ys);if(!r)return null;try{return{element:Cs(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function ei(t,e,r){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,r){const n=t.property?.name;if(!n)return null;let s=await e.evaluate(t.target,r);return Array.isArray(s)&&(s=s[0]),Ss(s)?{element:s,property:n}:null}(t,e,r);if(function(t){return!(!t||"object"!=typeof t)&&"propertyAccess"===t.type&&("string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name)}(t))return async function(t,e,r){const n="string"==typeof t.property?t.property:t.property?.name;if(!n)return null;let s=await e.evaluate(t.object,r);return Array.isArray(s)&&(s=s[0]),Ss(s)?{element:s,property:n}:null}(t,e,r);const n=t;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const t=n.object,s=n.property;let i=await e.evaluate(t,r);if(Array.isArray(i)&&(i=i[0]),!Ss(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function ri(t,e){const{element:r,property:n}=t;n.startsWith("*")?js(r,n.substring(1),e+""):Xs(r,n,e)}async function ni(t,e,r){let n,s;if(t?.for){const s=await e.evaluate(t.for,r);n="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const r=Us(t);return r?r.milliseconds:e}return e}(s):void 0}if(t?.until){const n=await e.evaluate(t.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}function si(t,e){const r=e?.name,n=function(t){if(!t||"object"!=typeof t)return!1;if("identifier"!==t.type)return!1;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.includes(e)}(e)}(e);if(Ss(t)||Array.isArray(t)&&t.every(t=>Ss(t)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const ii=As((()=>{let t,e,r=[ks({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),xs({name:"toggle",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("toggle command requires an argument");const n=t.args[0],s=n?.name;if("between"===s&&t.args.length>=4){const{duration:n,untilEvent:s}=await ni(t.modifiers,e,r),i=await e.evaluate(t.args[1],r),o=await e.evaluate(t.args[3],r),a=[];for(let e=4;t.args.length>e;e++){const r=t.args[e]?.name;"on"!==r&&"from"!==r&&a.push(t.args[e])}const c={filterPrepositions:!0,fallbackModifierKey:"on"},l=await $s(a,e,r,"toggle",c,t.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:n,untilEvent:s}}const i=await ei(n,e,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let s=n.value,i=1;if("*"===s&&t.args.length>1&&"identifier"===t.args[1].type&&(s="*"+t.args[1].name,i=2),"*"===s&&t.modifiers?.on){const n=t.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){s="*"+n;const{duration:i,untilEvent:o}=await ni(t.modifiers,e,r),a=Is(s);if(a){const t=r.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Is(s);if(o){const{duration:n,untilEvent:s}=await ni(t.modifiers,e,r),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await $s(t.args.slice(i),e,r,"toggle",a,t.modifiers),duration:n,untilEvent:s}}}const{duration:o,untilEvent:a}=await ni(t.modifiers,e,r),{value:c}=await Ps(n,e,r);if(Qs(c)){const t=ti(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=si(c,n),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=hs(u);return{type:"attribute",name:n,value:s,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=Is(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(Ss(c))s=[c];else if(Array.isArray(c)&&c.every(t=>Ss(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>Ss(t))}else s=await $s([n],e,r,"toggle",h,t.modifiers);const i=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(t,e,r,n){if(e?.as){const t=await r.evaluate(e.as,n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await r.evaluate(t[1],n);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await r.evaluate(t[2],n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Ws(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:ms(u),targets:s,duration:o,untilEvent:a}}default:{const n=ms(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}}}async execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);if(0===r.length)return[...t.targets];if(ds(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&Zs(e,"class",r[0],t.duration),t.untilEvent&&Gs(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,fs(t.targets,t=>{ps(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Zs(e,"attribute",t.name,t.duration),t.untilEvent&&Gs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return fs(t.targets,e=>function(t,e){const r=window.getComputedStyle(t);switch(e){case"display":"none"===r.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=r.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:r}=t;return r.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,r.substring(1)):rr(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||Ks.has(n)||Ks.has(n.toLowerCase())){const r=!e;return ri(t,r),r}if("number"==typeof e){const r=0===e?1:0;return ri(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(ri(t,s),s):(t.element[n]=e,ri(t,""),"")}ri(t,!e)}(t.target),[t.target.element];case"dialog":return fs(t.targets,e=>{return n=t.mode,void((r=e).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return fs(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return fs(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const r=e.classList.contains(t.classA),n=e.classList.contains(t.classB);r?(e.classList.remove(t.classA),e.classList.add(t.classB)):n?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Zs(e,"class",t.classA,t.duration),t.untilEvent&&Gs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},ls(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());class oi{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await $s(t.args,e,r,n)}}(t,e,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>Ss(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const r=t.dataset.originalDisplay;void 0!==r?(t.style.display=r||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let ai=(()=>{let t,e,r=[ks({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),xs({name:"show",category:"dom"})],n=[],s=oi;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const r=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,r)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>Ss(t))&&"string"==typeof e.defaultDisplay}},ls(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const ci=As(ai);let li=(()=>{let t,e,r=[ks({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),xs({name:"hide",category:"dom"})],n=[],s=oi;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>Ss(t))}},ls(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const ui=As(li);const hi=As((()=>{let t,e,r=[ks({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"]}),xs({name:"put",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("put requires arguments");const n=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const r=t.args[e],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i)if(t.modifiers.into||t.modifiers.before||t.modifiers.after){const e=t.modifiers.into?"into":t.modifiers.before?"before":"after";a=t.args[0],o=e,c=t.modifiers[e]}else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2];else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,r),u=this.mapPosition(o);let h,f,d=null;if(c){const t=n(c),s=await ei(c,e,r);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,n=c.property;if("selector"===t?.type?d=t.value:"identifier"===t?.type&&(d=t.name),d&&n?.name)h=n.name;else{const t=await e.evaluate(c,r);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Qs(t)){const e=ti(t,r);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const n=await e.evaluate(c,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,r),n=this.resolveEvaluatedAsElements(t);if(n)return{value:l,targets:n,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,r),position:u,memberPath:h}}async execute(t,e){const{value:r,targets:n,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,r),e[o]=r,void Object.assign(e,{it:r});if(i)for(const t of n)this.setProperty(t,i,r);else for(const t of n){const e=this.parseValue(r);this.insertContent(t,e,s)}return n}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!Ss(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>Ss(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return Ss(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(Ss(e)){const n=e;switch(r){case"beforebegin":t.parentElement?.insertBefore(n,t);break;case"afterbegin":t.insertBefore(n,t.firstChild);break;case"beforeend":t.appendChild(n);break;case"afterend":t.parentElement?.insertBefore(n,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e);else Ss(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(Ss(t))return[t];if(Array.isArray(t)){const e=t.filter(Ss);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(Ss);return e.length>0?e:null}return null}looksLikeCss(t){return!!t&&(!!/^[#.\[]/.test(t)||(!(!/[>+~\s]/.test(t)||1>=t.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase())))}setProperty(t,e,r){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++){if(!s[n[t]])throw Error(`Property path "${e}" does not exist`);s=s[n[t]]}s[n[n.length-1]]=r}},ls(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());function fi(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function di(t,e,r){return"global"===r&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==r&&e.locals&&e.locals.has(t)?e.locals.get(t):e.globals&&e.globals.has(t)?e.globals.get(t):e.variables&&e.variables.has(t)?e.variables.get(t):"global"===r&&e.locals&&e.locals.has(t)?e.locals.get(t):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function pi(t,e,r,n){if("global"===n)return r.globals.set(t,e),void("undefined"!=typeof window&&(window[t]=e));if(r.locals&&r.locals.has(t))r.locals.set(t,e);else{if(r.globals&&r.globals.has(t))return r.globals.set(t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(!r.variables||!r.variables.has(t))return"undefined"!=typeof window&&t in window?(window[t]=e,void r.globals.set(t,e)):void r.locals.set(t,e);r.variables.set(t,e)}}function mi(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:di(t,e)}const yi=As((()=>{let t,e,r=[ks({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"]}),xs({name:"make",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){const n=t.args.length>0?await e.evaluate(t.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const s=void 0!==t.modifiers.an?"an":"a",i=await async function(t,e,r){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const n=[];for(const s of t.args)n.push(await e.evaluate(s,r));return n}const n=await e.evaluate(t,r);return Array.isArray(n)?n:[n]}(t.modifiers.from,e,r),o=await async function(t,e,r){if(!t)return;if("symbol"===t.type&&"string"==typeof t.name)return t.name;const n=await e.evaluate(t,r);return"string"==typeof n?n:n+""}(t.modifiers.called,e,r);return{article:s,expression:n,constructorArgs:i,variableName:o}}async execute(t,e){const{expression:r,constructorArgs:n=[],variableName:s}=t,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(t){const e=t.slice(1,-2);let r="div",n=e;const s=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=e.slice(s[0].length));const i=document.createElement(r),o=n.split(/(?=[.#])/);for(const t of o)if(t.startsWith("#")){const e=t.slice(1);e&&(i.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&i.classList.add(e)}return i}(r):function(t,e,r){if(Ss(t))return t;const n=t+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===e.length?new s:new s(...e)}(r,n,e);return Object.assign(e,{it:i}),s&&pi(s,i,e),i}},ls(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),vi=As((()=>{let t,e,r=[ks({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"]}),xs({name:"set",category:"data"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("set command requires a target");const n=t.args[0],s=n?.name||n?.value,i=await ei(n,e,r);if(i){const n=await this.extractValue(t,e,r);if(i.property.startsWith("*")){const t=i.property.substring(1);return{type:"style",element:i.element,property:t,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,t,e,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await e.evaluate(n,r):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(Ss(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(t.modifiers.on,e,r)};if(Qs(o)){const n=ti(o,r);if(n){const s=await this.extractValue(t,e,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,t,e,r)}if("string"==typeof o&&Rs(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,r),property:n,value:s+""}}if("string"==typeof o&&us(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"attribute",element:await this.resolveElement(t.modifiers.on,e,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=Os(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(Ss(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&Ss(o[0])){const n=await this.extractValue(t,e,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal"+("memberExpression"===n?.type||"propertyAccess"===n?.type?` (a property chain evaluated to ${null===o?"null":typeof o} — check that all intermediate objects exist)`:""));return{type:"variable",name:o,value:await this.extractValue(t,e,r)}}async execute(t,e){switch(t.type){case"variable":return e.locals.set(t.name,t.value),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":return t.element.setAttribute(t.name,t.value+""),Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Xs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return js(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[r,n]of Object.entries(t.properties))Xs(e,r,n);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,r,n){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=Os(t,n),o=await this.extractValue(e,r,n);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=await r.evaluate(o,n);if(null!=s&&"object"==typeof s){const o=a?await r.evaluate(t.property,n)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,value:await this.extractValue(e,r,n)}}}return null}async extractValue(t,e,r){if(t.modifiers.to)return e.evaluate(t.modifiers.to,r);const n=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(n>=0&&t.args.length>n+1)return e.evaluate(t.args[n+1],r);if(t.args.length>=2)return e.evaluate(t.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,r){return Cs(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return Ns(t?await e.evaluate(t,r):void 0,r)}async parseTheXofY(t,e,r,n){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=Cs(o,n),c=await this.extractValue(e,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return!1;const e=t;if(!e.type||"string"!=typeof e.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return!1;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Ss(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&Ss(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&Ss(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return!1}}},ls(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());let gi=(()=>{let t,e,r=[ks({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"]}),xs({name:"increment",category:"data"})],n=[];return e=class{async parseInput(t,e,r){const n="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",s=await async function(t,e,r,n){if(!t.args||0===t.args.length)throw Error(n+" command requires a target");const s=t.args[0];let i,o;const a=(c=s)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===a)i=s.name,s.scope&&(o=s.scope);else if("literal"===a)i=s.value;else{const t=await e.evaluate(s,r);i=Array.isArray(t)&&t.length>0?t[0]:t}let l=1,u=o;for(let n=1;t.args.length>n;n++){const s=t.args[n];if(s&&"literal"===s.type){const t=s.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(s&&"literal"!==s.type){const t=await e.evaluate(s,r);"number"==typeof t&&(l=t)}}return{target:i,amount:l,...u&&{scope:u}}}(t,e,r,n);return{...s,operation:n}}async execute(t,e){const{target:r,property:n,scope:s,amount:i=1,operation:o="increment"}=t,a=function(t,e,r,n){if("number"==typeof t)return t;if(Ss(t)){const r=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?fi(r.getAttribute(e)):fi(r[e]):fi(r.value||r.textContent)}return"string"==typeof t?"global"===r?fi(di(t,n,"global")):t.includes(".")?function(t,e){const r=t.split("."),n=r[1],s=mi(r[0],e);return s?fi(s[n]):0}(t,n):fi("me"===t&&n.me?n.me.value||0:"it"===t?n.it||0:"you"===t&&n.you?n.you.value||0:di(t,n)):fi(t)}(r,n,s,e);let c;if(isNaN(a))c=NaN;else{const t=isFinite(i)?i:1;c="increment"===o?a+t:a-t}return function(t,e,r,n,s){if(Ss(t)){const r=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?r.setAttribute(e,n+""):r[e]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof t){if("global"===r)return void pi(t,n,s,"global");if(t.includes("."))return void function(t,e,r){const n=t.split("."),s=n[1],i=mi(n[0],r);i&&(i[s]=e)}(t,n,s);if("me"===t&&s.me)return void(s.me.value=n);if("it"===t)return void Object.assign(s,{it:n});if("you"===t&&s.you)return void(s.you.value=n);pi(t,n,s)}}(r,n,s,c,e),Object.assign(e,{it:c}),c}},ls(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})();const bi=As(gi),Ei=As(gi);function wi(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e||"false"!==e&&("null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0)}let xi=(()=>{let t,e,r=[ks({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),xs({name:"trigger",category:"event"})],n=[];return e=class{async parseInput(t,e,r){const n="send"===t.commandName?.toLowerCase()?"send":"trigger",s=n;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,r))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,r);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,r,s);else{const n=t.args.findIndex((t,e)=>{if(0===e)return!1;const r=t.name||t.value;return"on"===r||"to"===r});if(-1!==n&&t.args.length-1>n){const i=t.args.slice(n+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,r),mode:n}}async execute(t,e){const r=function(t,e,r={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(r);e.it=r}async resolveTargets(t,e,r,n){const s=[];for(const n of t){const t=await e.evaluate(n,r);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&r.me)s.push(r.me);else if("you"===t&&r.you)s.push(r.you);else if("it"===t&&r.it)s.push(r.it);else if(Ss(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(Ss));else if(Array.isArray(t))s.push(...t.filter(Ss));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(Ss));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(t,e,r){if(!t?.length)return;if(1===t.length){const n=t[0];if("objectLiteral"!==n?.type)return await e.evaluate(n,r)}const n={};for(const s of t){const t=await e.evaluate(s,r);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":",2);n[e.trim()]=wi(r.trim())}}else Object.assign(n,t)}return Object.keys(n).length?n:void 0}async parseEventOptions(t,e,r){const n={bubbles:!0,cancelable:!0,composed:!1},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return n;for(const i of t.slice(s+1)){const t=await e.evaluate(i,r);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?n.bubbles=!0:"nobubbles"===e?n.bubbles=!1:"cancelable"===e?n.cancelable=!0:"nocancelable"===e?n.cancelable=!1:"composed"===e&&(n.composed=!0)}}return n}},ls(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})();const ki=As(xi),Ai=As(xi);function Si(t,e,r){return t?new Promise(r=>{const n=function(r,n){let i=!1;return r=>{i||(i=!0,t.removeEventListener(e,s),n(r))}}(0,r),s=t=>{n({event:t,timedOut:!1,cancelled:!1})};t.addEventListener(e,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function Ci(t){return new Promise(e=>setTimeout(e,t))}const Ni=As((()=>{let t,e,r=[ks({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"]}),xs({name:"wait",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,r);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r);const n=t.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,t.args[1],e,r):this.parseTimeWait(t.args[0],e,r)}async execute(t,e){const r=Date.now();if("time"===t.type)return await Ci(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await Si(n,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const r of t.destructure)r in s&&e.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in n&&e.locals.set(t,n[t]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(t,e,r){return{type:"time",milliseconds:zs(await e.evaluate(t,r))}}async parseEventWait(t,e,r,n){const s=await r.evaluate(t,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await r.evaluate(e,n);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=n.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,r,n){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",r=[];for(const n of t.properties){const t=n.key?.name||n.key?.value;"name"===t&&n.value?e=n.value.value||"":"args"===t&&n.value?.elements&&(r=n.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:r})}}let i;if(e){const t=await r.evaluate(e,n);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,r){const n=[];t.modifiers.for?n.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r)):t.args[0]&&n.push(await this.parseTimeWait(t.args[0],e,r));const s=await e.evaluate(t.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const t of i)try{n.push({type:"time",milliseconds:zs(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);n.push(e?{type:"event",eventName:e[1],target:r.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(t,e){const r=t.map(t=>"time"===t.type?Ci(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Si(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},ls(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Ti=new Map;const Oi=As((()=>{let t,e,r=[ks({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),xs({name:"fetch",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(t.args[0],e,r),responseType:this.parseResponseType(t.modifiers.as),options:await this.parseRequestOptions(t.modifiers.with,e,r)}}async execute(t,e){const r=Date.now(),{url:n,responseType:s,options:i}=t,o=new AbortController;let a;e.me&&(a=()=>o.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:o.signal},l=Ti.get(s);if(l?.accept){const t=new Headers(c.headers);t.has("Accept")||t.set("Accept",l.accept),c.headers=t}if(e.me){const t={...c,sender:e.me,headers:c.headers||{}};this.dispatchEvent(e.me,"fetch:beforeRequest",t),c.headers=t.headers}let u;i.timeout&&(u=setTimeout(()=>o.abort(),i.timeout));try{let t=await fetch(n,c);if(e.me){const r={response:t};this.dispatchEvent(e.me,"fetch:afterResponse",r),t=r.response}const i=await this.handleResponse(t,s,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:i});const o={status:t.status,statusText:t.statusText,headers:t.headers,data:i,url:t.url,duration:Date.now()-r};return Object.assign(e,{it:i}),o}catch(t){if(e.me&&this.dispatchEvent(e.me,"fetch:error",{reason:t instanceof Error?t.message:t+"",error:t}),t instanceof Error&&"AbortError"===t.name)throw Error("Fetch aborted for "+n);throw Error(`Fetch failed for ${n}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,r){const n=await e.evaluate(t,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(t){if(!t)return"text";if(("identifier"===t.type||"expression"===t.type)&&t.name){const e=t.name.toLowerCase();if("object"===e)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(e))return"arraybuffer"===e?"arrayBuffer":e;if(Ti.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,r){if(!t)return{};const n=await e.evaluate(t,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[r,n]of Object.entries(t))e.set(r,n+"");return e}parseBody(t){return null==t?null:t instanceof FormData||t instanceof Blob||t instanceof ArrayBuffer||t instanceof URLSearchParams||"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):t+""}async handleResponse(t,e,r){switch(e){case"response":return t;case"json":return t.json();case"html":return this.parseHTML(await t.text());case"blob":return t.blob();case"arrayBuffer":return t.arrayBuffer();case"text":return t.text();default:{const n=Ti.get(e);return n?n.handler(t,r):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),r=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>r.appendChild(t.cloneNode(!0))),1===r.childNodes.length&&Ss(r.firstChild)?r.firstChild:r}dispatchEvent(t,e,r){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:!0,cancelable:!0}))}},ls(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Li=As((()=>{let t,e,r=[ks({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),xs({name:"go",category:"navigation"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{args:[]}}async execute(t,e){const{args:r}=t;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,e),type:"url"}:{result:await this.scrollToElement(r,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const r=t.findIndex(t=>"url"===t),n=t[r+1];if(!n)throw Error('URL is required after "url" keyword');const s="string"==typeof n?n:n+"",i=t.includes("new")&&t.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const t=window.open(s,"_blank");t?.focus&&t.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const r=this.parseScrollPosition(t),n=this.parseScrollTarget(t),s=this.parseScrollOffset(t),i=!t.includes("instantly"),o=this.resolveScrollTarget(n,e);if(!o)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const t=i?"smooth":"instant",e=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==s){o.scrollIntoView?.({behavior:t,block:e,inline:n});const{x:i,y:a}=this.calculateScrollPosition(o,r,s);window.scrollTo?.({left:i,top:a,behavior:t})}else o.scrollIntoView?.({behavior:t,block:e,inline:n})}return o}mapVerticalPosition(t){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[t]||"start"}mapHorizontalPosition(t){return{left:"start",center:"center",right:"end",nearest:"nearest"}[t]||"nearest"}parseScrollPosition(t){const e={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let s=!1,i=!1;for(const o of t)"string"==typeof o&&(r.includes(o)?(e.vertical=o,s=!0):n.includes(o)&&(e.horizontal=o,i=!0));return i&&!s&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let r=t[e+1];return"the"===r&&t.length>e+2&&(r=t[e+2]),r}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!r.includes(e)&&(e.startsWith("#")||e.startsWith(".")||e.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(e)))return e;return"body"}parseScrollOffset(t){for(let e=0;t.length>e;e++){const r=t[e];if("string"==typeof r){const t=r.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===r||"-"===r)&&t.length>e+1){const n=t[e+1],s="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(s))return"-"===r?-s:s}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const r="string"==typeof t?t:t+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&Ss(e.me))return e.me;if("it"===r&&Ss(e.it))return e.it;if("you"===r&&Ss(e.you))return e.you;const n=di(r,e);if(Ss(n))return n;if("undefined"!=typeof document)try{const t=document.querySelector(r);if(t)return t}catch{try{const t=document.getElementsByTagName(r);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,r){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const n=t.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=s,l=i;switch(e.horizontal){case"left":c=n.left+s;break;case"center":c=n.left+s+n.width/2-o/2;break;case"right":c=n.right+s-o}switch(e.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-a/2+r;break;case"bottom":l=n.bottom+i-a+r}return{x:Math.max(0,c),y:Math.max(0,l)}}},ls(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),$i=As((()=>{let t,e,r=[ks({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"]}),xs({name:"log",category:"utility"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{values:[]}}async execute(t,e){const r="undefined"!=typeof window?window.console:console;0===t.values.length?r.log():r.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}},ls(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Ri=function(t,e){const r=new Xn(e.expressionEvaluator);for(const e of t)r.register(e);return new is({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Fs(),Hs(),ii(),ci(),ui(),hi(),yi(),vi(),bi(),Ei(),Ai(),ki(),Ni(),Oi(),Li(),$i()],{expressionEvaluator:new class extends hr{constructor(t){super();for(const e of t)this.registerCategory(e)}}([Mr,wn,Wn,$n,Bn])}),Ii={parse:t=>je(t),execute:async(t,e)=>{const r=function(t){if(!t)return qe();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=qe(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),n=je(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Ri.execute(n.node,r)}},ji=function(t){return new os(t)}(Ii),Mi={runtime:Ii,parse:t=>Ii.parse(t),execute:async(t,e)=>Ii.execute(t,e),createContext:qe,attributeProcessor:ji,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","set","increment","decrement","send","trigger","wait","fetch","go","log"],eval:async(t,e)=>Ii.execute(t,e),init:()=>{ji.init()}};return"undefined"!=typeof window&&(window.hyperfixi=Mi,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ji.init()}):ji.init()),Mi}();
1
+ var hyperfixi=function(){"use strict";const t="then",e="else",r="end",n="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",v="behavior",g="global",b="the",E="start",w=new Set(["add","append","async","beep","break","call","continue","copy","decrement","default","exit","fetch","for","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","return","send","set","settle","show","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),A="at end of",S=["into","before","after","at",k,A,"at the start of","at the end of"],C=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),N=t=>w.has(t.toLowerCase()),T=t=>x.has(t.toLowerCase()),O=t=>C.has(t.toLowerCase()),L=t=>$.has(t.toLowerCase()),$=new Set(["hsl","hsla","rgb","rgba","hwb","lab","lch","oklch","oklab","color","color-mix","calc","min","max","clamp","var","url","linear-gradient","radial-gradient","conic-gradient","repeating-linear-gradient","repeating-radial-gradient","repeating-conic-gradient"]),R=new Set(["me","it","you","result","my","its","your"]),I=new Set(["and","or","not","no"]),j=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","is a","is an","is not a","is not an","contains","has","have","does not contain","include","includes","does not include","match","matches","exists","does not exist","is empty","is not empty","is in","is not in","equals","in","is equal to","is really equal to","is not equal to","is not really equal to","is greater than","is less than","is greater than or equal to","is less than or equal to","really equals"]),M=new Set(["click","dblclick","mousedown","mouseup","mouseover","mouseout","mousemove","mouseenter","mouseleave","focus","blur","change","input","submit","reset","select","load","unload","resize","scroll","keydown","keyup","keypress","touchstart","touchend","touchmove","touchcancel","drag","drop","dragover","dragenter","dragleave","cut","copy","paste","toggle"]),D=new Set(["on","init","behavior","def","if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","as","then","when","where","after","before","by","at","between","async","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]);var P;!function(t){t.IDENTIFIER="identifier",t.STRING="string",t.NUMBER="number",t.SELECTOR="selector",t.OPERATOR="operator",t.TIME="time",t.TEMPLATE="template",t.COMMENT="comment",t.SYMBOL="symbol",t.UNKNOWN="unknown"}(P||(P={}));const V=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function F(t,e=1){const r=t.position+e;return t.input.length>r?t.input[r]:""}function _(t){const e=t.input[t.position];return t.position++,"\n"===e?(t.line++,t.column=1):"\r"===e?("\n"===(t.input.length>t.position?t.input[t.position]:"")&&t.position++,t.line++,t.column=1):t.column++,e}function q(t){const e=t.input,r=e.length;for(;r>t.position;){const r=e[t.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;_(t)}}function H(t,e,r,n,s){const i=n??t.position-r.length,o=t.position;let a=t.column-r.length;if(void 0!==n){a=1;let e=-1;for(let r=0;n>r;r++)"\n"!==t.input[r]&&"\r"!==t.input[r]||(e=r);a=n-e}const c={kind:e,value:r,start:i,end:o,line:U(t,i),column:a};t.tokens.push(c)}function U(t,e){let r=1;for(let n=0;e>n&&t.input.length>n;n++){const e=t.input[n];"\n"===e?r++:"\r"===e&&(r++,t.input.length>n+1&&"\n"===t.input[n+1]&&n++)}return r}function z(t){const e=t.position;let r="";for(_(t),_(t);t.input.length>t.position&&"\n"!==t.input[t.position];)r+=_(t);H(t,P.COMMENT,"--"+r,e)}function W(t){const e=t.position,r=_(t);let n=r;for(;t.input.length>t.position;){const e=_(t);if(n+=e,e===r)break;"\\"===e&&t.input.length>t.position&&(n+=_(t))}H(t,P.STRING,n,e)}function J(t){const e=t.position;_(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){_(t);break}if("\\"===e){if(_(t),t.input.length>t.position){const e=_(t);switch(e){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=e}}}else r+=_(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-r.length}`);H(t,P.TEMPLATE,r,e)}function Z(t){const e=t.position;let r=_(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(r+=_(t);t.input.length>t.position;){const e=t.input[t.position];if(r+=_(t),"}"===e)break}H(t,P.SELECTOR,r,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if(!rt(e)&&"-"!==e&&"_"!==e&&":"!==e)break;r+=_(t)}H(t,P.SELECTOR,r,e)}}function G(t){const e=t.position;let r="";for(r+=_(t);t.input.length-1>t.position;){const e=t.input[t.position],n=t.input[t.position+1];if(r+=_(t),"/"===e&&">"===n){r+=_(t);break}}H(t,P.SELECTOR,r,e)}function X(t){const e=t.position;let r=_(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!rt(e)&&"_"!==e&&"-"!==e)break;r+=_(t)}H(t,P.SYMBOL,r,e)}function Y(t){const e=t.position;let r="";const n=t.input[t.position];if(("'"===n||"'"===n)&&"s"===F(t,1))return r="'s",_(t),_(t),void H(t,P.OPERATOR,r,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(r=i,_(t),_(t),_(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,_(t),_(t)):r=_(t),H(t,P.OPERATOR,r,e)}function K(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position&&"."===r[t.position]&&(t.position+1>=n||"."!==r[t.position+1]))for(s+=_(t);n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}if(n>t.position){const e=r[t.position];if("e"===e||"E"===e){const e=n>t.position+1?r[t.position+1]:"",i=n>t.position+2?r[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=_(t),"+"!==r[t.position]&&"-"!==r[t.position]||(s+=_(t));n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=_(t)}}}const i=t.position;let o="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=_(t)}B.has(o)?H(t,P.TIME,s+o,e):(t.position=i,H(t,P.NUMBER,s,e))}function Q(t){const e=t.position,r=t.input,n=r.length;let s="";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;s+=_(t)}const i=function(t,e,r){const n=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return!1;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===P.IDENTIFIER||i.kind===P.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}q(t);let o="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;o+=_(t)}if(o){const e=o.toLowerCase(),s=`${n} ${e}`,i=function(t,e,r,n){const s=e.toLowerCase(),i=r.toLowerCase();if("at"===s){const e=t.position;if("the"===i){q(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}const s=r.toLowerCase();if("start"===s||"end"===s){q(t);let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;e+=_(t)}if("of"===e.toLowerCase())return H(t,P.IDENTIFIER,`at the ${s} of`,n),!0}return t.position=e,!1}if("start"===i||"end"===i){q(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;r+=_(t)}return"of"===r.toLowerCase()?(H(t,P.IDENTIFIER,`at ${i} of`,n),!0):(t.position=e,!1)}}return!1}(t,n,e,r);if(i)return!0;const a=function(t,e,r){const n=t.position;let s=`${e} ${r}`,i=t.position;const o=[e,r];for(;8>o.length&&(q(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const r=t.input[t.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;e+=_(t)}if(!e)break;o.push(e.toLowerCase());const r=o.join(" ");j.has(r)&&(s=r,i=t.position)}return j.has(s)&&s!==`${e} ${r}`?(t.position=i,s):(t.position=n,null)}(t,n,e);if(a)return H(t,P.OPERATOR,a,r),!0;if(j.has(s))return H(t,P.OPERATOR,s,r),!0}return j.has(n)?(t.position=s,H(t,P.OPERATOR,e,r),!0):(t.position=s,!1)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||I.has(e)||V.has(t)||V.has(e)||j.has(e)?P.OPERATOR:P.IDENTIFIER}(s);H(t,o,s,e)}function tt(t){const e=t.position,r=t.input,n=r.length;_(t);let s="$";for(;n>t.position;){const e=r[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=_(t)}H(t,P.IDENTIFIER,s,e)}function et(t){return/[a-zA-Z]/.test(t)}function rt(t){return/[a-zA-Z0-9]/.test(t)}function nt(t){let e=t.position+1,r=!1;for(;t.input.length>e;){const n=t.input[e];if("/"===n&&t.input.length>e+1&&">"===t.input[e+1])return r;if(rt(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n)r=!0,e++;else{if(" "!==n&&"\t"!==n)return!1;e++}if(e-t.position>50)return!1}return!1}function st(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const it=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return!0}catch{}return!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG}(),ot=it,at=it,ct=it,lt=it,ut=it,ht=(...t)=>{ot&&console.log("🔧",...t)},ft=(...t)=>{at&&console.log("🎯",...t)},dt=(...t)=>{ct&&console.log("📝",...t)},pt=(...t)=>{lt&&console.log("🔍",...t)},mt=(...t)=>{ut&&console.log("🚀",...t)};let yt=!1,vt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(yt=!0,vt=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let gt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class bt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??!1}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(bt.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const r=t.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)||!!/\*[a-zA-Z]/.test(t)}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:!1,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:!1,confidence:0,errors:[`Semantic parsing not available for language '${this.language}'`]};try{const n=this.analyzer.analyze(t,this.language),s=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:n.confidence,command:n.command?.name,threshold:this.confidenceThreshold});const i=n.confidence>=this.confidenceThreshold&&!!n.command,o=!i&&n.confidence>0;if(yt){const e={};if(n.command?.roles)for(const[t,r]of n.command.roles)e[t]=r.value;const a={input:t.substring(0,100),language:this.language,confidence:n.confidence,threshold:this.confidenceThreshold,semanticSuccess:i,fallbackTriggered:o,command:n.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:n.errors,timestamp:Date.now(),duration:s};!function(t){if(!yt)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",r=Math.round(100*t.confidence),n=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${r}% (threshold: ${n}%)`),t.command&&console.log("Command: "+t.command),t.roles&&Object.keys(t.roles).length>0&&console.log("Roles:",t.roles),t.duration&&console.log(`Duration: ${t.duration.toFixed(2)}ms`),t.errors?.length&&console.log("Errors:",t.errors),console.groupEnd(),vt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});vt.dispatchEvent(e)}}(a),r=a,gt.totalParses++,r.semanticSuccess?gt.semanticSuccesses++:r.fallbackTriggered?gt.semanticFallbacks++:gt.traditionalParses++,gt.confidenceHistory.push(r.confidence),gt.confidenceHistory.length>100&&gt.confidenceHistory.shift(),gt.averageConfidence=gt.confidenceHistory.reduce((t,e)=>t+e,0)/gt.confidenceHistory.length}return i?{success:!0,node:this.buildCommandNode(n),confidence:n.confidence,tokensConsumed:n.tokensConsumed}:{success:!1,confidence:n.confidence,tokensConsumed:n.tokensConsumed,errors:n.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var r}buildCommandNode(t){const{command:e}=t;if(!e)throw Error("Cannot build command node without command data");if("repeat"===e.name)return this.buildRepeatCommandNode(e);if("for"===e.name)return this.buildRepeatCommandNode(e);if("set"===e.name)return this.buildSetCommandNode(e);if("if"===e.name||"unless"===e.name)return this.buildIfCommandNode(e);const r=[],n={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":r.push(i);break;case"destination":"put"===e.name?n.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?n.to=i:n.on=i;break;case"source":"fetch"===e.name?r.push(i):n.from=i;break;case"quantity":n.by=i;break;case"duration":n.over=i;break;case"responseType":n.as=i;break;case"method":n.method=i;break;case"style":n.with=i;break;case"condition":n.when=i;break;default:n[t]=i}}return{type:"command",name:e.name,args:r,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildRepeatCommandNode(t){const e=[],r={},n=t.roles.get("loopType");n&&e.push({type:"identifier",name:n.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("patient");"for"==(n?n.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(r.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],r=t.roles.get("destination");if(r)if("property-path"===r.type){const t=r;e.push({type:"possessiveExpression",object:this.semanticValueToExpression(t.object),property:this.createPropertyNode(t.property),start:0,end:0,line:1,column:0})}else e.push(this.semanticValueToExpression(r));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const n=t.roles.get("patient");return n&&e.push(this.semanticValueToExpression(n)),{type:"command",name:"set",args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}createPropertyNode(t){return t.startsWith("*")?{type:"cssProperty",name:t.substring(1),start:0,end:0,line:1,column:0}:{type:"identifier",name:t,start:0,end:0,line:1,column:0}}buildIfCommandNode(t){const e=[],r=t.roles.get("condition");return r&&e.push(this.semanticValueToExpression(r)),{type:"command",name:t.name,args:e,isBlocking:!1,start:0,end:0,line:1,column:0}}semanticValueToExpression(t){switch(t.type){case"selector":return{type:"selector",value:t.value,start:0,end:0,line:1,column:0};case"reference":return{type:"identifier",name:t.value,start:0,end:0,line:1,column:0};case"literal":return"string"==typeof t.value&&t.value.includes("${")&&t.value.includes("}")?{type:"templateLiteral",value:t.value,start:0,end:0,line:1,column:0}:{type:"literal",value:t.value,raw:t.raw??t.value,start:0,end:0,line:1,column:0};case"property-path":{const e=t;return{type:"memberExpression",object:this.semanticValueToExpression(e.object),property:{type:"identifier",name:e.property,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0}}default:return this.parseExpressionString(t.raw||"")}}parseExpressionString(t){let e=0;const r=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},n=()=>{r();const n=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(n,e)},s=()=>{const n=[];if(e++,r(),")"!==t[e])for(n.push(i()),r();","===t[e];)e++,r(),n.push(i()),r();return")"===t[e]&&e++,n},i=()=>{r();const i=n();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){r();const i=t[e];if("."===i){e++;const t=n();t&&(o={type:"memberExpression",object:o,property:{type:"identifier",name:t,start:0,end:0,line:1,column:0},computed:!1,start:0,end:0,line:1,column:0})}else{if("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}function Et(t){return t.kind===P.IDENTIFIER&&w.has(t.value.toLowerCase())}function wt(t){return t.kind===P.IDENTIFIER&&D.has(t.value.toLowerCase())}function xt(t){return t.kind===P.IDENTIFIER&&M.has(t.value.toLowerCase())}function kt(t){return t.kind===P.IDENTIFIER&&R.has(t.value.toLowerCase())}function At(t){return j.has(t.value.toLowerCase())}function St(t){return t.kind===P.IDENTIFIER}function Ct(t){return t.kind===P.SELECTOR}function Nt(t){return t.kind===P.SELECTOR&&!t.value.startsWith("<")}function Tt(t){return t.kind===P.STRING||t.kind===P.NUMBER||t.kind===P.TEMPLATE}function Ot(t){return t.kind===P.IDENTIFIER}function Lt(t){return t.kind===P.TIME}function $t(t){return t.kind===P.SYMBOL}function Rt(t){return t.kind===P.COMMENT}function It(t){if(t.kind!==P.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(w.has(e)||D.has(e)||M.has(e)||R.has(e))}function jt(t){return t.kind===P.STRING}function Mt(t){return t.kind===P.NUMBER}function Dt(t){if(t.kind===P.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function Pt(t){return t.kind===P.TEMPLATE}function Vt(t){return t.kind===P.SELECTOR&&t.value.startsWith("<")}function Bt(t){return t.kind===P.SELECTOR&&t.value.startsWith("#")}function Ft(t){return t.kind===P.SELECTOR&&t.value.startsWith(".")}function _t(t){return t.kind===P.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function qt(t){if(t.kind!==P.OPERATOR)return!1;const e=t.value.toLowerCase();return!I.has(e)&&!j.has(e)}function Ht(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function Ut(t,e,r){return{type:"literal",value:t,raw:e,start:r.start,end:r.end,line:r.line,column:r.column}}function zt(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Wt(t,e,r,n){return{type:"binaryExpression",operator:t,left:e,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function Jt(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Zt(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Gt(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Xt(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Yt(t,e,r){return{type:"propertyOfExpression",property:t,target:e,start:r.start,end:r.end,line:r.line,column:r.column}}function Kt(t,e,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...r&&{source:r}}],start:t.start,end:t.end,line:t.line,column:t.column}}bt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const Qt=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function te(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const ee=[t,n,e,r];function re(t,e=[]){if(t.isAtEnd())return!0;for(const e of ee)if(t.check(e))return!0;for(const r of e)if(t.check(r))return!0;return!!t.checkIsCommand()}function ne(t,e=[]){if(!re(t,e))return t.parseExpression()}function se(t,e,r){return!!t.check(e)&&(t.advance(),r.push(t.createIdentifier(e)),!0)}function ie(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function oe(t,e){return!!t.check(e)&&(t.advance(),!0)}class ae{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new ae(t.value);return e.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},e}static fromIdentifier(t){const e=new ae(t.name);return void 0!==t.start&&(e.startPos={start:t.start,end:t.end??0,line:t.line??1,column:t.column??1}),e}static named(t){return new ae(t)}withArgs(...t){return this.args.push(...t),this}withBody(t){return this.body=t,this}withImplicitTarget(t){return this.implicitTarget=t,this}withModifier(t,e){return this.modifiers||(this.modifiers={}),this.modifiers[t]=e,this}withModifiers(t){return this.modifiers={...this.modifiers,...t},this}withName(t){return this.name=t,this}withOriginalCommand(t){return this.originalCmd=t,this}blocking(t=!0){return this.isBlocking=t,this}startingAt(t){return this.startPos={start:t.start??0,end:t.end??0,line:t.line??1,column:t.column??1},this}endingAt(t){return this.endPos={start:t.start??this.startPos?.start??0,end:t.end,line:t.line??this.startPos?.line??1,column:t.column??this.startPos?.column??1},this}build(){const t={type:"command",name:this.name,args:this.args,isBlocking:this.isBlocking,start:this.startPos?.start??0,end:this.endPos?.end??this.startPos?.end??0,line:this.startPos?.line??1,column:this.startPos?.column??1};return this.body&&(t.body=this.body),this.implicitTarget&&(t.implicitTarget=this.implicitTarget),this.modifiers&&(t.modifiers=this.modifiers),this.originalCmd&&(t.originalCommand=this.originalCmd),t}clone(){const t=new ae(this.name);return t.args=[...this.args],t.body=this.body?[...this.body]:void 0,t.implicitTarget=this.implicitTarget,t.isBlocking=this.isBlocking,t.modifiers=this.modifiers?{...this.modifiers}:void 0,t.originalCmd=this.originalCmd,t.startPos=this.startPos?{...this.startPos}:void 0,t.endPos=this.endPos?{...this.endPos}:void 0,t}}function ce(t,e){const r=[];let n="";const s=t.peek().start||0,i=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(n=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),n+=":",t.checkIdentifierLike()&&(n+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const r=t.savePosition();let n;if(t.checkIdentifierLike()){const e=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=e):t.restorePosition(r)}const s=t.parseExpression();if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:s}],start:s.start,end:s.end,line:s.line,column:s.column}:s),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),r.push({type:"functionCall",name:n,args:e,start:s,end:t.getPosition().end,line:i,column:o})}else r.push({type:"string",value:n,start:s,end:t.getPosition().end,line:i,column:o})}const a=[...r];if(t.check("on")||t.check("to")){const e=t.advance().value;for(a.push(t.createIdentifier(e));!re(t);)a.push(t.parsePrimary())}return ae.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function le(t,e){const r=[];if(t.check(b)){const e=t.advance();if(r.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();r.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ue(n,s){const i=[];let o=!1;const a=n.savePosition();for(let e=0;500>e&&!n.isAtEnd();e++){const e=n.peek();if(e.value===t){o=!0;break}if(e.value===r||e.value===v||"def"===e.value||e.value===m)break;n.advance()}n.restorePosition(a);let c=!1;if(!o){const t=n.savePosition(),i=s.line,o=100;for(;!n.isAtEnd()&&o>n.current-t;){const t=n.peek(),s=t.value?.toLowerCase();if(s===v||"def"===s||s===m)break;if(s===e||s===r){t.line===i&&(c=!0);break}if((n.checkIsCommand()||n.isCommand(s))&&void 0!==t.line&&t.line!==i){c=!0;break}n.advance()}n.restorePosition(t)}const l=o||c;let u;if(l)u=n.parseExpression();else{const e=[],r=20;let i=0;for(;!n.isAtEnd()&&!n.checkIsCommand()&&!n.isCommand(n.peek().value)&&!n.check(t)&&r>i;){const t=n.savePosition();e.push(n.parseLogicalAnd()),n.savePosition()===t&&n.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&n.advance();const t=[];for(;!n.isAtEnd()&&!n.check(e)&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}if(0===t.length&&n.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(Jt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}));let a=!1;if(n.check(e))if(n.advance(),n.check("if")){const t=n.peek();n.advance();const e=ue(n,t);i.push(Jt([e],{start:t.start,end:n.getPosition().end,line:t.line,column:t.column})),a=!0}else{const t=[];for(;!n.isAtEnd()&&!n.check(r)&&(n.checkIsCommand()||n.isCommand(n.peek().value));){n.advance();const e=n.parseCommand();e&&t.push(e)}i.push(Jt(t,{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}a||n.consume(r,"Expected 'end' after if block")}else{if(!n.checkIsCommand()&&!n.isCommand(n.peek().value))throw Error("Expected command after if condition in single-line form");{n.advance();const t=n.parseCommand();i.push(Jt([t],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return ae.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function he(t,e){const r=[],n={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(r.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();r.push({type:"identifier",name:"*"+e.value,start:e.start-1,end:e.end,line:e.line,column:e.column})}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();r.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();n.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const s=ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function fe(t,e){const r=[],n=ne(t,[f]);n&&r.push(n),se(t,f,r);const s=ne(t);return s&&r.push(s),ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function de(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=ne(t,[n]);i&&r.push(i),se(t,n,r);const o=ne(t,[f,m,s]);if(o&&r.push(o),ie(t,[f,m],r)){const e=ne(t);e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=ne(t,[f,m]);if(i&&r.push(i),ie(t,[f,m],r)){const e=ne(t);e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function pe(t,e){const n=t.parseExpression();if(!n)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!S.includes(s.value))return t.addError(`Expected operation keyword (${S.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=A:"at"===i&&(t.check(E)||t.check(b)?(oe(t,b),t.check(E)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(r)&&(t.advance(),t.check(p)&&(t.advance(),i=A)));const a=t.parseExpression();return a?ae.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const me=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function ye(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(g)&&!t.check("local"))return null;const e=t.advance(),r=t.advance();return{type:"identifier",name:r.value,scope:e.value,start:e.start,end:r.end}}(s)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const r=t.parseExpression();if(!r)return t.restorePosition(e),null;if("binaryExpression"===r.type&&r.operator===p){const t=r.left,e=r.right;return Yt(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(h)?r:(t.restorePosition(e),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(n)||s.check(e)||s.check(r));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],r=i[3];return{expression:Yt(zt(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===r.type?"idSelector":"cssSelector",value:t(r,"value")||t(r,"name")||"",start:r.start??0,end:r.end??0,line:r.line,column:r.column},{start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(h)),l&&u.push(l),ae.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function ve(t,e){const r=[];for(;!re(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ge(t){if(t.isAtEnd())return!0;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||re(t)}function be(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Ee(t){const e=[],r=t.getPosition();do{if(!t.checkIdentifierLike())break;const r=t.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};t.consume(":","Expected ':' after property name in fetch named arguments");const s=t.parsePrimary();s&&e.push({key:n,value:s})}while(t.match(",")&&!t.isAtEnd());const n=t.getPosition();return{type:"objectLiteral",properties:e,start:r.start,end:n.end,line:r.line,column:r.column}}const we=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),xe=new Set([")","]","}",","]);function ke(...t){const e=new Map;for(const r of t)for(const[t,n]of r){const r=e.get(t);e.set(t,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}return e}function Ae(t,e){return{infix:{bp:[t,t+1],handler:e??((e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t+1),start:e.start}))}}}function Se(t,e){return{infix:{bp:[t+1,t],handler:(e,r,n)=>({type:"binaryExpression",operator:r.value,left:e,right:n.parseExpr(t),start:e.start})}}}function Ce(t,e){return{prefix:{bp:t,handler:e??((e,r)=>({type:"unaryExpression",operator:e.value,operand:r.parseExpr(t),start:e.start}))}}}const Ne=new Map([["or",Ae(10)],["||",Ae(10)],["and",Ae(20)],["&&",Ae(20)],["==",Ae(30)],["!=",Ae(30)],["<",Ae(30)],[">",Ae(30)],["<=",Ae(30)],[">=",Ae(30)],["is",Ae(30)],["matches",Ae(30)],["contains",Ae(30)],["+",{...Ae(40),...Ce(80)}],["-",{...Ae(40),...Ce(80)}],["*",Ae(50)],["/",Ae(50)],["%",Ae(50)],["mod",Ae(50)],["^",Se(60)],["**",Se(60)],["as",Ae(70,(t,e,r)=>({type:"asExpression",expression:t,targetType:r.parseExpr(71),start:t.start}))],["not",Ce(80)],["!",Ce(80)],["no",Ce(80)]]),Te=new Map([["first",Ce(85,(t,e)=>({type:"positionalExpression",position:"first",operand:e.parseExpr(85),start:t.start}))],["last",Ce(85,(t,e)=>({type:"positionalExpression",position:"last",operand:e.parseExpr(85),start:t.start}))]]),Oe=new Map([[".",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"propertyAccess",object:t,property:r.advance().value,start:t.start})}}],["?.",{infix:{bp:[90,91],handler:(t,e,r)=>({type:"optionalChain",object:t,property:r.advance().value,start:t.start})}}],["'s",{infix:{bp:[95,96],handler:(t,e,r)=>({type:"possessiveExpression",object:t,property:r.advance().value,start:t.start})}}]]),Le=new Map([["===",Ae(30)],["!==",Ae(30)],["is not",Ae(30)],["is a",Ae(30)],["is an",Ae(30)],["is not a",Ae(30)],["is not an",Ae(30)],["is in",Ae(30)],["is not in",Ae(30)],["has",Ae(30)],["have",Ae(30)],["match",Ae(30)],["include",Ae(30)],["includes",Ae(30)],["equals",Ae(30)],["does not contain",Ae(30)],["does not include",Ae(30)],["in",Ae(30)],["of",Ae(30)],["really",Ae(30)],["exists",{prefix:{bp:80,handler:(t,e)=>({type:"unaryExpression",operator:t.value,operand:e.parseExpr(80),start:t.start})},infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:!1,start:t.start})}}],["some",Ce(80)]]),$e=new Map([["=",Se(5)]]);ke(Ne,Te,Oe);const Re=ke(Ne,Le,$e);class Ie{constructor(t,e,r){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new bt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=r||t.map(t=>t.value).join(" ")}resolveKeyword(t){return this.keywordResolver?this.keywordResolver.resolve(t)??t:t}addWarning(t){this.warnings.push(t)}parse(){this.prattCache.clear();const t=this.parseInternal();return this.errors.length>0&&(t.errors=[...this.errors]),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const t=[];for(;this.check("behavior");){this.advance();const e=this.parseBehaviorDefinition();if(e&&t.push(e),this.error)break}return this.error?{success:!1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else if(this.check("init")){this.advance();const e=this.parseTopLevelInitBlock();e&&t.push(e)}else if(this.check("on")){this.advance();const e=this.parseEventHandler();e&&t.push(e)}else{if(!this.check("def"))break;{this.advance();const e=this.parseDefFeature();e&&t.push(e)}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const t=this.parseCommandSequence();if(t){if(!this.isAtEnd()&&this.check("on")){dt("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];dt(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){dt(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(dt("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),r++,dt(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),dt(`✅ PARSER: After parsing event handler, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd=${this.isAtEnd()}, check('on')=${this.check("on")}`),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return dt("⚠️ PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};dt("✅ PARSER: No more event handlers, at end of input");break}}return dt(`✅ PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const t=this.parseExpression();return this.error?{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error}:this.isAtEnd()?{success:!0,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings})}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(t){const e=`${this.current}:${t}`,r=this.prattCache.get(e);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=Ie.PRATT_TABLE.get(n.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek(),r=Ie.PRATT_TABLE.get(e.value);if(!r?.infix){if(we.has(e.value)||xe.has(e.value))break;break}const[n]=r.infix.bp;if(t>n)break;if("="===e.value&&this.tokens.length>this.current+1&&">"===this.tokens[this.current+1].value){if(this.advance(),this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpressionPratt(0)}catch{}return this.createErrorNode()}if("+"===e.value||"-"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("+"===t.value||"-"===t.value))return this.addError(`Invalid operator combination: ${e.value}${t.value}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ie.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return!e||we.has(e.value)||xe.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseAssignment(){let t=this.parseLogicalOr();if(this.match("=")){if(this.check(">")){if(this.advance(),this.addError('Arrow functions (=>) are not supported in hyperscript. Use "js ... end" blocks for JavaScript callbacks.'),!this.isAtEnd())try{this.parseExpression()}catch{}return this.createErrorNode()}const e=this.previous().value,r=this.parseAssignment();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalOr(){let t=this.parseLogicalAnd();for(;this.match("or");){const e=this.previous().value,r=this.parseLogicalAnd();t=this.createBinaryExpression(e,t,r)}return t}parseLogicalAnd(){let t=this.parseEquality();for(;this.match("and");){const e=this.previous().value,r=this.parseEquality();t=this.createBinaryExpression(e,t,r)}return t}parseEquality(){let t=this.parseComparison();for(;this.matchComparisonOperator()||this.match("is","match","matches","contains","include","includes","in","of","as","really");){const e=this.previous().value;if(Ie.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,!1);continue}const r=this.parseComparison();t=this.createBinaryExpression(e,t,r)}return t}parseComparison(){let t=this.parseAddition();for(;this.matchComparisonOperator();){const e=this.previous().value;if(Ie.POSTFIX_UNARY_OPERATORS.has(e)){t=this.createUnaryExpression(e,t,!1);continue}const r=this.parseAddition();t=this.createBinaryExpression(e,t,r)}return t}parseAddition(){let t=this.parseMultiplication();for(;this.match("+","-")||this.matchOperator("+")||this.matchOperator("-");){const e=this.previous().value;if(this.check("+")||this.check("-"))return this.addError(`Invalid operator combination: ${e}${this.peek().value}`),t;if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseMultiplication();t=this.createBinaryExpression(e,t,r)}return t}parseMultiplication(){let t=this.parseUnary();for(;this.match("*","/","%","mod");){const e=this.previous().value;if(this.check("*")||this.check("/")||this.check("%")||this.check("+")||this.check("-")){const r=this.peek().value;return this.addError("*"===e&&"*"===r?"Unexpected token: "+r:`Invalid operator combination: ${e}${r}`),t}if(this.isAtEnd())return this.addError(`Expected expression after '${e}' operator`),t;const r=this.parseUnary();t=this.createBinaryExpression(e,t,r)}return t}parseUnary(){if(this.match("not","no","exists","some","-","+")){const t=this.previous().value;if(this.isAtEnd())return this.addError(`Expected expression after '${t}' operator`),this.createErrorNode();const e=this.parseUnary();return this.createUnaryExpression(t,e,!0)}if(this.check("does")&&this.tokens.length>this.current+1&&"not"===this.tokens[this.current+1].value&&this.tokens.length>this.current+2&&"exist"===this.tokens[this.current+2].value){if(this.advance(),this.advance(),this.advance(),this.isAtEnd())return this.addError("Expected expression after 'does not exist' operator"),this.createErrorNode();const t=this.parseUnary();return this.createUnaryExpression("does not exist",t,!0)}return this.parseImplicitBinary()}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):N(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):O(t)}createCommandFromIdentifier(t){const e=[],r=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(r))return this.parseCompoundCommand(t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.checkIsCommand())&&(this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()||this.checkEvent()||this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkString()||this.checkNumber()||this.checkTimeExpression()||this.match("<"));)e.push(this.parsePrimary());return{type:"command",name:t.name,args:e,isBlocking:!1,...void 0!==t.start&&{start:t.start},end:this.getPosition().end,...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}isCompoundCommand(t){return T(t)}parseCompoundCommand(s){return function(s,i){switch(i.name.toLowerCase()){case"put":return pe(s,i);case"trigger":case"send":return ce(s,i);case"remove":return fe(s,i);case"toggle":return de(s,i);case"set":return ye(s,i);case"halt":return le(s,i);case"measure":return he(s,i);case"js":return function(t,e){const n=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&n.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const s=t.peek().start,i=function(t,e){const r=t.getInputSlice(e);if(!r)return e;let n=0;for(;r.length>n;){const t=r[n];if("'"!==t&&"’"!==t&&"‘"!==t)if('"'!==t)if("`"!==t)if("/"===t&&r.length>n+1&&"/"===r[n+1])for(n+=2;r.length>n&&"\n"!==r[n];)n++;else if("/"===t&&r.length>n+1&&"*"===r[n+1]){for(n+=2;r.length>n&&("*"!==r[n]||n+1>=r.length||"/"!==r[n+1]);)n++;n+=2}else{if(!("e"!==t&&"E"!==t||n+3>r.length||"end"!==r.slice(n,n+3).toLowerCase()||0!==n&&/[a-zA-Z0-9_]/.test(r[n-1])||r.length>n+3&&/[a-zA-Z0-9_]/.test(r[n+3])))return e+n;n++}else{for(n++;r.length>n&&"`"!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&'"'!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&r[n]!==t;)"\\"===r[n]&&n++,n++;n++}}return e+r.length}(t,s);for(;!t.isAtEnd()&&!t.check(r)&&t.peek().start<i;)t.advance();t.consume(r,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:n.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return ae.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(n))continue;if(s.check(t)||s.check(e)||s.check(r))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return ae.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"swap":case"morph":return function(t,e){console.log("[PARSER DEBUG] parseSwapCommand called");const r=[];let n=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const s=e.value.toLowerCase();me.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),r.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&r.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),r.push(t.createIdentifier("with"));const e=t.parseExpression();e&&r.push(e)}return ae.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return ve(s,i)}}(this.getContext(),s)}parsePutCommand(t){return pe(this.getContext(),t)}parseSetCommand(t){return ye(this.getContext(),t)}parseHaltCommand(t){return le(this.getContext(),t)}parseMeasureCommand(t){return he(this.getContext(),t)}parseTriggerCommand(t){return ce(this.getContext(),t)}parseCommandListUntilEnd(){const t=[];for(dt("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){dt("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let e=!1;const r=this.checkIsCommand(),n=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||n){dt(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(dt("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(dt("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(t){dt("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&dt("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){dt("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(dt("📍 After parsing command, current token:",this.peek().value);!(this.isAtEnd()||this.check("end")||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)dt("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))dt("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){dt("📍 No separator and no command, breaking. Current token:",this.peek().value);break}dt("✅ Next token is a command, continuing without separator")}}if(dt('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw dt('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return dt('✅ Found "end", consuming it'),this.advance(),dt("✅ parseCommandListUntilEnd: Successfully parsed",t.length,"commands"),t}parseRepeatCommand(t){return function(t,e){const r=[];let n="forever",h=null,p=null,m=null,v=null,g=null,E=null;if(t.check(s)){t.advance(),n=s;const e=t.peek();St(e)&&(g=e.value,t.advance()),t.check(u)&&(t.advance(),v=t.parseExpression())}else if(t.check(u))t.advance(),n=s,g="it",v=t.parseExpression();else if(t.check(i))t.advance(),n=i,m=t.parseExpression();else if(t.check(o))if(t.advance(),n=o,t.check(y)){t.advance(),n="until-event";const e=t.peek();if(dt("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!St(e)&&!xt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),dt("✅ Got event name:",h,"Next token:",t.peek().value),dt('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){dt('✅ Found "from", advancing...'),t.advance(),dt('📍 After consuming "from", current token:',t.peek().value),oe(t,b)&&dt('✅ Found "the", advancing...');const e=t.peek();dt("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),dt("✅ After parsePrimary, eventTarget:",p)}else dt('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),n=a):(E=t.parseExpression(),t.check(c)&&(t.advance(),n=c));let w=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),w=l)}else if(t.check(l)){t.advance();const e=t.peek();St(e)?(w=e.value,t.advance()):w=l}const x=t.parseCommandListUntilEnd();r.push({type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column});const k={start:e.start,end:e.end,line:e.line,column:e.column};return g&&r.push(Zt(g,k)),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push(Zt(h,k)),p&&r.push(p),w&&r.push(Zt(w,k)),r.push(Jt(x,{...k,end:k.end||0})),ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const r=[];let n=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!St(i))throw Error('Expected variable name after "for"');if(n=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();St(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();r.push({type:"identifier",name:"for",start:e.start,end:e.end,line:e.line,column:e.column});const c={start:e.start,end:e.end,line:e.line,column:e.column};return r.push(Zt(n,c)),r.push(s),o&&r.push(Zt(o,c)),r.push(Jt(a,{...c,end:c.end||0})),ae.from({...e,value:"repeat"}).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const r=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!re(t)){const n=t.parseExpression();return r.push(n),ae.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const n=[];do{const e=t.peek();if(!St(e))throw Error('Expected event name after "for"');const r=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!St(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(n.push({name:r,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),oe(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Xt(n.map(t=>Gt([{key:zt("name",i),value:Ut(t.name,`"${t.name}"`,i)},{key:zt("args",i),value:Xt(t.params.map(t=>Ut(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return ae.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const r=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=t.advance().value,s=t.previous();if(r.push(zt(n,{start:s.start,end:s.end,line:s.line,column:s.column})),t.check("(")){t.advance();const n=[];for(;!t.isAtEnd()&&!t.check(")");){const e=t.savePosition();let r;if(t.checkIdentifierLike()){const n=t.peek().value;t.advance(),t.check(":")?(t.advance(),r=n):t.restorePosition(e)}const s=t.parseExpression();if(n.push(void 0!==r?{name:r,value:s}:{value:s}),t.check(","))t.advance();else if(!t.check(")"))break}if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),n.length>0){const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Gt(n.map(t=>({key:t.name?zt(t.name,s):Ut("_positional","_positional",s),value:t.value})),s))}}return ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const r=[],n={};let s=null;const i=t.peek();if(St(i)||"*"===i.value){let e="";t.check("*")&&(e="*",t.advance());const r=function(t){if(!t.checkIdentifierLike())return"";let e=t.advance().value;for(;t.check("-")&&!t.isAtEnd();)e+="-",t.advance(),t.checkIdentifierLike()&&(e+=t.advance().value);return e}(t);r&&(e+=r,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(r.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(n.to=o,t.check("over")){t.advance();const e=t.parsePrimary();n.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();n.with=e}return ae.from(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const r=[];if(t.match("{"))r.push(t.parseCSSObjectLiteral());else{const e=ne(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=ne(t);e&&r.push(e)}return ae.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return ue(this.getContext(),t)}parseRemoveCommand(t){return fe(this.getContext(),t)}parseToggleCommand(t){return de(this.getContext(),t)}parseRegularCommand(t){return ve(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifier("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,!0)}else{if(!this.check("'s"))break;{let e;this.advance(),this.check("*")?(this.advance(),e="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value):e=$t(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&St(this.peek())){const t=this.advance().value;return this.createSelector("*"+t)}this.current=t}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const t=this.peek();return this.addError(`Binary operator '${t.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const t=parseFloat(this.previous().value);return this.createLiteral(t,this.previous().value)}if(this.matchString()){const t=this.previous().value;if(2>t.length||t.startsWith('"')&&!t.endsWith('"')||t.startsWith("'")&&!t.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const e=t.slice(1,-1),r=this.processEscapeSequences(e);return this.createLiteral(r,t)}if(this.matchTemplateLiteral()){const t=this.previous();return{type:"templateLiteral",value:t.value,start:t.start||0,end:t.end||0,line:t.line,column:t.column}}if(this.matchBoolean()){const t=this.previous().value;let e;switch(t){case"true":e=!0;break;case"false":e=!1;break;case"null":e=null;break;case"undefined":e=void 0;break;default:e="true"===t}return this.createLiteral(e,t)}if(this.matchTimeExpression()){const t=this.previous().value;return this.createLiteral(t,t)}if(this.matchQueryReference()){const t=this.previous().value.slice(1,-2).trim();return this.createSelector(t)}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(It)||this.matchPredicate(wt)||this.matchPredicate(kt)||this.matchPredicate(Et)||this.matchPredicate(xt))){const t=this.previous();if("new"===t.value)return this.parseConstructorCall();if("on"===t.value)return this.parseEventHandler();if("if"===t.value)return this.parseConditional();if("closest"===t.value||"first"===t.value||"last"===t.value||"previous"===t.value||"next"===t.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(t.value);if(this.check(".")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,r=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[r])}this.current=e}return this.createIdentifier(t.value)}return"my"!==t.value||this.check(".")?"its"!==t.value||this.check(".")?"your"!==t.value||this.check(".")?"the"===t.value?this.parseTheXofY():"values"===t.value&&this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(t.value):this.parseContextPropertyAccess("you"):this.parseContextPropertyAccess("it"):this.parseContextPropertyAccess("me")}if(this.match("$"))return this.parseDollarExpression();if($t(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}}return{type:"dollarExpression",expression:e,raw:`$${t.value}${this.previous().value||""}`,line:t.line,column:t.column-1}}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let t="";for(;!this.check("/")&&!this.isAtEnd();)t+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(t)}parseObjectLiteral(){const t=[],e=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column};do{let e;if(this.matchPredicate(It))e=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const t=this.previous().value,r=t.slice(1,-1);e=this.createLiteral(r,t)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(t.push({key:e,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCSSObjectLiteral(){const t=this.getPosition(),e=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(It))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const t=this.previous().value,e=t.slice(1,-1);r=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=!1,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();n.push(t.value),"$"===t.value&&this.check("{")&&(s=!0),"{"===t.value&&i++,"}"===t.value&&i--}const o=n.join(""),a=s?{type:"templateLiteral",value:o,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(o,o);if(e.push({key:r,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),r=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();if(this.advance(),this.check(")"))this.advance();else{let t=1;for(;t>0&&!this.isAtEnd();){const e=this.advance();"("===e.value&&t++,")"===e.value&&t--}}return{type:"callExpression",callee:{type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column},arguments:[],isConstructor:!0,start:t.start,end:this.previous().end,line:t.line,column:t.column}}parseTopLevelInitBlock(){const t=this.getPosition(),e=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseDefFeature(){const t=this.getPosition();let e="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:t.start,end:this.getPosition().end,line:t.line,column:t.column};for(e=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(e+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let r=e.value;return this.check(":")&&(this.advance(),r=`${r}:${this.advance().value}`),r}callExprToCommandNode(t,e){return{type:"command",name:t.callee.name,args:t.arguments,isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}}createPseudoCommandNode(t,e,r,n,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const r=t.callee.name,n=this.peek();if(!(Ie.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||It(n)&&!this.isCommand(n.value)||kt(n)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}}),Ie.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(r,t,s,i,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(dt("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return dt("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){dt("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[],e=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(e),dt("🔧 parseEventHandler: Parsed first event name: "+e);this.check("or");){this.advance(),dt("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),dt("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(dt("🔧 parseEventHandler: Total events parsed: "+t.join(", ")),this.registryIntegration){const e=t[0];if(this.registryIntegration.hasEventSource(e)){const t=this.registryIntegration.getEventSource(e);r=t?.name,dt(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),dt("🔧 parseEventHandler: Parsed event parameters: "+n.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=!0,dt("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=!0,dt("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=!0,dt("🔧 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),r=parseInt(e.value,10);if(isNaN(r))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=r,dt(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,dt(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else dt(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const r=this.advance(),n=(i=r.value).endsWith("ms")?parseInt(i,10):i.endsWith("seconds")||i.endsWith("s")?1e3*parseFloat(i):i.endsWith("minutes")?6e4*parseFloat(i):i.endsWith("hours")?36e5*parseFloat(i):i.endsWith("days")?864e5*parseFloat(i):parseInt(i,10);s[e]=n,dt(`🔧 parseEventHandler: Parsed '${t} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[e]=r,dt(`🔧 parseEventHandler: Parsed '${t} at ${r}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`)}var i;let o,a,c,l;if(Object.keys(s).length>0&&dt("🔧 parseEventHandler: Parsed modifiers:",s),this.match("[")&&(o=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();a=t.value,dt(`🔧 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,dt("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(dt("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),dt("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(dt(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(dt(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){dt("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())dt("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){dt("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const r=this.parseCommand();u.push(r);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(u.push(t),dt("✅ parseEventHandler: Parsed command, next token: "+(this.isAtEnd()?"END":this.peek().value)))}}else{if(!this.checkIdentifier())break;{const t=this.peek();if(this.isCommand(t.value)){const t=this.parseCommandWithErrorRecovery();t&&u.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){dt("⚠️ Expression parsing error, restoring error state:",t instanceof Error?t.message:t+""),this.error=e;break}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(u.push(e.node),e.targetFailed)continue}else{if(!t||"binaryExpression"!==t.type||" "!==t.operator)break;{const e=t;if(!e.left||"identifier"!==e.left.type||!this.isCommand(e.left.name))break;{const r={type:"command",name:e.left.name,args:[e.right],isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}};u.push(r)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const h=this.getPosition(),f={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...n.length>0&&{params:n},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:h.start,end:h.end,line:h.line,column:h.column};return dt(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),f}parseBehaviorDefinition(){const t=this.getPosition(),e=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(e)||this.addError(`Behavior name must start with uppercase letter (got "${e}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");r.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();It(t)?(r.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),r=n.has(e.value);this.checkIsCommand()&&!r||(t.push(e.value),i=e.value,this.advance())}}const o={type:"eventHandler",event:e,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...r.length>0&&{args:r},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,r=this.parseCommand();for(this.error&&this.error!==e&&(this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(dt("⚠️ parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)dt("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){dt('✅ parseCommandSequence: Found "on" token, stopping command sequence to allow event handler parsing');break}if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const e=this.peek(),r=this.getPosition(),n="Expected command, got: "+e.value;this.addError(n);const s=Kt(r,n,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return Qt.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return te(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!re(t,["catch","finally",...n.keywords])&&!te(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&te(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&te(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!te(t.peek(),n.keywords))break}const o=ae.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(dt(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(dt(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return dt("[Semantic] Error during semantic parse:",t),null}}getRemainingInput(){if(!this.originalInput)return this.tokens.slice(this.current>0?this.current-1:0).map(t=>t.value).join(" ");const t=this.current>0?this.tokens[this.current-1]:this.tokens[0];return t&&void 0!==t.start?this.originalInput.slice(t.start):this.originalInput}skipToCommandBoundary(){const t=["then","and","else","end"];for(;!this.isAtEnd();){const e=this.peek(),r=e.value.toLowerCase();if(t.includes(r))break;if(Et(e))break;this.advance()}}parseCommand(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const r={};let n=null;if(!t.isAtEnd()&&t.check("/")&&(n=function(t){const e=t.savePosition();let r="";for(;!t.isAtEnd()&&!ge(t);)r+=t.advance().value;return r&&"/"!==r?{type:"literal",value:r,raw:r,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(t)),n||(n=t.parsePrimary()),!n)return t.addError("fetch requires a URL"),ae.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(r.with=t.parsePrimary());for(let e=0;2>e&&!t.isAtEnd();e++)if(!t.check("as")||r.as){if(!t.check("with")||r.with)break;t.advance(),r.with=be(t)?Ee(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||oe(t,"a")||oe(t,"an"),r.as=t.parsePrimary();const s=ae.from(e).withArgs(n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),t);const r=this.parseMultiWordCommand(t,e);if(r)return r;const n=e.toLowerCase();if("repeat"===n)return this.parseRepeatCommand(t);if("for"===n)return this.parseForCommand(t);if("if"===n||"unless"===n)return this.parseIfCommand(t);if("wait"===n)return this.parseWaitCommand(t);if("install"===n)return this.parseInstallCommand(t);if("transition"===n)return this.parseTransitionCommand(t);if("add"===n)return this.parseAddCommand(t);if(this.isCompoundCommand(n))return this.parseCompoundCommand({type:"identifier",name:n,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||this.createErrorNode();const s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const r=e.value,n="increment"===r?"+":"-";let s=!1;t.check(g)&&(s=!0,t.advance());const i=t.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${r} command`);o=e}else o=Ut(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=Wt(n,i,o,c),u=[a,zt(h,c),l];return ae.from(e).withName("set").withArgs(...u).withOriginalCommand(r).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const r=s[s.length-1];if(!r||"identifier"!==r.type&&"keyword"!==r.type||!e.includes(r.name??r.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:!1,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}if(this.checkIdentifier()||this.checkKeyword()){const t=this.peek();if(this.isCommand(t.value)){const t=this.advance(),e=this.createIdentifier(t.value);return this.createCommandFromIdentifier(e)||e}}return this.parseExpression()}parseNavigationFunction(t){const e=[];if(this.match("of"))e.push(this.parseExpression());else{if(this.check("("))return this.finishCall(this.createIdentifier(t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||e.push(this.parsePrimary())}return this.createCallExpression(this.createIdentifier(t),e)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if("me"===t&&this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),!1);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const r="computed-"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(r),!1)}{if($t(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(t){const e=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(t,[this.createErrorNode()]);e.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===t.type){const e=t.name;L(e)&&dt(`💡 Tip: CSS functions like ${e}() should be quoted for clean parsing. Use '${e}(...)' or \`${e}(...)\` instead.`)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(t,e)}createLiteral(t,e){return Ut(t,e,this.getPosition())}createIdentifier(t){return zt(t,this.getPosition())}createBinaryExpression(t,e,r){return Wt(t,e,r,this.getPosition())}createUnaryExpression(t,e,r){return function(t,e,r,n){return{type:"unaryExpression",operator:t,argument:e,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createCallExpression(t,e){return function(t,e,r){return{type:"callExpression",callee:t,arguments:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createMemberExpression(t,e,r){return function(t,e,r,n){return{type:"memberExpression",object:t,property:e,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,r,this.getPosition())}createSelector(t){return function(t,e){return{type:"selector",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}(t,this.getPosition())}createPossessiveExpression(t,e){return function(t,e,r){return{type:"possessiveExpression",object:t,property:e,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,this.getPosition())}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(t=this.getPosition()).start,end:t.end,line:t.line,column:t.column};var t}processEscapeSequences(t){return t.replace(/\\(.)/g,(t,e)=>{switch(e){case"n":return"\n";case"t":return"\t";case"r":return"\r";case"b":return"\b";case"f":return"\f";case"v":return"\v";case"0":return"\0";case"\\":return"\\";case'"':return'"';case"'":return"'";default:return e}})}createProgramNode(t){return function(t){if(dt(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return dt("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return dt(`✅ createProgramNode: Returning single statement (type=${t[0].type})`),t[0];const e={type:"Program",statements:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1};return dt(`✅ createProgramNode: Returning Program node with ${t.length} statements, type=${e.type}`),e}(t)}match(...t){for(const e of t)if(this.check(e))return this.advance(),!0;return!1}matchOperator(t){if(this.isAtEnd())return!1;const e=this.peek();return!(!qt(e)||e.value!==t||(this.advance(),0))}check(t){if(this.isAtEnd())return!1;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return!this.isAtEnd()&&t(this.peek())}matchPredicate(t){return!!this.checkPredicate(t)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Nt)}matchSelector(){return this.matchPredicate(Nt)}checkAnySelector(){return this.checkPredicate(Ct)}checkLiteral(){return this.checkPredicate(Tt)}checkIdentifierLike(){return this.checkPredicate(St)}checkIsCommand(){return this.checkPredicate(Et)}checkCommandTerminator(){return this.checkPredicate(Ht)}checkReference(){return this.checkPredicate(Ot)}checkTimeExpression(){return this.checkPredicate(Lt)}checkEvent(){return this.checkPredicate(xt)}checkContextVar(){return this.checkPredicate(kt)}checkComment(){return this.checkPredicate(Rt)}checkIdentifier(){return this.checkPredicate(It)}checkKeyword(){return this.checkPredicate(wt)}checkString(){return this.checkPredicate(jt)}matchString(){return this.matchPredicate(jt)}checkNumber(){return this.checkPredicate(Mt)}matchNumber(){return this.matchPredicate(Mt)}checkBoolean(){return this.checkPredicate(Dt)}matchBoolean(){return this.matchPredicate(Dt)}checkTemplateLiteral(){return this.checkPredicate(Pt)}matchTemplateLiteral(){return this.matchPredicate(Pt)}checkQueryReference(){return this.checkPredicate(Vt)}matchQueryReference(){return this.matchPredicate(Vt)}checkIdSelector(){return this.checkPredicate(Bt)}checkClassSelector(){return this.checkPredicate(Ft)}checkCssSelector(){return this.checkPredicate(_t)}checkBasicOperator(){return this.checkPredicate(qt)}matchBasicOperator(){return this.matchPredicate(qt)}matchTimeExpression(){return this.matchPredicate(Lt)}matchIdentifierLike(){return this.matchPredicate(St)}matchComparisonOperator(){return this.matchPredicate(At)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(It,t)}consumeIdentifierLike(t){return this.consumePredicate(St,t)}consumeEvent(t){return this.consumePredicate(xt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let r=e.start||0,n=e.line||1,s=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;r=t.end||t.start||0,n=t.line||1,s=t.column||1,0===r&&this.current>0&&(r=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;r=t.start||0,n=t.line||1,s=t.column||1,0===r&&(r=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const r=this.tokens[e];if(r&&("+"===r.value||"-"===r.value)){t=r;break}}r=t.start||0,n=t.line||1,s=t.column||1}this.error={message:t,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},this.errors.push(this.error)}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const t=this.peek();if("then"===t.value||"end"===t.value||"on"===t.value)return;if(this.checkIsCommand()||this.isCommand(t.value)&&!this.isKeyword(t.value))return;dt("⚠️ synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();n.push(t.value)}this.consume("]","Expected ']' after attribute literal");const s="["+n.join("")+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:r}}const n=[];if(!this.check("]"))do{if(this.check("]"))break;n.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:n,start:t,end:this.previous().end,line:e,column:r}}getPosition(){const t=this.current>0?this.previous():this.peek();return{start:t.start||0,end:t.end||0,line:t.line||1,column:t.column||1}}getContext(){const t=this,e={tokens:this.tokens,advance:this.advance.bind(this),peek:this.peek.bind(this),previous:this.previous.bind(this),consume:this.consume.bind(this),check:this.check.bind(this),checkIdentifierLike:this.checkIdentifierLike.bind(this),checkSelector:this.checkSelector.bind(this),checkAnySelector:this.checkAnySelector.bind(this),checkLiteral:this.checkLiteral.bind(this),checkReference:this.checkReference.bind(this),checkTimeExpression:this.checkTimeExpression.bind(this),checkEvent:this.checkEvent.bind(this),checkIsCommand:this.checkIsCommand.bind(this),checkContextVar:this.checkContextVar.bind(this),match:this.match.bind(this),matchOperator:this.matchOperator.bind(this),isAtEnd:this.isAtEnd.bind(this),createIdentifier:this.createIdentifier.bind(this),createLiteral:this.createLiteral.bind(this),createSelector:this.createSelector.bind(this),createBinaryExpression:this.createBinaryExpression.bind(this),createUnaryExpression:this.createUnaryExpression.bind(this),createMemberExpression:this.createMemberExpression.bind(this),createPossessiveExpression:this.createPossessiveExpression.bind(this),createCallExpression:this.createCallExpression.bind(this),createErrorNode:this.createErrorNode.bind(this),createProgramNode:this.createProgramNode.bind(this),createCommandFromIdentifier:this.createCommandFromIdentifier.bind(this),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseCall:this.parseCall.bind(this),parseAssignment:this.parseAssignment.bind(this),parseLogicalOr:this.parseLogicalOr.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseEquality:this.parseEquality.bind(this),parseComparison:this.parseComparison.bind(this),parseAddition:this.parseAddition.bind(this),parseMultiplication:this.parseMultiplication.bind(this),parseImplicitBinary:this.parseImplicitBinary.bind(this),parseConditional:this.parseConditional.bind(this),parseConditionalBranch:this.parseConditionalBranch.bind(this),parseEventHandler:this.parseEventHandler.bind(this),parseBehaviorDefinition:this.parseBehaviorDefinition.bind(this),parseNavigationFunction:this.parseNavigationFunction.bind(this),parseMyPropertyAccess:this.parseMyPropertyAccess.bind(this),parseDollarExpression:this.parseDollarExpression.bind(this),parseHyperscriptSelector:this.parseHyperscriptSelector.bind(this),parseAttributeOrArrayLiteral:this.parseAttributeOrArrayLiteral.bind(this),parseObjectLiteral:this.parseObjectLiteral.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),getPosition:this.getPosition.bind(this),addError:this.addError.bind(this),addWarning:this.addWarning.bind(this),isCommand:this.isCommand.bind(this),isCompoundCommand:this.isCompoundCommand.bind(this),isKeyword:this.isKeyword.bind(this),getMultiWordPattern:this.getMultiWordPattern.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>t.current,restorePosition:e=>{t.current=e},peekAt:e=>{const r=t.current+e;return r>=0&&t.tokens.length>r?t.tokens[r]:null},getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:!0,configurable:!0}),e}}function je(t,e){const r=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const r=t.length;for(;r>e.position&&(q(e),r>e.position);){const r=t[e.position];if("-"!==r||"-"!==F(e,1))if('"'!==r){if("'"===r||"'"===r){const t=F(e,1),r=e.tokens[e.tokens.length-1];if("s"!==t||!r||r.kind!==P.IDENTIFIER&&r.kind!==P.SELECTOR&&"]"!==r.value&&")"!==r.value&&"}"!==r.value)W(e);else{const t=e.position;_(e),_(e),H(e,P.OPERATOR,"'s",t)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===F(e,1)){const t=e.position;_(e),_(e),H(e,P.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],r=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),n=t&&t.kind===P.IDENTIFIER&&w.has(t.value.toLowerCase()),s=t&&t.kind===P.IDENTIFIER&&r.has(t.value.toLowerCase());if((!t||t.kind===P.OPERATOR&&")"!==t.value&&"]"!==t.value||n||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(et(F(e))||"{"===F(e))){Z(e);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const t=e.tokens[e.tokens.length-1],r=t&&t.kind===P.IDENTIFIER&&M.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==P.IDENTIFIER&&")"!==t.value&&"]"!==t.value||r)&&r?(H(e,P.SYMBOL,"["),_(e)):(H(e,P.OPERATOR,"["),_(e));continue}if("]"!==r){if("$"===r){const t=F(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){tt(e);continue}}st(r)?Y(e):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(H(e,P.UNKNOWN,r),_(e)):Q(e):K(e)}else H(e,P.OPERATOR,"]"),_(e)}else H(e,P.OPERATOR,"}"),_(e);else H(e,P.OPERATOR,"{"),_(e);else X(e)}else Z(e);else nt(e)?G(e):Y(e);else J(e)}else W(e);else z(e)}return e.tokens}(t);return new Ie(r,e,t).parse()}Ie.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),Ie.PRATT_TABLE=Re,Ie.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Me{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(t,e){this.unregister(t),this.hooks.set(t,e),e.beforeExecute&&this.beforeExecuteHooks.push(e.beforeExecute),e.afterExecute&&this.afterExecuteHooks.push(e.afterExecute),e.onError&&this.onErrorHooks.push(e.onError),e.interceptCommand&&this.interceptCommandHooks.push(e.interceptCommand)}unregister(t){const e=this.hooks.get(t);if(!e)return!1;if(e.beforeExecute){const t=this.beforeExecuteHooks.indexOf(e.beforeExecute);t>-1&&this.beforeExecuteHooks.splice(t,1)}if(e.afterExecute){const t=this.afterExecuteHooks.indexOf(e.afterExecute);t>-1&&this.afterExecuteHooks.splice(t,1)}if(e.onError){const t=this.onErrorHooks.indexOf(e.onError);t>-1&&this.onErrorHooks.splice(t,1)}if(e.interceptCommand){const t=this.interceptCommandHooks.indexOf(e.interceptCommand);t>-1&&this.interceptCommandHooks.splice(t,1)}return this.hooks.delete(t)}has(t){return this.hooks.has(t)}async runBeforeExecute(t){for(const e of this.beforeExecuteHooks)await e(t)}async runAfterExecute(t,e){for(const r of this.afterExecuteHooks)await r(t,e)}async runOnError(t,e){let r=e;for(const e of this.onErrorHooks){const n=await e(t,r);n instanceof Error&&(r=n)}return r}shouldIntercept(t,e){for(const r of this.interceptCommandHooks)if(r(t,e))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function De(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Pe(t){return{ok:!0,value:t}}function Ve(t){return{ok:!1,error:t}}function Be(t){return!0===t.ok}class Fe{constructor(t){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=t?.debug??!1}registerListener(t,e,r,n,s){this.addCleanup(t,{type:"listener",target:e,eventName:r,cleanup:()=>{e.removeEventListener(r,n,s),this.debugMode&&mt(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&mt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&mt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&mt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,r){this.addCleanup(t,{type:"custom",cleanup:e,description:r||"Custom cleanup"})}registerGlobal(t,e="custom",r){this.globalCleanups.push({type:e,cleanup:t,description:r||"Global cleanup"}),this.debugMode&&mt("CleanupRegistry: Registered global cleanup: "+(r||e))}addCleanup(t,e){const r=this.elementCleanups.get(t);r?r.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&mt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let r=0;for(const t of e){try{t.cleanup(),r++}catch(t){this.debugMode&&mt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&mt(`CleanupRegistry: Cleaned up ${r} resources for element`),r}cleanupElementTree(t){let e=this.cleanupElement(t);const r=t.querySelectorAll("*");for(const t of r)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&mt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&mt(`CleanupRegistry: Cleaned up ${t} global resources`),t}cleanupAll(){return this.cleanupGlobal()}hasCleanups(t){const e=this.elementCleanups.get(t);return void 0!==e&&e.length>0}getCleanupCount(t){const e=this.elementCleanups.get(t);return e?.length??0}getStats(){let t=0,e=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}const _e=new Map;function qe(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||_e,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class He{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const r=t.toLowerCase();this.sources.has(r)&&console.warn("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(r,e)}unregister(t){const e=t.toLowerCase(),r=this.sources.get(e);if(r){for(const[t,r]of this.subscriptions.entries())r.source===e&&(r.unsubscribe(),this.subscriptions.delete(t));return r.destroy?.(),this.sources.delete(e)}return!1}get(t){return this.sources.get(t.toLowerCase())}has(t){return this.sources.has(t.toLowerCase())}subscribe(t,e,r){const n=this.get(t);if(!n)return void console.warn("[EventSourceRegistry] Unknown event source: "+t);n.initialize?.();const s=n.subscribe(e,r);return this.subscriptions.set(s.id,s),s}unsubscribe(t){const e=this.subscriptions.get(t);return!!e&&(e.unsubscribe(),this.subscriptions.delete(t))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(t){for(const[e,r]of this.sources.entries())if(r.supports?.(t)??r.supportedEvents?.includes(t))return e}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const t of this.subscriptions.values())t.unsubscribe();this.subscriptions.clear();for(const t of this.sources.values())t.destroy?.();this.sources.clear()}}class Ue{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,r){const n=t.toLowerCase();this.providers.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:e)}registerGlobal(t,e,r){const n=t.toLowerCase();this.globalProviders.set(n,"function"==typeof e?{name:n,provide:e,cache:r?.cache??!0,description:r?.description,dependencies:r?.dependencies}:e)}unregister(t){return this.providers.delete(t.toLowerCase())}unregisterGlobal(t){return this.globalProviders.delete(t.toLowerCase())}get(t){const e=t.toLowerCase();return this.providers.get(e)??this.globalProviders.get(e)}has(t){const e=t.toLowerCase();return this.providers.has(e)||this.globalProviders.has(e)}async resolve(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);if(n.dependencies)for(const t of n.dependencies)await this.resolve(t,e,r);const i=await n.provide(e);return n.cache&&r&&r.set(s,i),i}resolveSync(t,e,r){const n=this.get(t);if(!n)return;const s="__provider_"+n.name;if(n.cache&&r?.has(s))return r.get(s);const i=n.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return n.cache&&r&&r.set(s,i),i}enhance(t){const e=this,r=new Map;return new Proxy(t,{get(t,n,s){if("string"==typeof n&&e.get(n))try{return e.resolveSync(n,t,r)}catch{return e.resolve(n,t,r)}return Reflect.get(t,n,s)},has:(t,r)=>!("string"!=typeof r||!e.has(r))||Reflect.has(t,r)})}async resolveAll(t){const e=new Map,r={},n=[...this.globalProviders.entries(),...this.providers.entries()];for(const[s,i]of n)try{r[s]=await this.resolve(s,t,e)}catch(t){console.warn(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),r[s]=void 0}return r}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const ze=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...t},this.registerBuiltinTypes()}register(t){this.types.has(t.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${t.name}'`),this.types.set(t.name,t)}get(t){return this.types.get(t)}has(t){return this.types.has(t)}getTypeNames(){return Array.from(this.types.keys())}inferType(t){for(const[e,r]of this.types)if(r.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),r=this.types.get(e);return r?.hyperscriptType??"unknown"}coerce(t,e,r){const n=this.types.get(e);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(n.isType(t))return t;if(this.config.cacheCoercions){const r=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(t),i=n.coerceFrom?.[s];if(i){const n=i(t,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(t,e){const r=this.types.get(e);if(!r)return!1;if(r.isType(t))return!0;const n=this.inferType(t);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(t,e){const r=this.types.get(e);return r&&(t===e||r.coerceFrom?.[t])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:t=>"string"==typeof t,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:t=>t+"",Boolean:t=>t+"",Null:()=>"",Undefined:()=>"",Array:t=>Array.isArray(t)?t.join(", "):null,Object:t=>{try{return JSON.stringify(t)}catch{return t+""}},Element:t=>t instanceof Element?t.textContent??t.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:t=>"number"==typeof t&&!isNaN(t),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:t=>{const e=parseFloat(t);return isNaN(e)?null:e},Boolean:t=>t?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:t=>"boolean"==typeof t,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e||"false"!==e&&"no"!==e&&"0"!==e&&""!==e&&e.length>0},Number:t=>0!==t,Null:()=>!1,Undefined:()=>!1,Array:t=>!!Array.isArray(t)&&t.length>0,Element:t=>t instanceof Element,ElementList:t=>Array.isArray(t)&&t.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:t=>t instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(t,e)=>{const r=t;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:t=>Array.isArray(t)&&t.length>0?t[0]:null,NodeList:t=>t.length>0?t[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:t=>Array.isArray(t)&&t.length>0&&t.every(t=>t instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:t=>t instanceof Element?[t]:[],NodeList:t=>Array.from(t),String:t=>{try{return Array.from(document.querySelectorAll(t))}catch{return[]}},Array:t=>{const e=t;return e.every(t=>t instanceof Element)?e:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:t=>Array.isArray(t),defaultValue:[],description:"Array of values",coerceFrom:{String:t=>{const e=t;try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map(t=>t.trim())},ElementList:t=>t,NodeList:t=>Array.from(t),Object:t=>Object.values(t)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:t=>!("object"!=typeof t||null===t||Array.isArray(t)||t instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:t=>{try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e}catch{}return null},Array:t=>{const e={};return t.forEach((t,r)=>{e[r+""]=t}),e}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:t=>null===t,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:t=>void 0===t,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:t=>"function"==typeof t,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:t=>t instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:t=>t instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:t=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:t=>!0,defaultValue:null,description:"Unknown/any value type"})}};function We(t){const e=ze.get("String");return e?e.isType(t):"string"==typeof t}function Je(t){const e=ze.get("Number");return e?e.isType(t):"number"==typeof t}function Ze(t){const e=ze.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ge(t){const e=ze.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Xe(t){const e=ze.get("Function");return e?e.isType(t):"function"==typeof t}function Ye(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Ke(t){return t instanceof Element}const Qe=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function tr(t,e){return Qe.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const er={id:t=>t.id,classname:t=>t.className,class:t=>t.className,tagname:t=>t.tagName.toLowerCase(),innertext:t=>t.textContent?.trim(),innerHTML:t=>t.innerHTML,outerhtml:t=>t.outerHTML,value:t=>function(t){if(null===t||"object"!=typeof t||!("tagName"in t))return!1;const e=t.tagName;return"INPUT"===e||"SELECT"===e||"TEXTAREA"===e}(t)?t.value:void 0,checked:t=>function(t){return null!==t&&"object"==typeof t&&"tagName"in t&&"INPUT"===t.tagName}(t)?t.checked:void 0,disabled:t=>"disabled"in t?t.disabled:void 0,selected:t=>function(t){return null!=t&&"object"==typeof t&&"tagName"in t&&"OPTION"===t.tagName}(t)?t.selected:void 0,tabindex:t=>Ye(t)?t.tabIndex:void 0,hidden:t=>Ye(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t.getAttribute("name");r&&"value"in t&&e.append(r,t.value)}),e}(t)};function rr(t,e){if(e.startsWith("computed-")){const r=e.slice(9);return function(t){return t instanceof HTMLElement}(t)?getComputedStyle(t).getPropertyValue(r):void 0}if(e.startsWith("@"))return tr(t,e.slice(1));const r=er[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return tr(t,e);const n=t[e];return Xe(n)?n.bind(t):n}function nr(t){if("string"==typeof t)return t;if(t&&"object"==typeof t){if("string"==typeof t.name)return t.name;if("string"==typeof t.value)return t.value}return t}function sr(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function ir(t,e){return e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):e.variables?.has(t)?e.variables.get(t):"me"===t?e.me:"it"===t?e.it:"result"===t?e.result:void 0}async function or(t,e){if(t.includes(".")){const r=t.split(".");let n=ir(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return ir(t,e)}async function ar(t,e){if(pt(`RESOLVE: Looking for '${t}' in context`,{hasInLocals:e.locals.has(t),localsKeys:Array.from(e.locals.keys()),value:e.locals.get(t)}),e.locals.has(t)){const r=e.locals.get(t);return pt(`RESOLVE: Found '${t}' in locals:`,r),r}if(e.globals&&e.globals.has(t)){const r=e.globals.get(t);return pt(`RESOLVE: Found '${t}' in globals:`,r),r}if(e.variables&&e.variables.has(t)){const r=e.variables.get(t);return pt(`RESOLVE: Found '${t}' in variables (legacy):`,r),r}const r=Number(t);if(!isNaN(r))return r;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.includes(".")){const r=t.split("."),n=r[0];let s=null;if(e.locals.has(n)?s=e.locals.get(n):e.globals&&e.globals.has(n)?s=e.globals.get(n):e.variables&&e.variables.has(n)&&(s=e.variables.get(n)),null!=s){for(let t=1;r.length>t;t++){if(null==s)return void pt(`RESOLVE: Property access failed at '${r[t-1]}'`);s=s[r[t]]}return pt(`RESOLVE: Property access '${t}' =`,s),s}}return t}async function cr(t,e){pt("EVAL: Evaluating expression:",t);const r=t.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,t,n,s]=r;pt("EVAL: Parsed ternary:",{conditionExpr:t,trueExpr:n,falseExpr:s});const i=await ar(t.trim(),e);if(pt("EVAL: Ternary condition value:",i),i){const t=await ar(n.trim(),e);return pt("EVAL: Ternary returned true branch:",t),t}{const t=await ar(s.trim(),e);return pt("EVAL: Ternary returned false branch:",t),t}}const n=t.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)\s*([\+\-\*\/\%])\s*([a-zA-Z_$][a-zA-Z0-9_$]*|\d+(?:\.\d+)?)$/);if(n){const[,t,r,s]=n;pt("EVAL: Parsed arithmetic:",{left:t,operator:r,right:s});const i=await ar(t.trim(),e),o=await ar(s.trim(),e);pt("EVAL: Resolved values:",{leftValue:i,rightValue:o});const a=Number(i),c=Number(o);if(!isNaN(a)&&!isNaN(c)){let t;switch(r){case"+":t=a+c;break;case"-":t=a-c;break;case"*":t=a*c;break;case"/":t=a/c;break;case"%":t=a%c;break;default:t=a}return pt("EVAL: Arithmetic result:",t),t}}const s=await ar(t.trim(),e);return pt("EVAL: Fallback result:",s),s}function lr(t){if(Array.isArray(t)&&1===t.length&&(t=t[0]),null!==t&&"object"==typeof t&&"string"==typeof t.textContent){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?t:r}return 0}return t}async function ur(t,e,r,n,s){try{const i=s(await n(t.object,r));if(null==i)throw Error("Cannot call method on null or undefined");const o=nr(t.property);if(!o||"string"!=typeof o)throw Error("Invalid method name: "+o);const a=i[o];if("function"!=typeof a)throw Error(`Property "${o}" is not a function on ${i.constructor?.name||typeof i}`);const c=await Promise.all(e.map(t=>n(t,r)));return a.apply(i,c)}catch(t){if(t instanceof Error)throw t;throw Error("Failed to evaluate method call: "+t)}}class hr{constructor(){this.expressionRegistry=new Map}registerCategory(t){Object.entries(t).forEach(([t,e])=>{this.expressionRegistry.set(t,e)})}unwrapSelectorResult(t){if(t instanceof NodeList&&t.length>0)return t[0];if(Array.isArray(t)&&t.length>0){const e=t[0];return"index"in t&&"input"in t?t:e instanceof Element||e instanceof Node?e:t}return t}async evaluate(t,e){if(!t)return pt("EVALUATOR: Received null/undefined node, returning null"),null;if(!t.type)throw console.error("EVALUATOR: Node missing type property:",t),Error("Node missing type property: "+JSON.stringify(t));switch(t.type){case"identifier":return this.evaluateIdentifier(t,e);case"literal":return this.evaluateLiteral(t,e);case"string":return t.value??"";case"memberExpression":return this.evaluateMemberExpression(t,e);case"binaryExpression":return this.evaluateBinaryExpression(t,e);case"unaryExpression":return this.evaluateUnaryExpression(t,e);case"callExpression":return this.evaluateCallExpression(t,e);case"selector":return this.evaluateSelector(t,e);case"dollarExpression":return this.evaluateDollarExpression(t,e);case"possessiveExpression":return this.evaluatePossessiveExpression(t,e);case"templateLiteral":return this.evaluateTemplateLiteral(t,e);case"arrayLiteral":return this.evaluateArrayLiteral(t,e);case"objectLiteral":return this.evaluateObjectLiteral(t,e);case"conditionalExpression":return this.evaluateConditionalExpression(t,e);case"cssSelector":return this.evaluateCSSSelector(t,e);case"propertyAccess":return this.evaluatePropertyAccess(t,e);case"propertyOfExpression":return this.evaluatePropertyOfExpression(t,e);case"contextReference":return this.evaluateContextReference(t,e);case"queryReference":return this.evaluateQueryReference(t,e);case"idSelector":return this.evaluateIdSelector(t,e);case"attributeAccess":return this.evaluateAttributeAccess(t,e);case"asExpression":return this.evaluateAsExpression(t,e);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return Pe(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ve({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ve({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ve({type:"break"});if(e.isContinue)return Ve({type:"continue"});if(e.isReturn)return Ve({type:"return",returnValue:e.returnValue})}throw t}}async evaluateArrayLiteral(t,e){const r=t.elements||[],n=[];for(const t of r){const r=await this.evaluate(t,e);n.push(r)}return n}async evaluateObjectLiteral(t,e){const r=t.properties||[],n={};for(const t of r){let r;r="identifier"===t.key.type?t.key.name:"literal"===t.key.type?t.key.value+"":await this.evaluate(t.key,e)+"";const s=await this.evaluate(t.value,e);n[r]=s}return n}async evaluateConditionalExpression(t,e){return await this.evaluate(t.test,e)?this.evaluate(t.consequent,e):t.alternate?this.evaluate(t.alternate,e):void 0}async evaluateTemplateLiteral(t,e){return async function(t,e){let r=t.value||"";pt("TEMPLATE LITERAL: Evaluating",{template:r,node:t});const n=/\$([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)/g,s=[];let i;for(;null!==(i=n.exec(r));)"{"!==r[i.index+1]&&s.push({match:i[0],varName:i[1],index:i.index});for(let t=s.length-1;t>=0;t--){const{match:n,varName:i,index:o}=s[t],a=await or(i,e);pt(`TEMPLATE: $${i} resolved to`,a),r=r.slice(0,o)+((a??"")+"")+r.slice(o+n.length)}let o="",a=0;for(;r.length>a;){const t=r.indexOf("${",a);if(-1===t){o+=r.slice(a);break}o+=r.slice(a,t);let n=1,s=t+2;for(;r.length>s&&n>0;)"{"===r[s]&&n++,"}"===r[s]&&n--,n>0&&s++;if(0!==n)throw Error("Unterminated template expression in: "+r);const i=r.slice(t+2,s);let c;pt("TEMPLATE: Evaluating expression:",i);const l=i.trim();e.locals.has(l)?(c=e.locals.get(l),pt(`TEMPLATE: Found in locals: ${l} =`,c)):e.globals&&e.globals.has(l)?(c=e.globals.get(l),pt(`TEMPLATE: Found in globals: ${l} =`,c)):e.variables&&e.variables.has(l)?(c=e.variables.get(l),pt(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await cr(i,e),pt(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return cr(t,e)}async resolveValue(t,e){return ar(t,e)}async evaluateIdentifier(t,e){const{name:r,scope:n}=t;if("me"===r||"my"===r||"I"===r)return e.me;if("you"===r||"your"===r)return e.you;if("it"===r||"its"===r)return e.it;if("result"===r)return e.result;if("event"===r)return e.event;const s=this.expressionRegistry.get(r);return s?s.evaluate(e):"local"===n?e.locals?.has(r)?e.locals.get(r):void 0:"global"===n?e.globals?.has(r)?e.globals.get(r):"undefined"!=typeof window&&r in window?window[r]:void 0:e.locals?.has(r)?e.locals.get(r):e.globals?.has(r)?e.globals.get(r):e.variables?.has(r)?e.variables.get(r):"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:"undefined"!=typeof window&&r in window?window[r]:void 0}async evaluateLiteral(t,e){return t.value}async evaluateContextReference(t,e){const{contextType:r}=t;switch(r){case"me":return e.me;case"it":return e.result;case"you":return e.you;case"event":return e.event;case"body":return e.meta?.ownerDocument?.body||document?.body;case"detail":return e.event?.detail;case"target":return e.you||e.event?.target;case"sender":return e.event?.target;default:return e.locals&&e.locals.has(r)?e.locals.get(r):void pt("Unknown context reference type: "+r)}}async evaluateMemberExpression(t,e){const{object:r,property:n,computed:s}=t;if("identifier"===r.type&&["add","remove"].includes(r.name)){const t=r.name,s=nr(n);if(!e.me)throw Error('Context element "me" is null');return void("add"===t?e.me.classList.add(s):"remove"===t&&e.me.classList.remove(s))}let i=await this.evaluate(r,e);if(s)return i[await this.evaluate(n,e)];{const t=nr(n);if(Array.isArray(i)&&"string"==typeof t&&("length"===t||t in Array.prototype)||(i=this.unwrapSelectorResult(i)),"string"==typeof t){if(t.startsWith("computed-")){const e=t.substring(9);return i&&"undefined"!=typeof window&&i instanceof Element?window.getComputedStyle(i).getPropertyValue(e):void 0}if(t.startsWith("@")){const e=t.substring(1);return i&&"function"==typeof i.getAttribute?tr(i,e):void 0}if(i&&i instanceof Element){if("previous"===t||"prev"===t)return i.previousElementSibling;if("next"===t)return i.nextElementSibling}}const e=i?.[t];return"function"==typeof e?e.bind(i):e}}coerceArithmeticOperand(t){return lr(t)}async evaluateBinaryExpression(t,e){return async function(t,e,r,n,s){const{operator:i,left:o,right:a}=t;if("in"===i&&"selector"===o.type){let t=o.value;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i&&"queryReference"===o.type){let t=o.selector;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const s=n(await r(a,e));if(!s||"function"!=typeof s.querySelector)throw Error(`'in' operator requires a DOM element as the right operand (got: ${typeof s})`);const i=s.querySelectorAll(t);return Array.from(i)}if("in"===i){let t=null,s=null;if("positionalExpression"===o.type){t=o.operator;const n=o.argument;"cssSelector"===n?.type?s=n.selector:"selector"===n?.type?s=n.value:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}else if("memberExpression"!==o.type||"identifier"!==o.object?.type||"first"!==o.object.name&&"last"!==o.object.name){if("callExpression"===o.type&&"identifier"===o.callee?.type&&("first"===o.callee.name||"last"===o.callee.name)){t=o.callee.name;const n=o.arguments?.[0];"selector"===n?.type?s=n.value:"cssSelector"===n?.type?s=n.selector:"classSelector"===n?.type?s="."+n.className:"idSelector"===n?.type?s="#"+n.id:n&&(s=await r(n,e)+"")}}else t=o.object.name,"identifier"===o.property?.type&&o.property.name&&(s="."+o.property.name);if(t&&s){const i=n(await r(a,e));if(!i||"function"!=typeof i.querySelectorAll)return;const o=i.querySelectorAll(s),c=Array.from(o);return"first"===t?c.length>0?c[0]:void 0:"last"===t?c.length>0?c[c.length-1]:void 0:c}}if("matches"===i&&("selector"===a.type||"cssSelector"===a.type||"classSelector"===a.type)){const t=await r(o,e),n=a.value||a.selector;if(t&&"function"==typeof t.matches)try{return t.matches(n)}catch{return!1}return!1}const c=await r(o,e),l=await r(a,e);if("has"===i||"have"===i){if(c instanceof Element){if("cssSelector"===a.type&&"class"===a.selectorType||"selector"===a.type&&a.value?.startsWith(".")){const t=a.selector?.slice(1)||a.value?.slice(1)||"";return c.classList.contains(t)}if("attributeAccess"===a.type||"attributeRef"===a.type){const t=a.attributeName||a.name||a.value?.replace(/^@/,"")||"";return c.hasAttribute(t)}if("cssSelector"===a.type&&"attribute"===a.selectorType){const t=(a.selector||a.value||"").replace(/^@/,"");return c.hasAttribute(t)}if("cssSelector"===a.type&&"id"===a.selectorType||"idSelector"===a.type){const t=(a.selector||a.value||"").replace(/^#/,"");return null!==c.querySelector("#"+CSS.escape(t))}if("selector"===a.type||"queryReference"===a.type){let t=a.value||a.selector||"";t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());try{return null!==c.querySelector(t)}catch{return!1}}if("cssSelector"===a.type){const t=a.selector||"";try{return null!==c.querySelector(t)}catch{return!1}}}return Array.isArray(c)?c.includes(l):"string"==typeof c&&c.includes(l+"")}switch(i){case">":case"is greater than":return c>l;case"<":case"is less than":return l>c;case">=":case"is greater than or equal to":return c>=l;case"<=":case"is less than or equal to":return l>=c;case"==":case"equals":case"is equal to":return c==l;case"===":case"is really equal to":case"really equals":return c===l;case"!=":case"is not equal to":return c!=l;case"!==":case"is not really equal to":return c!==l;case"+":{const t=lr(c),r=lr(l);if("string"==typeof t||"string"==typeof r){const n=s.get("stringConcatenation");if(n){pt("Using string concatenation for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}else{const n=s.get("addition");if(n){pt("Using numeric addition for:",{leftValue:t,rightValue:r});const s=await n.evaluate(e,{left:t,right:r});return s.success?s.value:t+r}}return t+r}case"-":return lr(c)-lr(l);case"*":return lr(c)*lr(l);case"/":return lr(c)/lr(l);case"%":case"mod":return lr(c)%lr(l);case"as":const t="string"==typeof l?l:"identifier"===a.type?a.name:"literal"===a.type?a.value:l+"",r=s.get("as");return r?r.evaluate(e,c,t):c;case"&&":case"and":return c&&l;case"||":case"or":return c||l;case"is":return c===l;case"is not":return c!==l;case"is a":case"is an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"==typeof c;case"number":return"number"==typeof c;case"boolean":return"boolean"==typeof c;case"object":return"object"==typeof c&&null!==c;case"array":return Array.isArray(c);case"function":return"function"==typeof c;case"null":return null===c;case"undefined":return void 0===c;default:const t="identifier"===a.type?a.name:l+"";return null!=c&&c.constructor?.name===t}case"is not a":case"is not an":switch("identifier"===a.type?a.name.toLowerCase():(l+"").toLowerCase()){case"string":return"string"!=typeof c;case"number":return"number"!=typeof c;case"boolean":return"boolean"!=typeof c;case"object":return!("object"==typeof c&&null!==c);case"array":return!Array.isArray(c);case"function":return"function"!=typeof c;case"null":return null!==c;case"undefined":return void 0!==c;default:const t="identifier"===a.type?a.name:l+"";return!(null!=c&&c.constructor?.name===t)}case"=":if("identifier"===o.type){const t=o.name;return"result"===t?e.result=l:"it"===t?e.it=l:"you"===t?e.you=l:e.locals.set(t,l),l}throw Error("Left side of assignment must be an identifier");case"contains":case"include":case"includes":return Array.isArray(c)?c.includes(l):"string"==typeof c?c.includes(l+""):!(!c||"function"!=typeof c.matches)&&c.matches(l+"");case"match":case"matches":if(c&&"function"==typeof c.matches){const t="string"==typeof l?l:l+"";try{return c.matches(t)}catch{return!1}}return!1;case"in":const n="string"==typeof c?c:c+"",u=l;if(!u||"function"!=typeof u.querySelector){if(Array.isArray(u))return u.includes(c);if("object"==typeof u&&null!==u)return n in u;throw Error(`'in' operator requires a DOM element, array, or object as the right operand (got: ${typeof u})`)}return u.querySelector(n);case" ":return"string"==typeof c&&"string"==typeof l?{command:c,selector:l}:"identifier"===o.type&&"selector"===a.type?{command:o.name,selector:a.value}:l;default:throw Error(`Unsupported binary operator: "${i}" (length: ${i.length})`)}}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateUnaryExpression(t,e){const{operator:r,argument:n}=t,s=await this.evaluate(n,e);switch(r){case"not":case"!":const t=this.expressionRegistry.get("not");return t?t.evaluate(e,s):!s;case"no":const n=this.expressionRegistry.get("no");return!!n&&n.evaluate(e,s);case"some":return null!=s&&("string"==typeof s||Array.isArray(s)||s instanceof NodeList||s instanceof HTMLCollection?s.length>0:"object"!=typeof s||Object.keys(s).length>0);case"exists":const i=this.expressionRegistry.get("exists");return i?i.evaluate(e,s):null!=s;case"does not exist":const o=this.expressionRegistry.get("doesNotExist");return o?o.evaluate(e,s):null==s;case"-":return-s;case"+":return+s;default:throw Error("Unsupported unary operator: "+r)}}async evaluateCallExpression(t,e){return async function(t,e,r,n,s,i){const{callee:o,arguments:a,isConstructor:c}=t;if(c){const t=o.name,n=e.globals?.get(t)||window[t];if("function"==typeof n)return new n(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown constructor: "+t)}if("memberExpression"===o.type||"propertyAccess"===o.type)return ur(o,a,e,r,n);const l=o.name||o,u=s.get(l);if(u){const t=["first","last","random","at"],n=["closest","previous","next"].includes(l),s=t.includes(l),o=await Promise.all(a.map(t=>n&&t&&"selector"===t.type&&"string"==typeof t.value?t.value:n&&t&&"identifier"===t.type&&"string"==typeof t.name?t.name:s&&t&&"selector"===t.type&&"string"==typeof t.value?i(t,e):r(t,e)));return u.evaluate(e,...o)}const h=e.globals?.get(l)||window[l];if("function"==typeof h)return h(...await Promise.all(a.map(t=>r(t,e))));throw Error("Unknown function: "+l)}(t,e,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this),this.expressionRegistry,this.evaluateSelector.bind(this))}async evaluateMethodCall(t,e,r){return ur(t,e,r,this.evaluate.bind(this),this.unwrapSelectorResult.bind(this))}async evaluateSelector(t,e){return function(t,e){let r=t.value;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return[];const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t&&"object"==typeof t&&1===t.nodeType&&"string"==typeof t.tagName)}(t,e)}evaluateAttributeAccess(t,e){return e.me&&"function"==typeof e.me.getAttribute?tr(e.me,t.attributeName):"@"+t.attributeName}async evaluateAsExpression(t,e){const r=await this.evaluate(t.expression,e),n=this.expressionRegistry.get("as");if(n)return n.evaluate(e,r,t.targetType);throw Error("Conversion type 'as' not registered")}getAvailableExpressions(){return Array.from(this.expressionRegistry.keys())}async evaluateDollarExpression(t,e){const r=await this.evaluate(t.expression,e);if("identifier"===t.expression.type){const r=t.expression.name;return/^\d+$/.test(r)?r:e.locals?.has(r)?e.locals.get(r):"me"===r&&e.me?e.me:"you"===r&&e.you?e.you:"it"===r&&e.it?e.it:"result"===r&&e.result?e.result:"undefined"!=typeof window&&"window"===r?window:e.globals?.has(r)?e.globals.get(r):void 0}return r}async evaluatePossessiveExpression(t,e){const{object:r,property:n}=t,s=this.unwrapSelectorResult(await this.evaluate(r,e));if(!s)return;const i=nr(n);return"string"==typeof i&&Ke(s)?rr(s,i):s[i]}hasExpression(t){return this.expressionRegistry.has(t)}async evaluateCSSSelector(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return"id"===t.selectorType?null:[];if("id"===t.selectorType){const t=r.startsWith("#")?r.slice(1):r;return n.getElementById(t)}if("class"===t.selectorType){const t=r.replace(/:/g,"\\:"),e=n.querySelectorAll(t);return Array.from(e).filter(t=>t instanceof HTMLElement)}const s=n.querySelectorAll(r);return Array.from(s).filter(t=>t instanceof HTMLElement)}(t,e)}async evaluateIdSelector(t,e){return function(t,e){const r=sr(e);if(!r)return null;const n=t.value.startsWith("#")?t.value.slice(1):t.value;return r.getElementById(n)}(t,e)}async evaluateQueryReference(t,e){return function(t,e){let r=t.selector;r.startsWith("<")&&r.endsWith("/>")&&(r=r.slice(1,-2).trim());const n=sr(e);if(!n)return[];try{return n.querySelectorAll(r)}catch{return n.createDocumentFragment().childNodes}}(t,e)}async evaluatePropertyAccess(t,e){const r=await this.evaluate(t.object,e),n=t.property;if(null==r)throw Error(`Cannot access property "${n.name||n.value}" of ${r}`);const s=n.name||n.value;if(!s)throw Error("Property name must be an identifier");try{let t;return t=Ke(r)?rr(r,s):r[s],"function"==typeof t?t.bind(r):t}catch(t){throw Error(`Error accessing property "${s}": ${t}`)}}async evaluatePropertyOfExpression(t,e){const r=t.property,n=r.name||r.value;if(!n)throw Error('Property name must be an identifier in "the X of Y" pattern');const s=this.unwrapSelectorResult(await this.evaluate(t.target,e));if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);try{let t;return t=Ke(s)?rr(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const fr={1:"one",2:"two",3:"three",4:"four",5:"five"};function dr(t,e,r,n){if(t.length!==e){return`${r} requires exactly ${s=e,fr[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`}var s;return null}function pr(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function mr(t,e,r){return dr(t,1,e,r)??pr(t,0,e,r)}function yr(t,e){return dr(t,2,e,"left, right")}function vr(){return null}function gr(t,e,r,n){return t.length>e?`${r} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${n?` (${n})`:""}`:null}function br(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function Er(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const wr="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let xr;function kr(){return xr({validate:t=>({success:!0,data:t})})}function Ar(t,e){if(wr)return kr();const r=xr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:Er("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(e?.strict){const e=Object.keys(t),r=Object.keys(n).filter(t=>!e.includes(t));if(r.length>0)return{success:!1,error:Er("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[e,r]of Object.entries(t)){const t=n[e];if(!(e in n)&&!r.t)return{success:!1,error:Er("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:!1,error:Er("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:!0,data:s}}});return r.strict=()=>Ar(t,{strict:!0}),r}xr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:!0,data:e.data}:{success:!1,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:!0,validate:e=>null==e?{success:!0,data:void 0}:t(e)};return xr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&t>n.data.length?{success:!1,error:Er("runtime-error",`String must be at least ${t} characters long`)}:n}};return xr(r)}),t.max||(t.max=function(t){const e=this.validate.bind(this),r={...this,validate:r=>{const n=e(r);return n.success&&"string"==typeof n.data&&n.data.length>t?{success:!1,error:Er("runtime-error",`String must be at most ${t} characters long`)}:n}};return xr(r)}),t.default||(t.default=function(t){const e=this.validate.bind(this),r={...this,i:t,o:!0,validate:r=>void 0===r?{success:!0,data:t}:e(r)};return xr(r)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?t(s.data)?s:{success:!1,error:Er("runtime-error",e||"Refinement validation failed")}:s}};return xr(n)}),new Proxy(t,{get:(t,e,r)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,r):function(...t){return r}})};const Sr=t=>function(t={}){return wr?kr():xr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Er("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Er("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Er("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:!1,error:Er("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Er("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),Cr=t=>function(t={}){return wr?kr():xr({validate:e=>{const r=Number(e);return isNaN(r)?{success:!1,error:Er("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:!1,error:Er("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:!1,error:Er("runtime-error","Number must be at most "+t.max)}:{success:!0,data:r}}})}(t||{}),Nr=()=>wr?kr():xr({validate:t=>"boolean"!=typeof t?{success:!1,error:Er("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),Tr=t=>Ar(t),Or=t=>function(t){return wr?kr():xr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Er("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Er("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const r=[];for(let n=0;t.length>n;n++){const s=t[n].validate(e[n]);if(!s.success)return{success:!1,error:Er("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(t),Lr=()=>kr(),$r=()=>kr(),Rr=()=>function(t,e="Custom validation failed"){return wr?kr():xr({validate:r=>t(r)?{success:!0,data:r}:{success:!1,error:Er("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Ir{trackPerformance(t,e,r,n){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:r.success?r.value:r.error,timestamp:n,duration:Date.now()-n,success:r.success})}trackSimple(t,e,r,n=(r?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:n,timestamp:e,duration:Date.now()-e,success:r})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||Je(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,r,n,s=[]){return{success:!1,error:{name:t,type:e,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,r=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:r}],suggestions:r}}isElement(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName}inferType(t){return null===t?"null":void 0===t?"undefined":this.isElement(t)?"element":Array.isArray(t)?"array":Ge(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":We(t)?"String":Je(t)?"Number":Ze(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):We(t)?t.split(""):null==t?[]:Ge(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(Je(t)&&Number.isFinite(t))return t;if(We(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Ze(t)?t?1:0:null}}const jr=Tr({selector:Sr().min(1),single:Nr().optional().default(!1)});new class extends Ir{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Rr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.me,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("MeExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=Rr(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.you,s=this.isElement(n)?n:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,r),i}catch(n){const s=this.failure("YouExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=Rr(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=t.it,s={success:!0,value:n,type:this.inferType(n)};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("ItExpressionError","runtime-error",n instanceof Error?n.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,r),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends Ir{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=jr,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const r=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const n=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,n,r),n}let n;if(e.single)n=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));n=t.length>0?t:null}const s={success:!0,value:n,type:Array.isArray(n)?"element-list":"element"};return this.trackPerformance(t,e,s,r),s}catch(n){const s=this.failure("CSSSelectorError","runtime-error",n instanceof Error?n.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:r}=e.data;return this.isValidCSSSelector(r)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${r}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),!0}catch{return!1}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const Mr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:vr},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:vr},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:vr},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:vr},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:vr},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:t=>mr(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>mr(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:t=>mr(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:t=>mr(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let r=e[0];if(r&&"object"==typeof r&&"type"in r){const t=r;"identifier"===t.type&&t.name?r=t.name:"literal"===t.type&&"string"==typeof t.value&&(r=t.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return t.me?t.me.closest(r):null},validate(t){if(1!==t.length)return"closest requires exactly 1 argument (selector)";const e=t[0];return"string"==typeof e||e&&"object"==typeof e&&"type"in e&&("identifier"===e.type||"literal"===e.type)?null:"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me?t.me.parentElement:null,validate:vr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:vr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:vr},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const r=e[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=document.querySelectorAll(r);return Array.from(n)},validate:t=>mr(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||t.me;if(s&&s instanceof HTMLElement){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>br(t,1,2,"styleRef","property, optional element")??pr(t,0,"styleRef","property")??(2===t.length&&t[1]&&"object"!=typeof t[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>dr(t,2,"possessiveStyleRef","possessor, property")??pr(t,0,"possessiveStyleRef","possessor")??pr(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const r=e[0],n=e[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>dr(t,2,"ofStyleRef","property, reference")??pr(t,0,"ofStyleRef","property")??pr(t,1,"ofStyleRef","reference")}};class Dr{constructor(t=100,e=5e3){this.maxSize=t,this.ttl=e,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(t){const e=this.cache.get(t);if(e){if(Date.now()-e.timestamp<=this.ttl)return e.accessCount++,this.accessOrder.set(t,++this.accessCounter),e.result;this.delete(t)}}set(t,e){this.maxSize>this.cache.size||this.cache.has(t)||this.evictLRU();const r={result:e,timestamp:Date.now(),accessCount:1};this.cache.set(t,r),this.accessOrder.set(t,++this.accessCounter)}delete(t){return this.accessOrder.delete(t),this.cache.delete(t)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let t,e=1/0;for(const[r,n]of this.accessOrder)e>n&&(e=n,t=r);void 0!==t&&this.delete(t)}getStats(){const t=Array.from(this.cache.values()),e=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:t.length>0?t.filter(t=>t.accessCount>1).length/t.length:0,avgAge:t.length>0?t.reduce((t,r)=>t+(e-r.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const Pr=new class{constructor(){this.domQueryCache=new Dr(200,3e3),this.exprResultCache=new Dr(500,2e3),this.cssMatchCache=new Dr(100,5e3),this.formValueCache=new Dr(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(t);return this.domQueryCache.set(e,n),n}querySelectorAll(t){const e="querySelectorAll:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,n),n}getElementById(t){const e="getElementById:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(t);return this.domQueryCache.set(e,n),n}getElementsByClassName(t){const e="getElementsByClassName:"+t,r=this.domQueryCache.get(e);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,n),n}matches(t,e){const r=`matches:${this.getElementCacheKey(t)}:${e}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=t.matches(e);return this.cssMatchCache.set(r,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),r=this.formValueCache.get("formValue:"+e);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(t,e){const r=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+r,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(t.cache.keys()))"string"==typeof r&&r.includes(e)&&t.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(t){if(t.id)return"#"+t.id;const e=Array.from(t.classList).sort().join("."),r=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${r}`}getElementPosition(t){return""+Array.from(t.parentElement?.children||[]).indexOf(t)}getPerformanceStats(){const t=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(t>0?this.hits/t*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const t=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(e=>{Array.from(e.cache.entries()).forEach(([r,n])=>{t-n.timestamp>e.ttl&&e.delete(r)})})}};"undefined"!=typeof window&&setInterval(()=>{Pr.cleanup()},1e4);const Vr=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(t){this.startTimes.set(t,performance.now())}endTimer(t){const e=this.startTimes.get(t);if(e){const r=performance.now()-e;return this.startTimes.delete(t),r}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=Pr.getPerformanceStats();this.metrics.cacheHitRate=t.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Br(){Pr.cleanup(),Vr.getMetrics().memoryUsage>52428800&&Vr.reset()}let Fr=null;function _r(t,e){if("number"==typeof t){if(!Number.isFinite(t))throw Error(`${e} must be a finite number, got ${t}`);return t}if("string"==typeof t){const r=t.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${e} cannot be converted to number: "${t}"`);return n}if("boolean"==typeof t)return t?1:0;if(null==t)return 0;if("object"==typeof t&&null!==t){if(Array.isArray(t)&&1===t.length){const r=t[0];if(Array.isArray(r))throw Error(e+" is a nested array, cannot convert to number");return _r(r,e)}if("string"==typeof t.textContent||"value"in t){const e=t.value??t.textContent;if(null!=e){const t=(e+"").trim();if(""===t)return 0;const r=parseFloat(t);if(!isNaN(r))return r}}const r=t.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function qr(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const r=parseFloat(e);return isNaN(r)?null:r}return"boolean"==typeof t?t?1:0:null==t?0:null}function Hr(t,e,r){if("==="===r)return t===e;if("!=="===r)return t!==e;if(null==t||null==e)return function(t,e,r){if(null==t&&null==e)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,r);const[n,s]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const r=parseFloat(t),n=parseFloat(e);return isNaN(r)||isNaN(n)?[t,e]:[r,n]}const r=qr(t),n=qr(e);return null!==r&&null!==n?[r,n]:[t+"",e+""]}(t,e);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return Ur(t,e);case"!=":return!Ur(t,e);default:return!1}}function Ur(t,e){if(t===e)return!0;if(typeof t==typeof e)return("string"==typeof t||"number"==typeof t)&&t===e;if("number"==typeof t&&"string"==typeof e){const r=parseFloat(e);return!isNaN(r)&&t===r}if("string"==typeof t&&"number"==typeof e){const r=parseFloat(t);return!isNaN(r)&&r===e}return"boolean"==typeof t?Ur(t?1:0,e):"boolean"==typeof e?Ur(t,e?1:0):t+""==e+""}function zr(t,e,r,n,s,i=!0,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:r,output:n,timestamp:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),n}"undefined"!=typeof window&&function(t=3e4){Fr&&clearInterval(Fr),Fr=setInterval(Br,t)}();const Wr=Tr({left:Lr().describe("Left operand value"),right:Lr().describe("Right operand value")}).strict(),Jr=Tr({operand:Lr().describe("Operand value to negate")}).strict();function Zr(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Ir{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=Wr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,r,!0,"boolean"),this.success(!1,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,r,!0,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=Wr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,r,!0,"boolean"),this.success(!0,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,r,!0,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=Jr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,r,!0,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,r,!1),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Gr=Or([Lr(),Lr()]),Xr=Or([Lr(),Sr()]),Yr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return zr(this,t,[e,r],e==r,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>yr(t,"equals"),inputSchema:Gr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Compares two values for loose equality, allowing type coercion",parameters:[{name:"left",type:"unknown",description:"Left operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:!1,examples:["5",'"hello"',"true","null"]}],returns:{type:"Boolean",description:"True if values are loosely equal, false otherwise",examples:["true","false"]},examples:[{title:"Basic equality check",code:"if my.value is 10",explanation:"Check if element value equals 10",output:"Boolean result"},{title:"Type coercion",code:'if "5" == 5',explanation:'String "5" equals number 5 with automatic type conversion',output:"true"},{title:"Null checks",code:"if value is null",explanation:"Check if value is null or undefined",output:"Boolean result"}],seeAlso:["strictEquals","notEquals","matches"],tags:["comparison","equality","logic","type-coercion"]}},Kr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e===r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"strictEquals")},Qr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!=r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"notEquals")},tn={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e!==r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"strictNotEquals")},en={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,"<");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"lessThan")},rn={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,"<=");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"lessThanOrEqual")},nn={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,">");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"greaterThan")},sn={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=Hr(e,r,">=");return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"greaterThanOrEqual")},on={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return zr(this,t,[e,r],e&&r,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>yr(t,"and"),inputSchema:Gr,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}},documentation:{summary:"Logical AND operation that returns true only if both operands are truthy",parameters:[{name:"left",type:"unknown",description:"Left operand (evaluated for truthiness)",optional:!1,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:!1,examples:["false","age","0",'""']}],returns:{type:"Boolean",description:"True if both operands are truthy, false otherwise",examples:["true","false"]},examples:[{title:"Form validation",code:"if name and email",explanation:"Check if both name and email have values",output:"Boolean result"},{title:"Multiple conditions",code:"if age > 18 and hasLicense",explanation:"Combine multiple conditions",output:"Boolean result"},{title:"Short-circuit evaluation",code:"if element and element.value",explanation:"Check element exists before accessing properties",output:"Boolean result"}],seeAlso:["or","not","exists"],tags:["logic","boolean","conditions","validation"]}},an={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=e||r;return n&&zr(this,t,[e,r],i,s),i},validate:t=>yr(t,"or")},cn={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"not","operand")},ln={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||(We(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!Ge(e)||0!==Object.keys(e).length)),r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"isEmpty","value")},un={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0;let s;return s=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:!(We(e)||e instanceof Node||e instanceof Element||!Ge(e)||0!==Object.keys(e).length)),r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"no","value")},hn={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=!await ln.evaluate(t,e);return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"isNotEmpty","value")},fn={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null!=e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"exists","value")},dn={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const r=t.evaluationHistory,n=r?Date.now():0,s=null==e;return r&&zr(this,t,[e],s,n),s},validate:t=>dr(t,1,"doesNotExist","value")},pn={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i;if(e&&r){if(Zr(e)&&Zr(r))return i=e.contains(r),n&&zr(this,t,[e,r],i,s),i;if(We(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Zr(r))return i=o.contains(r),n&&zr(this,t,[e,r],i,s),i;if(o&&We(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=!!a&&o.contains(a),n&&zr(this,t,[e,r],i,s),i}}if(We(r)&&r.match(/^[.#][\w-]+$/)&&Zr(e)){const o=document.querySelector(r);return i=!!o&&e.contains(o),n&&zr(this,t,[e,r],i,s),i}}return i=We(e)&&We(r)||Array.isArray(e)?e.includes(r):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(r):!(!Ge(e)||!We(r))&&r in e,n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"contains","container, value")},mn={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await pn.evaluate(t,e,r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"doesNotContain","container, value")},yn={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!(!We(e)||!We(r))&&e.startsWith(r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"startsWith","str, prefix")},vn={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!(!We(e)||!We(r))&&e.endsWith(r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"endsWith","str, suffix")},gn={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,r){const n=Date.now();try{let s;if(e instanceof Element&&We(r)){const t=r;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return Pr.matches(t,e)}(e,t)}catch(t){s=!1}else s=!1}else if(We(e)&&We(r)){const t=e,n=r;try{s=(n.startsWith("/")&&n.endsWith("/")?RegExp(n.slice(1,-1)):RegExp(n)).test(t)}catch(e){s=t.includes(n)}}else s=!1;return zr(this,t,[e,r],s,n)}catch(s){throw zr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>dr(t,2,"matches","element, selector"),inputSchema:Xr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}},documentation:{summary:"Tests if element matches CSS selector or string matches regex pattern",parameters:[{name:"element",type:"Element | string",description:"DOM element or string to test",optional:!1,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:!1,examples:['".active"','"#navbar"','"/^hello/"','"\\\\d+"']}],returns:{type:"Boolean",description:"True if element matches selector/pattern",examples:["true","false"]},examples:[{title:"CSS class matching",code:'if me matches ".active"',explanation:'Check if current element has "active" class',output:"Boolean result"},{title:"Attribute matching",code:'if target matches "[data-role=\\"button\\"]"',explanation:"Check if element has specific data attribute",output:"Boolean result"},{title:"Regex pattern matching",code:'if email matches "/^[^@]+@[^@]+\\\\.[^@]+$/"',explanation:"Validate email format with regex",output:"Boolean result"},{title:"Complex CSS selector",code:'if element matches ".card:hover .button"',explanation:"Match complex CSS selector with pseudo-classes",output:"Boolean result"}],seeAlso:["contains","startsWith","endsWith","querySelector"],tags:["pattern","css","regex","validation","dom"]}},bn={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0;let i=!1;if(e instanceof Element&&We(r)){const t=r;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"has","element, selector")},En={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,r){const n=t.evaluationHistory,s=n?Date.now():0,i=!await bn.evaluate(t,e,r);return n&&zr(this,t,[e,r],i,s),i},validate:t=>dr(t,2,"doesNotHave","element, selector")},wn={equals:Yr,strictEquals:Kr,notEquals:Qr,strictNotEquals:tn,lessThan:en,lessThanOrEqual:rn,greaterThan:nn,greaterThanOrEqual:sn,and:on,or:an,not:cn,no:un,isEmpty:ln,isNotEmpty:hn,exists:fn,doesNotExist:dn,contains:pn,doesNotContain:mn,startsWith:yn,endsWith:vn,matches:gn,has:bn,doesNotHave:En};function xn(t,e,r,n,s="runtime-error"){return{success:!1,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function kn(t,e){return{success:!0,value:t,type:e}}function An(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const Sn={Array:(t,e)=>{try{return Array.isArray(t)?kn(t,"array"):t instanceof NodeList?kn(Array.from(t),"array"):kn(null==t?[]:[t],"array")}catch(t){return xn("Array","ARRAY_CONVERSION_FAILED",An("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?kn("","string"):We(t)?kn(t,"string"):Ge(t)?kn(JSON.stringify(t),"string"):kn(t+"","string")}catch(t){return xn("String","STRING_CONVERSION_FAILED",An("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Ze(t))return kn(t,"boolean");if(null==t)return kn(!1,"boolean");if(We(t)){const e=t.toLowerCase().trim();return kn("false"!==e&&"0"!==e&&""!==e,"boolean")}return Je(t)?kn(0!==t&&!isNaN(t),"boolean"):kn(!!t,"boolean")}catch(t){return xn("Boolean","BOOLEAN_CONVERSION_FAILED",An("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(Je(t))return kn(t,"number");if(null==t)return kn(0,"number");const e=Number(t);return isNaN(e)?xn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):kn(e,"number")}catch(t){return xn("Number","NUMBER_CONVERSION_FAILED",An("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=Sn.Number(t,e);return r.success?kn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=Sn.Number(t,e);return r.success?kn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return kn(t,"object");if(null==t)return kn(new Date(""),"object");if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return kn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?xn("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):kn(e,"object")}catch(t){return xn("Date","DATE_CONVERSION_FAILED",An("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return kn(JSON.stringify(t),"string")}catch(t){return xn("JSON","JSON_STRINGIFY_FAILED",An("Failed to convert value to JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(Ge(t))return kn(t,"object");if(We(t))try{return kn(JSON.parse(t),"object")}catch(t){return xn("Object","JSON_PARSE_FAILED",An("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return kn({},"object")}catch(t){return xn("Object","OBJECT_CONVERSION_FAILED",An("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return kn(On(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{const e=t;if(e.name){const t=Ln(e);void 0!==t&&(r[e.name]=t)}}),kn(r,"object")}return kn({},"object")}catch(t){return xn("FormValues","FORM_VALUES_EXTRACTION_FAILED",An("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Cn=Tr({value:$r(),type:Sr().min(1)}),Nn=Tr({value:$r(),type:Sr().min(1)});new class extends Ir{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=Cn,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSON",description:"Convert array to JSON string",expectedOutput:"[1,2,3]"},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:!1,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:!1,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSON into storage",explanation:"Convert array to JSON string for storage",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"AsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const n=i.match(/^Fixed:(\d+)$/),o=n?parseInt(n[1],10):2,a=Sn.Number(s,t);if(!a.success)return a;const c={success:!0,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,r),c}let o=Sn[i];if(o){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[i.toLowerCase()];if(a&&(o=Sn[a],o)){const n=o(s,t);return this.trackPerformance(t,e,n,r),n}const c={success:!1,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,r),c}catch(n){const s={success:!1,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(n instanceof Error?n.message:n+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends Ir{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Nn,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:!0},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:!0},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:!0,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:!1,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:!1,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:{name:"IsExpressionValidationError",type:"validation-error",message:n.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:n.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=We(s);break;case"number":a=Je(s)&&!isNaN(s);break;case"boolean":a=Ze(s);break;case"object":a=Ge(s);break;case"array":a=Array.isArray(s);break;case"function":a=Xe(s);break;case"date":a=s instanceof Date;break;case"element":a=s instanceof Element;break;case"node":a=s instanceof Node;break;case"node-list":a=s instanceof NodeList;break;case"empty":a=null==s||""===s||Array.isArray(s)&&0===s.length||Ge(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,r),c}catch(n){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(n instanceof Error?n.message:n+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const Tn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":We(t)?t:Ge(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Ze(t))return t;if(null==t)return!1;if(We(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return Je(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(Je(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(Je(t))return t;if(null==t)return 0;const e=(t+"").trim();if(!e)return 0;try{return function(t){if(t=t.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(t))throw Error("Invalid characters in math expression");try{const e=Function(`"use strict"; return (${t})`)();if(!Je(e)||!isFinite(e))throw Error("Expression did not evaluate to a finite number");return e}catch(t){throw Error("Math expression evaluation failed: "+(t instanceof Error?t.message:t+""))}}(e)}catch(t){return console.warn("Math conversion failed:",t),0}},Int:t=>{const e=Tn.Number(t);return Math.trunc(e)},Float:t=>{const e=Tn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return new Date(e,r-1,n)}return new Date(t)},JSON:t=>{try{return JSON.stringify(t)}catch(t){return"{}"}},Object:t=>{if(Ge(t))return t;if(We(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{We(t)||(t=Tn.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>We(t)?t:t instanceof NodeList?Array.from(t).map(t=>t instanceof Element?t.outerHTML:t.textContent||"").join(""):Array.isArray(t)?t.map(t=>t instanceof Element?t.outerHTML:Tn.String(t)).join(""):t instanceof Element?t.outerHTML:Tn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return On(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=Ln(t))}),r}return{}},"Values:Form":(t,e)=>{const r=Tn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=Tn.Values(t,e);return JSON.stringify(r)}};function On(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=Ln(r);void 0!==t&&(void 0!==e[r.name]?(Array.isArray(e[r.name])||(e[r.name]=[e[r.name]]),e[r.name].push(t)):e[r.name]=t)}}),e}function Ln(t){if(t instanceof HTMLInputElement)switch(t.type){case"checkbox":return t.checked;case"radio":return t.checked?t.value:void 0;case"number":case"range":return t.valueAsNumber;case"date":case"datetime-local":return t.valueAsDate;case"file":return t.files;default:return t.value}return t instanceof HTMLSelectElement&&t.multiple?Array.from(t.selectedOptions).map(t=>t.value):t.value}const $n={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof n)throw Error("Conversion type must be a string");if(n.startsWith("Fixed")){const{precision:t}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):2}:{}}(n);return Tn.Number(r).toFixed(t||2)}let s=Tn[n];if(s)return s(r,t);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON"}[n.toLowerCase()];return i&&(s=Tn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>dr(t,2,"as","value, type")??pr(t,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(t,...e){const[r,n]=e;if(!We(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return We(r);case"number":return Je(r)&&!isNaN(r);case"boolean":return Ze(r);case"object":return Ge(r);case"array":return Array.isArray(r);case"function":return Xe(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||Ge(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>dr(t,2,"is","value, type")??pr(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>dr(t,1,"async","expression")}},Rn={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},In=Tr({collection:Lr().describe("Collection to operate on (array, NodeList, or string)")}).strict(),jn=Tr({collection:Lr().describe("Collection to access"),index:Cr().describe("Index position to access")}).strict(),Mn=Tr({collection:Lr().describe("Collection to select random item from")}).strict();function Dn(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;const t=r.querySelector(e);if(t)return t;r=r.nextElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Dn(n,e):null}function Pn(t,e){let r=t.previousElementSibling;for(;r;){const t=Array.from(r.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(r.matches(e))return r;r=r.previousElementSibling}const n=t.parentElement;return n&&n!==document.documentElement?Pn(n,e):null}function Vn(t){let e=0,r=t;for(;r&&r.parentElement;)e+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,e+=1e3;return e}new class extends Ir{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=In,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(n instanceof Error?n.message:n+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=In,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(n instanceof Error?n.message:n+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends Ir{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=jn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:!0,value:o,type:Rn[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,r),a}catch(n){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(n instanceof Error?n.message:n+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends Ir{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=Mn,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return{success:!1,error:n.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const n={success:!0,value:void 0,type:"undefined"};return this.trackPerformance(t,e,n,r),n}const i=s[this.getSecureRandomIndex(s.length)],o={success:!0,value:i,type:Rn[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,r),o}catch(n){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(n instanceof Error?n.message:n+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,r),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:!1,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const Bn={first:{name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const r=void 0!==e?e:t.it;return null==r?null:Array.isArray(r)||r instanceof NodeList||r instanceof HTMLCollection?r.length>0?r[0]:null:r instanceof Element?r.children.length>0?r.children[0]:null:We(r)?r.length>0?r[0]:null:Ge(r)&&"length"in r&&Je(r.length)&&r.length>0?r[0]:null},validate:t=>gr(t,1,"first","collection")},last:{name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const r=void 0!==e?e:t.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const t=r.children;return t.length>0?t[t.length-1]:null}return We(r)?r.length>0?r[r.length-1]:null:Ge(r)&&"length"in r&&Je(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>gr(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!Je(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(We(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Ge(i)&&"length"in i&&Je(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>br(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)},next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Dn(s,r):s.nextElementSibling:null},validate:t=>gr(t,2,"next","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[r,n]=e,s=n||t.me;return s&&s instanceof Element?r?Pn(s,r):s.previousElementSibling:null},validate:t=>gr(t,2,"previous","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=Vn(t);for(const t of n)if(Vn(t)>s)return t;return null}(i,r,o):null},validate:t=>br(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[r,n,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(n);return o?function(t,e,r){const n=Array.from(r.querySelectorAll(e)),s=Vn(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>Vn(e))return e}return null}(i,r,o):null},validate:t=>br(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}},Fn=new Set(["__proto__","constructor","prototype"]),_n={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[r,n]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return rr(r,n);if(Ge(r)){if(Fn.has(n))return;return r[n]}return r[n]}},validate:t=>dr(t,2,"possessive","element, property")??pr(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[r]=e;if(t.me){if("string"!=typeof r)throw Error("Property name must be a string");if(t.me instanceof Element)return rr(t.me,r);if(Ge(t.me)){if(Fn.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>mr(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[r]=e;if(null==t.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=t.it;if(n instanceof Element)return rr(n,r);if(Ge(n)){if(Fn.has(r))return;return n[r]}return n[r]},validate:t=>mr(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[r]=e;if(t.you){if("string"!=typeof r)throw Error("Property name must be a string");if(t.you instanceof Element)return rr(t.you,r);if(Ge(t.you)){if(Fn.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>mr(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[r,n]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return rr(n,r);if(Ge(n)){if(Fn.has(r))return;return n[r]}return n[r]}},validate:t=>dr(t,2,"of","property, object")??pr(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[r,n]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||t.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:t=>br(t,1,2,"attribute","attributeName, optional element")??pr(t,0,"attribute","attribute name")??(2>t.length||null==t[1]||t[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(t,...e){const[r,n,s]=e;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||t.me;return!!(i&&i instanceof Element)&&i.getAttribute(r)===n},validate:t=>br(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??pr(t,0,"attributeWithValue","attribute name")??pr(t,1,"attributeWithValue","expected value")??(3>t.length||null==t[2]||t[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:t=>mr(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[r]=e;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:t=>mr(t,"idReference","idValue")}},qn=Tr({value:Sr().describe("String literal value")}).strict(),Hn=Tr({value:Cr().describe("Number literal value")}).strict(),Un=Tr({value:Nr().describe("Boolean literal value")}).strict(),zn=Tr({left:Lr().describe("Left operand"),right:Lr().describe("Right operand")}).strict();const Wn={stringLiteral:new class extends Ir{constructor(){super(...arguments),this.name="stringLiteral",this.category="Special",this.syntax="\"string\" or 'string'",this.description="String literals with template interpolation support",this.outputType="String",this.inputSchema=qn,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid){const e=this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(t,r,!1),e}let s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,r,!0,s),i}catch(e){return this.trackSimple(t,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(e instanceof Error?e.message:e+""),"STRING_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(t,e){let r=t.replace(/\$\{([^}]+)\}/g,(t,r)=>{try{const t=this.resolveExpression(r.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,r)=>{try{const t=this.resolveVariable(r,e);return void 0!==t?t+"":""}catch(t){return""}}),r}resolveExpression(t,e){if(t.includes(".")){const r=t.split(".");let n=this.resolveVariable(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return this.resolveVariable(t,e)}resolveVariable(t,e){return"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Ir{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Hn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?Number.isFinite(e.value)?(this.trackSimple(t,r,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(e instanceof Error?e.message:e+""),"NUMBER_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?Number.isFinite(e.data.value)?this.validationSuccess():this.validationFailure("invalid-argument","Number literal value must be finite",["Use finite numbers only","Avoid Infinity and NaN values"]):this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},booleanLiteral:new class extends Ir{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Un,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);return n.isValid?(this.trackSimple(t,r,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(e){return this.trackSimple(t,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(e instanceof Error?e.message:e+""),"BOOLEAN_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},addition:new class extends Ir{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=zn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=_r(e.left,"left operand")+_r(e.right,"right operand");return this.trackSimple(t,r,!0,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,!1),this.failure("AdditionError","runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""),"ADDITION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid addition input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},stringConcatenation:new class extends Ir{constructor(){super(...arguments),this.name="stringConcatenation",this.category="Special",this.syntax="left + right (string concatenation)",this.description="Concatenation of two values into a string",this.inputSchema=zn,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,r,!0,s),this.success(s,"string")}catch(e){return this.trackSimple(t,r,!1),this.failure("StringConcatenationError","runtime-error",e instanceof Error?e.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(t){const e=zn.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(t){if(null===t)return"null";if(void 0===t)return"undefined";if(We(t))return t;if(Je(t))return""+t;if(Ze(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Ir{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=zn,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const r=Date.now();try{const n=this.validate(e);if(!n.isValid)return this.trackSimple(t,r,!1),this.failure("ValidationError","validation-error",n.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",n.suggestions);const s=_r(e.left,"left operand")*_r(e.right,"right operand");return this.trackSimple(t,r,!0,s),this.success(s,"number")}catch(e){return this.trackSimple(t,r,!1),this.failure("MultiplicationError","runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""),"MULTIPLICATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():this.validationFailure("type-mismatch",e.error?.errors.map(t=>t.message).join(", ")||"Invalid multiplication input",["Provide left and right operands"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}};class Jn extends hr{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Mr),this.registerCategory(wn),this.registerCategory($n),this.registerCategory(Bn),this.registerCategory(_n),this.registerCategory(Wn)}}class Zn{static toTyped(t){return{me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},expressionStack:[],evaluationDepth:0,validationMode:"strict",evaluationHistory:[]}}static fromTyped(t,e){return{...e,me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},...void 0!==t.variables&&{variables:t.variables},locals:t.locals,globals:t.globals,...void 0!==t.events&&{events:t.events},...void 0!==t.meta&&{meta:t.meta}}}}class Gn{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new Jn,this.hookRegistry=r??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,r={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:r,event:t.event??void 0,executionContext:t}}get name(){return this.impl.name||this.impl.metadata?.name}get metadata(){return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:this.impl.metadata?.syntax||""}}async execute(t,...e){const r=e[0],n=this.createHookContext(t,e,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(ht(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void ht(`CommandAdapterV2: '${this.name}' intercepted by hook`);t.locals||(t.locals=new Map),t.locals.set("__evaluator",this.expressionEvaluator);const s=Zn.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ht(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const e=r.modifiers,n=e?.when||e?.where;if(n&&!await this.expressionEvaluator.evaluate(n,t))return void ht(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:r.args||[],modifiers:e||{},commandName:r.commandName},this.expressionEvaluator,t)}else i=e;else ht(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;return ht("CommandAdapterV2: Calling execute with parsed input:",i),o=2===this.impl.execute.length?await this.impl.execute(i,s):await this.impl.execute(s,...i),ht("CommandAdapterV2: Command result:",o),Object.assign(t,Zn.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(es(t)||ht(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(n,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:!0,errors:[],suggestions:[]}}}class Xn{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.sharedEvaluator=t,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);mt(`CommandRegistryV2: Hook registry set and propagated to ${this.adapters.size} adapters`)}getHookRegistry(){return this.hookRegistry}register(t){const e=t.name||t.metadata?.name;if(!e||"string"!=typeof e)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=e.toLowerCase();mt(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,t);const n=new Gn(t,this.sharedEvaluator,this.hookRegistry);this.adapters.set(r,n),w.add(r);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const r=e.toLowerCase();this.implementations.set(r,t),this.adapters.set(r,n),w.add(r)}}getAdapter(t){return this.adapters.get(t.toLowerCase())}has(t){return this.adapters.has(t.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(t){return this.implementations.get(t.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(t,e){const r=this.getAdapter(t);return r?r.validate(e):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Yn=null;function Kn(){return Yn||(Yn=function(t){const e=t?.commands??new Xn,r=t?.eventSources??new He,n=t?.context??new Ue,s=new Set,i={commands:e,eventSources:r,context:n,use(t){if(s.has(t.name))console.warn(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const r of t.commands)e.register(r);if(t.eventSources)for(const e of t.eventSources)r.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:r,options:s}of t.contextProviders)n.register(e,r,s);t.setup?.(i),s.add(t.name)}},reset(){s.clear()}};return i}()),Yn}class Qn{constructor(t={}){this.contextCache=new WeakMap;const e=Kn();this.options={enableContextProviders:t.enableContextProviders??!0,enableEventSources:t.enableEventSources??!0,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,mt(`[RegistryIntegration] Initialized (context=${this.options.enableContextProviders}, events=${this.options.enableEventSources})`)}enhanceContext(t){if(!this.options.enableContextProviders)return t;const e=this.contextCache.get(t);if(e)return e;try{const e=this.contextRegistry.enhance(t);return this.contextCache.set(t,e),mt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return mt("[RegistryIntegration] Failed to enhance context: "+(e instanceof Error?e.message:e+"")),t}}getEventSource(t){if(!this.options.enableEventSources)return;const e=this.eventSourceRegistry.get(t);if(e)return mt(`[RegistryIntegration] Found event source for '${t}'`),e;const r=this.eventSourceRegistry.findSourceForEvent(t);if(r){const e=this.eventSourceRegistry.get(r);return mt(`[RegistryIntegration] Found event source '${r}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(t,e,r);if(!n)throw Error(`Failed to subscribe to event source '${t}'`);return mt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${n.id})`),n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,mt("[RegistryIntegration] Destroyed")}}function ts(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=!0,"returnValue"in t&&(e.returnValue=t.returnValue),e}function es(t){return t instanceof Error&&(null!==De(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function rs(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function ns(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const ss=new WeakMap;class is{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:!0,enableResultPattern:!0,enableAutoCleanup:!0,...t},this.registry=t.registry,this.expressionEvaluator=t.expressionEvaluator,this.behaviorRegistry=new Map,this.globalVariables=_e,this.hookRegistry=new Me,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Fe,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Qn("object"==typeof t.registryIntegration?t.registryIntegration:{}),mt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,r)=>await this.installBehaviorOnElement(t,e,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const r of t)for(const t of r.removedNodes)t instanceof Element&&e.push(t);e.length>0&&queueMicrotask(()=>{for(const t of e)if(!t.isConnected){const e=this.cleanupRegistry.cleanupElementTree(t);e>0&&mt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(t,e){this.hookRegistry.register(t,e)}unregisterHooks(t){return this.hookRegistry.unregister(t)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(t){return this.cleanupRegistry.cleanupElement(t)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),mt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){mt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,r)=>this.execute(t,r||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return mt("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(t,e);if(!Be(r))throw ts(r.error);return r.value}catch(t){throw t}return await this.processCommand(t,e);case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const r={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(r,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"Program":return await this.executeProgram(t,e);case"initBlock":case"block":return await this.executeBlock(t,e);case"sequence":case"CommandSequence":if(this.options.enableResultPattern){const r=t,n=await this.executeCommandSequenceWithResult(r.commands||[],e);if(!Be(n))throw ts(n.error);return n.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const r=await this.evaluateExpressionWithResult(t,e);if(!Be(r))throw ts(r.error);return r.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ht(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw es(t)||console.error(`Error executing command '${i}':`,t),t}}const o=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(o),Error(o)}toSignal(t){const e=De(t);if(e){if(e.isHalt||"HALT_EXECUTION"===e.message)return{type:"halt"};if(e.isExit||"EXIT_COMMAND"===e.message)return{type:"exit",returnValue:e.returnValue};if(e.isBreak)return{type:"break"};if(e.isContinue)return{type:"continue"};if(e.isReturn)return{type:"return",returnValue:e.returnValue}}if(t instanceof Error){if("HALT_EXECUTION"===t.message)return{type:"halt"};if("EXIT_COMMAND"===t.message)return{type:"exit"}}return null}async processCommandWithResult(t,e){const{name:r,args:n,modifiers:s}=t,i=r.toLowerCase();if(ht(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){const t=`Unknown command: ${r}. Ensure it is registered in the Runtime options.`;throw this.options.enableErrorReporting&&console.warn(t),Error(t)}const o=await this.registry.getAdapter(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Pe(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw console.error(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let r;for(const n of t){if(this.hasErrorDiagnostics(n)){const t=n.diagnostics?.[0];mt("⚠️ RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===n.type){const t=await this.processCommandWithResult(n,e);if(!Be(t)){const r=t.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==r.returnValue&&Object.assign(e,{it:r.returnValue,result:r.returnValue}),Pe(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!Be(t))return t;r=t.value}}return Pe(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return ns(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!Be(r))return r;const n=r.value;if(ns(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return Pe(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw t}}return Pe(n)}async executeCommandFromPattern(t,e,r){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},r)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let r;const n=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?n.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of n)try{await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(es(t)&&(t.isHalt||t.isExit))break;throw t}return r}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const r of t.commands)try{await this.execute(r,e)}catch(t){if(es(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let r;for(const n of t.commands)try{r=await this.execute(n,e)}catch(t){if(es(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){if(void 0!==t.returnValue)return Object.assign(e,{it:t.returnValue,result:t.returnValue}),t.returnValue;break}if(t.isBreak)throw t}throw t}return r}async executeObjectLiteral(t,e){const r={};if(!t.properties)return r;for(const n of t.properties){let t;t="identifier"===n.key.type?n.key.name:"literal"===n.key.type?n.key.value+"":await this.execute(n.key,e)+"";const s=await this.execute(n.value,e);r[t]=s}return r}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:r,parameters:n,eventHandlers:s,initBlock:i}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(r,{name:r,parameters:n,type:"imperative",install:o}),mt(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),mt(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(t,e,r){mt("BEHAVIOR: installBehaviorOnElement called: "+t);let n=this.behaviorRegistry.get(t);if(!n&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(n=this.behaviorRegistry.get(t)),!n))throw Error(`Behavior "${t}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return mt(`BEHAVIOR: Installing imperative behavior '${t}'`),n.install(e,r),void mt(`BEHAVIOR: Finished installing imperative behavior '${t}'`);mt("BEHAVIOR: Found behavior, eventHandlers count: "+(n.eventHandlers?.length||0));const s={me:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},i=this.enhanceContext(s);if(n.parameters)for(const t of n.parameters)i.locals.set(t,t in r?r[t]:void 0);for(const[t,e]of Object.entries(r))n.parameters?.includes(t)||i.locals.set(t,e);if(n.initBlock){mt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),mt("BEHAVIOR: Init block completed for "+t)}catch(e){if(mt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&es(e)))throw e}}if(mt(`BEHAVIOR: About to attach ${n.eventHandlers?.length||0} handlers for ${t}`),n.eventHandlers){const e=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,i),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}mt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:r,events:n,commands:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=t,h=n&&n.length>0?n:[r];mt(`BEHAVIOR: executeEventHandler: event='${r}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);mt(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else mt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void mt(`BEHAVIOR: executeEventHandler - No targets found for event '${r}', returning early`);if("mutation"===r&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===r&&l)return void this.setupChangeObserver(l,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){mt(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${r}'`);const t=async t=>{const n=new Map(e.locals),i={...e,locals:n,it:t,event:t},o=this.enhanceContext(i);mt(`CUSTOM EVENT: Executing commands for event '${r}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){console.error(`[HyperFixi] Error executing commands for custom event '${r}':`,t)}};try{const n=this.registryIntegration.subscribeToEventSource(p,{event:r,handler:t,target:i,selector:a},e);mt(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${n.id})`),this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${p}' subscription ${n.id}`)}catch(t){console.error(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=is.createEventHandler(this,s,e,a,o);let y,v=null;if(u){let t=m;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let r;y=n=>{r&&clearTimeout(r),r=setTimeout(()=>t(n),e)},v=()=>{r&&(clearTimeout(r),r=void 0)}}else if(u.throttle){const e=u.throttle;let r=0;y=n=>{const s=Date.now();e>s-r||(r=s,t(n))}}else y=t}else y=m;const g=u?.once?{once:!0}:void 0;if(d){for(const t of h)d.addEventListener(t,y,g),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);v&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],v,"debounce-timeout"):this.cleanupRegistry.registerGlobal(v,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h)t.addEventListener(e,y,g),this.cleanupRegistry.registerListener(t,t,e,y);v&&this.cleanupRegistry.registerCustom(t,v,"debounce-timeout")}}static createEventHandler(t,e,r,n,s){return async i=>{const o=ss.get(i)??0;if(o>=100)return;if(ss.set(i,o+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{mt(`Event delegation: invalid CSS selector '${n}', skipping filter`)}const a=new Map(r.locals),c={...r,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const r of s)l.locals.set(r,t[r]??e?.[r]??null)}for(const r of e)try{const e=rs(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(es(t)){if(t.isHalt||t.isExit)break;if(t.isReturn){void 0!==t.returnValue&&Object.assign(l,{it:t.returnValue,result:t.returnValue});break}}throw console.error("COMMAND FAILED:",t),t}}}setupMutationObserver(t,e,r,n){mt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){ft(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...n,me:s,it:i,locals:new Map(n.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of r)try{await this.execute(t,c)}catch(t){if(es(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),mt("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,r){mt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const n=await this.execute(t,r);let s=[];this.isElement(n)?s=[n]:Array.isArray(n)&&(s=n.filter(t=>this.isElement(t))),mt(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const n=new MutationObserver(async n=>{for(const s of n)if("childList"===s.type||"characterData"===s.type){ft("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const n={...r,me:r.me,it:s,locals:new Map(r.locals)};n.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&n.locals.set("oldValue",i),n.locals.set("newValue",o);const a=this.enhanceContext(n);for(const t of e)try{await this.execute(t,a)}catch(t){if(es(t)){if(t.isHalt||t.isExit||t.isReturn)break}else console.error("Error executing change handler command:",t)}}});n.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,n),mt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const r=e.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return mt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}class os{constructor(t){this.observer=null,this.initialized=!1,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.scanDocument(),this.observer=new MutationObserver(t=>{for(const e of t)"childList"===e.type?e.addedNodes.forEach(t=>{t.nodeType===Node.ELEMENT_NODE&&(this.processElement(t),this.scanElement(t))}):"attributes"===e.type&&"_"===e.attributeName&&this.processElement(e.target)}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1}reset(){this.destroy()}scanAndProcessAll(){this.scanDocument()}scanDocument(){document.body&&this.scanElement(document.body)}scanElement(t){t.hasAttribute("_")&&this.processElement(t),t.querySelectorAll("[_]").forEach(t=>this.processElement(t))}processElement(t){const e=t.getAttribute("_");if(!e)return;const r=qe(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function as(t,e,r,n,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?n.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),f=!1,d=r.length-1;d>=0;d--){var p={};for(var m in n)p[m]="access"===m?{}:n[m];for(var m in n.access)p.access[m]=n.access[m];p.addInitializer=function(t){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,r[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,n.name,h),f=!0}function cs(t,e,r){for(var n=arguments.length>2,s=0;e.length>s;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function ls(t,e,r){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function us(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function hs(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),r=t.indexOf("=");if(-1===r)return{name:t.trim()};const n=t.slice(0,r).trim();let s=t.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function fs(t,e){for(const r of t)e(r);return t}function ds(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function ps(t,e,r){const n=t.hasAttribute(e);void 0!==r?n&&t.getAttribute(e)===r?t.removeAttribute(e):t.setAttribute(e,r):n?t.removeAttribute(e):t.setAttribute(e,"")}function ms(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&vs(r)?[r]:[]}function ys(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function vs(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!ys(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function gs(t,e){return t.map(t=>{if(ys(t)){const r=function(t){const e=t.trim(),r=e.match(/^\{(.+)\}$/);return r?r[1].trim():e}(t),n=e.locals.get(r)??e.globals.get(r);return null!=n?n+"":(console.warn(`Dynamic class variable '${r}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const bs=Symbol("command:name"),Es=Symbol("command:category"),ws=Symbol("command:metadata");function xs(t){return function(e,r){const n=e;n[bs]=t.name,n[Es]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function ks(t){return function(e,r){const n=e,s=n[Es];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??!1,hasBody:t.hasBody??!1,version:"1.0.0",compatibility:t.compatibility};n[ws]=i,Object.defineProperty(e,"metadata",{value:i,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:!0,configurable:!1})}}function As(t){return()=>new t}function Ss(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function Cs(t,e){if(Ss(t))return t;if(!t){const t=e.me;if(!t)throw Error("No target element - provide explicit target or ensure context.me is set");return Ts(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return Ts(e.me)}if("it"===r){if(!Ss(e.it))throw Error('Context reference "it" is not an HTMLElement');return e.it}if("you"===r){if(!e.you)throw Error('Context reference "you" is not available');return Ts(e.you)}const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelector(r);if(!s)throw Error("Element not found with selector: "+r);if(!Ss(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function Ns(t,e){if(Array.isArray(t))return t.filter(Ss);if(t instanceof NodeList)return Array.from(t).filter(Ss);if(Ss(t))return[t];if(!t){const t=e.me;return t&&Ss(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&Ss(e.me)?[e.me]:[];if("it"===r)return Ss(e.it)?[e.it]:[];if("you"===r)return e.you&&Ss(e.you)?[e.you]:[];const n=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let t=r;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.querySelectorAll(t);return Array.from(e).filter(Ss)}}return[]}function Ts(t){if(Ss(t))return t;throw Error("Value is not an HTMLElement")}function Os(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!Ss(e.me))throw Error("context.me is not an HTMLElement");return e.me;case"its":case"it":if(!e.it)throw Error('No "it" value in context');if(!Ss(e.it))throw Error("context.it is not an HTMLElement");return e.it;case"your":case"you":if(!e.you)throw Error('No "you" element in context');if(!Ss(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const Ls=["on","from","to","in","with","at"];async function $s(t,e,r,n,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!Ls.includes(e.name.toLowerCase())})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Ss(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const a=[];for(const t of o){const s=await e.evaluate(t,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(Ss(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(Ss);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(Ss);a.push(...t)}else{if("string"!=typeof s)throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const n=e.querySelectorAll(t),i=Array.from(n).filter(Ss);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!Ss(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function Rs(t){return"string"==typeof t&&t.trim().startsWith("*")}function Is(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const r=e.substring(1).trim();return r?{property:r}:null}(t);if(!e)return null;const r=e.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function js(t,e,r){t.style.setProperty(e,r)}const Ms=["dialog","details","summary","select"];function Ds(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Ps(t,e,r){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const r=Ds(t);return"string"==typeof r&&r.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return!1;const r=Ds(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:Ds(t),extractedFromNode:!0}:function(t){if(!t||"object"!=typeof t)return!1;if("attributeAccess"===t.type)return!0;if("selector"===t.type||"cssSelector"===t.type){const e=Ds(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:Ds(n)),extractedFromNode:!0}:{value:await e.evaluate(t,r),extractedFromNode:!1};var n}class Vs{async resolveTargets(t,e,r,n){return $s(t,e,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Ps(t,e,r)}parseClassNames(t){return ms(t)}isAttribute(t){return us(t.trim())}isCSSProperty(t){return Rs(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>Ss(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let Bs=(()=>{let t,e,r=[ks({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"]}),xs({name:"add",category:"dom"})],n=[],s=Vs;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if("object"==typeof n&&null!==n&&!Array.isArray(n))return{type:"styles",styles:n,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(t){const e=hs(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],r);return{type:"styles",styles:{[n]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,r,t.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);r.length>0&&ds(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,fs(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":!function(t,e){ds(t,Object.entries(e),(t,[e,r])=>{t.style.setProperty(e,r)})}(t.targets,t.styles)}var r,n}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1;if("string"!=typeof t.value)return!1}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return!1;if(Array.isArray(e.styles))return!1;const r=e.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(t=>"string"==typeof t))return!1}return!0}},ls(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const Fs=As(Bs);function _s(t){return!!t.parentNode&&(t.remove(),!0)}let qs=(()=>{let t,e,r=[ks({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"]}),xs({name:"remove",category:"dom"})],n=[],s=Vs;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}async parseInput(t,e,r){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(t.args[0],e,r);if(Ss(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&Ss(n[0]))return{type:"element",targets:n.filter(t=>Ss(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:hs(s).name,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,r,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);r.length>0&&ds(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,fs(t.targets,t=>{t.removeAttribute(r)});break;case"styles":!function(t,e){ds(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)_s(e)}var r}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(e.targets))return!1;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return!1}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return!1}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return!1;return!0}},ls(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const Hs=As(qs);function Us(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function zs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Us(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Ws(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Js(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&ps(t,r)}}function Zs(t,e,r,n){const s=Js(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Gs(t,e,r,n){const s=Js(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:!0}),()=>{t.removeEventListener(n,i)}}function Xs(t,e,r){if(e.startsWith("@")){const n=e.substring(1);return void(!1===r?t.removeAttribute(n):t.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(e){case"textContent":return void(t.textContent=n);case"innerHTML":return void(t.innerHTML=n);case"innerText":return void(t.innerText=n);case"id":return void(t.id=n);case"className":return void(t.className=n);case"value":return void("value"in t&&(t.value=n));case"checked":return void("checked"in t&&(t.checked=!!r))}if(e.includes(".")){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++)if(s=s[n[t]],null==s)return;return void(s[n[n.length-1]]=r)}if(e.includes("-")||e in t.style)t.style.setProperty(e,n);else try{t[e]=r}catch(t){if(!(t instanceof TypeError&&(t.message.includes("only a getter")||t.message.includes("read only"))))throw Error(`Cannot set property '${e}': ${t instanceof Error?t.message:"Unknown error"}`)}}const Ys=/^the\s+(.+?)\s+of\s+(.+)$/i,Ks=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function Qs(t){return"string"==typeof t&&Ys.test(t)}function ti(t,e){const r=t.match(Ys);if(!r)return null;try{return{element:Cs(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function ei(t,e,r){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,r){const n=t.property?.name;if(!n)return null;let s=await e.evaluate(t.target,r);return Array.isArray(s)&&(s=s[0]),Ss(s)?{element:s,property:n}:null}(t,e,r);if(function(t){return!(!t||"object"!=typeof t)&&"propertyAccess"===t.type&&("string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name)}(t))return async function(t,e,r){const n="string"==typeof t.property?t.property:t.property?.name;if(!n)return null;let s=await e.evaluate(t.object,r);return Array.isArray(s)&&(s=s[0]),Ss(s)?{element:s,property:n}:null}(t,e,r);const n=t;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const t=n.object,s=n.property;let i=await e.evaluate(t,r);if(Array.isArray(i)&&(i=i[0]),!Ss(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function ri(t,e){const{element:r,property:n}=t;n.startsWith("*")?js(r,n.substring(1),e+""):Xs(r,n,e)}async function ni(t,e,r){let n,s;if(t?.for){const s=await e.evaluate(t.for,r);n="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const r=Us(t);return r?r.milliseconds:e}return e}(s):void 0}if(t?.until){const n=await e.evaluate(t.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}function si(t,e){const r=e?.name,n=function(t){if(!t||"object"!=typeof t)return!1;if("identifier"!==t.type)return!1;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.includes(e)}(e)}(e);if(Ss(t)||Array.isArray(t)&&t.every(t=>Ss(t)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const ii=As((()=>{let t,e,r=[ks({description:"Toggle classes, attributes, or interactive elements",syntax:["toggle <class> [on <target>]","toggle @attr","toggle <element> [as modal]","toggle <expr> for <duration>"],examples:["toggle .active on me","toggle @disabled","toggle #myDialog as modal","toggle .loading for 2s"],sideEffects:["dom-mutation"]}),xs({name:"toggle",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("toggle command requires an argument");const n=t.args[0],s=n?.name;if("between"===s&&t.args.length>=4){const{duration:n,untilEvent:s}=await ni(t.modifiers,e,r),i=await e.evaluate(t.args[1],r),o=await e.evaluate(t.args[3],r),a=[];for(let e=4;t.args.length>e;e++){const r=t.args[e]?.name;"on"!==r&&"from"!==r&&a.push(t.args[e])}const c={filterPrepositions:!0,fallbackModifierKey:"on"},l=await $s(a,e,r,"toggle",c,t.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:n,untilEvent:s}}const i=await ei(n,e,r);if(i)return{type:"property",target:i};if("selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("*")){let s=n.value,i=1;if("*"===s&&t.args.length>1&&"identifier"===t.args[1].type&&(s="*"+t.args[1].name,i=2),"*"===s&&t.modifiers?.on){const n=t.modifiers.on?.name;if(n&&["display","visibility","opacity"].includes(n)){s="*"+n;const{duration:i,untilEvent:o}=await ni(t.modifiers,e,r),a=Is(s);if(a){const t=r.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Is(s);if(o){const{duration:n,untilEvent:s}=await ni(t.modifiers,e,r),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await $s(t.args.slice(i),e,r,"toggle",a,t.modifiers),duration:n,untilEvent:s}}}const{duration:o,untilEvent:a}=await ni(t.modifiers,e,r),{value:c}=await Ps(n,e,r);if(Qs(c)){const t=ti(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=si(c,n),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=hs(u);return{type:"attribute",name:n,value:s,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=Is(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(Ss(c))s=[c];else if(Array.isArray(c)&&c.every(t=>Ss(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>Ss(t))}else s=await $s([n],e,r,"toggle",h,t.modifiers);const i=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(s);if("dialog"===i){const n=await async function(t,e,r,n){if(e?.as){const t=await r.evaluate(e.as,n);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await r.evaluate(t[1],n);if("string"==typeof e){const s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&t.length>=3){const e=await r.evaluate(t[2],n);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,r);return{type:"dialog",mode:n,targets:s}}return"details"===i?{type:"details",targets:Ws(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:ms(u),targets:s,duration:o,untilEvent:a}}default:{const n=ms(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await $s(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}}}async execute(t,e){switch(t.type){case"classes":{const r=gs(t.classes,e);if(0===r.length)return[...t.targets];if(ds(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&Zs(e,"class",r[0],t.duration),t.untilEvent&&Gs(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,fs(t.targets,t=>{ps(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Zs(e,"attribute",t.name,t.duration),t.untilEvent&&Gs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return fs(t.targets,e=>function(t,e){const r=window.getComputedStyle(t);switch(e){case"display":"none"===r.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=r.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:r}=t;return r.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,r.substring(1)):rr(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||Ks.has(n)||Ks.has(n.toLowerCase())){const r=!e;return ri(t,r),r}if("number"==typeof e){const r=0===e?1:0;return ri(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(ri(t,s),s):(t.element[n]=e,ri(t,""),"")}ri(t,!e)}(t.target),[t.target.element];case"dialog":return fs(t.targets,e=>{return n=t.mode,void((r=e).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return fs(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return fs(t.targets,t=>function(t){if(document.activeElement===t)t.blur();else{if(t.focus(),"showPicker"in t&&"function"==typeof t.showPicker)try{return void t.showPicker()}catch{}const e=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});t.dispatchEvent(e)}}(t));case"classes-between":for(const e of t.targets){const r=e.classList.contains(t.classA),n=e.classList.contains(t.classB);r?(e.classList.remove(t.classA),e.classList.add(t.classB)):n?(e.classList.remove(t.classB),e.classList.add(t.classA)):e.classList.add(t.classA)}if(t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Zs(e,"class",t.classA,t.duration),t.untilEvent&&Gs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},ls(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());class oi{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await $s(t.args,e,r,n)}}(t,e,r,this.mode);return{targets:n,mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>Ss(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const r=t.dataset.originalDisplay;void 0!==r?(t.style.display=r||e,delete t.dataset.originalDisplay):"none"===t.style.display&&(t.style.display=e),t.classList.add("show")}hideElement(t){if(!t.dataset.originalDisplay){const e=t.style.display;t.dataset.originalDisplay="none"===e?"":e}t.style.display="none",t.classList.remove("show")}}let ai=(()=>{let t,e,r=[ks({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),xs({name:"show",category:"dom"})],n=[],s=oi;return e=class extends s{constructor(){super(...arguments),this.mode="show"}async execute(t,e){const r=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,r)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>Ss(t))&&"string"==typeof e.defaultDisplay}},ls(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const ci=As(ai);let li=(()=>{let t,e,r=[ks({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),xs({name:"hide",category:"dom"})],n=[],s=oi;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>Ss(t))}},ls(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:i},null,n),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i}),cs(e,n)})(),e})();const ui=As(li);const hi=As((()=>{let t,e,r=[ks({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"]}),xs({name:"put",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("put requires arguments");const n=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const r=t.args[e],a=n(r),c="literal"===a?r.value:r.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i)if(t.modifiers.into||t.modifiers.before||t.modifiers.after){const e=t.modifiers.into?"into":t.modifiers.before?"before":"after";a=t.args[0],o=e,c=t.modifiers[e]}else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2];else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,r),u=this.mapPosition(o);let h,f,d=null;if(c){const t=n(c),s=await ei(c,e,r);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,n=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const s=t.name;if("my"===s||"me"===s||"I"===s){if(r.me&&n?.name)return{value:l,targets:[r.me],position:"replace",memberPath:n.name}}else if("its"===s||"it"===s){const t=await e.evaluate(c,r);"string"==typeof t&&(d=t)}else d=s}if(d&&n?.name)h=n.name;else if(!d&&!h){const t=await e.evaluate(c,r);"string"==typeof t&&(d=t)}}else if("identifier"===t&&"me"===c.name)d=null;else if("selector"===t||"cssSelector"===t)d=c.value||c.selector;else if("literal"===t){const t=c.value;if("string"==typeof t&&Qs(t)){const e=ti(t,r);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const n=await e.evaluate(c,r),s=this.resolveEvaluatedAsElements(n);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,r),n=this.resolveEvaluatedAsElements(t);if(n)return{value:l,targets:n,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,r),position:u,memberPath:h}}async execute(t,e){const{value:r,targets:n,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,r),e[o]=r,void Object.assign(e,{it:r});if(i)for(const t of n)this.setProperty(t,i,r);else for(const t of n){const e=this.parseValue(r);this.insertContent(t,e,s)}return n}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!Ss(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>Ss(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return Ss(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(Ss(e)){const n=e;switch(r){case"beforebegin":t.parentElement?.insertBefore(n,t);break;case"afterbegin":t.insertBefore(n,t.firstChild);break;case"beforeend":t.appendChild(n);break;case"afterend":t.parentElement?.insertBefore(n,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e);else Ss(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(Ss(t))return[t];if(Array.isArray(t)){const e=t.filter(Ss);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(Ss);return e.length>0?e:null}return null}looksLikeCss(t){return!!t&&(!!/^[#.\[]/.test(t)||(!(!/[>+~\s]/.test(t)||1>=t.length)||["div","span","p","a","button","input","form","ul","li","ol","table","tr","td","th","img","h1","h2","h3","h4","h5","h6","section","article","header","footer","nav","main","aside","dialog","label","select","option","textarea"].includes(t.toLowerCase())))}setProperty(t,e,r){const n=e.split(".");let s=t;for(let t=0;n.length-1>t;t++){if(!s[n[t]])throw Error(`Property path "${e}" does not exist`);s=s[n[t]]}s[n[n.length-1]]=r}},ls(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());function fi(t){if(null==t)return 0;if("number"==typeof t)return isFinite(t)?t:0;if("string"==typeof t)return parseFloat(t);if("boolean"==typeof t)return t?1:0;if(Array.isArray(t))return t.length;if("object"==typeof t){if("length"in t&&"number"==typeof t.length)return t.length;if("function"==typeof t.valueOf){const e=t.valueOf();if("number"==typeof e)return e}return NaN}return 0}function di(t,e,r){return"global"===r&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==r&&e.locals&&e.locals.has(t)?e.locals.get(t):e.globals&&e.globals.has(t)?e.globals.get(t):e.variables&&e.variables.has(t)?e.variables.get(t):"global"===r&&e.locals&&e.locals.has(t)?e.locals.get(t):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function pi(t,e,r,n){if("global"===n)return r.globals.set(t,e),void("undefined"!=typeof window&&(window[t]=e));if(r.locals&&r.locals.has(t))r.locals.set(t,e);else{if(r.globals&&r.globals.has(t))return r.globals.set(t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(!r.variables||!r.variables.has(t))return"undefined"!=typeof window&&t in window?(window[t]=e,void r.globals.set(t,e)):void r.locals.set(t,e);r.variables.set(t,e)}}function mi(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:di(t,e)}const yi=As((()=>{let t,e,r=[ks({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"]}),xs({name:"make",category:"dom"})],n=[];return e=class{async parseInput(t,e,r){const n=t.args.length>0?await e.evaluate(t.args[0],r):void 0;if(!n)throw Error("Make command requires class name or DOM element expression");const s=void 0!==t.modifiers.an?"an":"a",i=await async function(t,e,r){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const n=[];for(const s of t.args)n.push(await e.evaluate(s,r));return n}const n=await e.evaluate(t,r);return Array.isArray(n)?n:[n]}(t.modifiers.from,e,r),o=await async function(t,e,r){if(!t)return;if("symbol"===t.type&&"string"==typeof t.name)return t.name;const n=await e.evaluate(t,r);return"string"==typeof n?n:n+""}(t.modifiers.called,e,r);return{article:s,expression:n,constructorArgs:i,variableName:o}}async execute(t,e){const{expression:r,constructorArgs:n=[],variableName:s}=t,i="string"==typeof r&&r.startsWith("<")&&r.endsWith("/>")?function(t){const e=t.slice(1,-2);let r="div",n=e;const s=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=e.slice(s[0].length));const i=document.createElement(r),o=n.split(/(?=[.#])/);for(const t of o)if(t.startsWith("#")){const e=t.slice(1);e&&(i.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&i.classList.add(e)}return i}(r):function(t,e,r){if(Ss(t))return t;const n=t+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===e.length?new s:new s(...e)}(r,n,e);return Object.assign(e,{it:i}),s&&pi(s,i,e),i}},ls(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),vi=As((()=>{let t,e,r=[ks({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"]}),xs({name:"set",category:"data"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("set command requires a target");const n=t.args[0],s=n?.name||n?.value,i=await ei(n,e,r);if(i){const n=await this.extractValue(t,e,r);if(i.property.startsWith("*")){const t=i.property.substring(1);return{type:"style",element:i.element,property:t,value:n+""}}return{type:"property",element:i.element,property:i.property,value:n}}if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,t,e,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await e.evaluate(n,r):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(Ss(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(o))return{type:"object-literal",properties:o,targets:await this.resolveTargets(t.modifiers.on,e,r)};if(Qs(o)){const n=ti(o,r);if(n){const s=await this.extractValue(t,e,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,t,e,r)}if("string"==typeof o&&Rs(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,r),property:n,value:s+""}}if("string"==typeof o&&us(o)){const n=o.substring(1).trim(),s=await this.extractValue(t,e,r);return{type:"attribute",element:await this.resolveElement(t.modifiers.on,e,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=Os(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(Ss(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&Ss(o[0])){const n=await this.extractValue(t,e,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o)throw Error("set command target must be a string or object literal"+("memberExpression"===n?.type||"propertyAccess"===n?.type?` (a property chain evaluated to ${null===o?"null":typeof o} — check that all intermediate objects exist)`:""));return{type:"variable",name:o,value:await this.extractValue(t,e,r)}}async execute(t,e){switch(t.type){case"variable":return e.locals.set(t.name,t.value),"result"!==t.name&&"it"!==t.name||Object.assign(e,{[t.name]:t.value}),Object.assign(e,{it:t.value}),{target:t.name,value:t.value,targetType:"variable"};case"attribute":return t.element.setAttribute(t.name,t.value+""),Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Xs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return js(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[r,n]of Object.entries(t.properties))Xs(e,r,n);return Object.assign(e,{it:t.properties}),{target:t.targets[0]||"unknown",value:t.properties,targetType:"property"};case"member-assignment":return t.container[t.property]=t.value,Object.assign(e,{it:t.value}),{target:t.property,value:t.value,targetType:"property"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,r,n){const s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=Os(t,n),o=await this.extractValue(e,r,n);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=await r.evaluate(o,n);if(null!=s&&"object"==typeof s){const o=a?await r.evaluate(t.property,n)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,value:await this.extractValue(e,r,n)}}}return null}async extractValue(t,e,r){if(t.modifiers.to)return e.evaluate(t.modifiers.to,r);const n=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(n>=0&&t.args.length>n+1)return e.evaluate(t.args[n+1],r);if(t.args.length>=2)return e.evaluate(t.args[1],r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,r){return Cs(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return Ns(t?await e.evaluate(t,r):void 0,r)}async parseTheXofY(t,e,r,n){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=Cs(o,n),c=await this.extractValue(e,r,n);return{type:"property",element:a,property:i.trim(),value:c}}validate(t){if(!t||"object"!=typeof t)return!1;const e=t;if(!e.type||"string"!=typeof e.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return!1;switch(e.type){case"variable":return"string"==typeof e.name&&"value"in e;case"attribute":return"string"==typeof e.name&&Ss(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&Ss(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&Ss(e.element)&&"string"==typeof e.value;case"object-literal":return null!==e.properties&&"object"==typeof e.properties&&Array.isArray(e.targets)&&e.targets.length>0;default:return!1}}},ls(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})());let gi=(()=>{let t,e,r=[ks({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"]}),xs({name:"increment",category:"data"})],n=[];return e=class{async parseInput(t,e,r){const n="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",s=await async function(t,e,r,n){if(!t.args||0===t.args.length)throw Error(n+" command requires a target");const s=t.args[0];let i,o;const a=(c=s)&&"object"==typeof c&&c.type||"unknown";var c;if("identifier"===a)i=s.name,s.scope&&(o=s.scope);else if("literal"===a)i=s.value;else{const t=await e.evaluate(s,r);i=Array.isArray(t)&&t.length>0?t[0]:t}let l=1,u=o;for(let n=1;t.args.length>n;n++){const s=t.args[n];if(s&&"literal"===s.type){const t=s.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(s&&"literal"!==s.type){const t=await e.evaluate(s,r);"number"==typeof t&&(l=t)}}return{target:i,amount:l,...u&&{scope:u}}}(t,e,r,n);return{...s,operation:n}}async execute(t,e){const{target:r,property:n,scope:s,amount:i=1,operation:o="increment"}=t,a=function(t,e,r,n){if("number"==typeof t)return t;if(Ss(t)){const r=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?fi(r.getAttribute(e)):fi(r[e]):fi(r.value||r.textContent)}return"string"==typeof t?"global"===r?fi(di(t,n,"global")):t.includes(".")?function(t,e){const r=t.split("."),n=r[1],s=mi(r[0],e);return s?fi(s[n]):0}(t,n):fi("me"===t&&n.me?n.me.value||0:"it"===t?n.it||0:"you"===t&&n.you?n.you.value||0:di(t,n)):fi(t)}(r,n,s,e);let c;if(isNaN(a))c=NaN;else{const t=isFinite(i)?i:1;c="increment"===o?a+t:a-t}return function(t,e,r,n,s){if(Ss(t)){const r=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?r.setAttribute(e,n+""):r[e]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof t){if("global"===r)return void pi(t,n,s,"global");if(t.includes("."))return void function(t,e,r){const n=t.split("."),s=n[1],i=mi(n[0],r);i&&(i[s]=e)}(t,n,s);if("me"===t&&s.me)return void(s.me.value=n);if("it"===t)return void Object.assign(s,{it:n});if("you"===t&&s.you)return void(s.you.value=n);pi(t,n,s)}}(r,n,s,c,e),Object.assign(e,{it:c}),c}},ls(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})();const bi=As(gi),Ei=As(gi);function wi(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e||"false"!==e&&("null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0)}let xi=(()=>{let t,e,r=[ks({description:"Dispatch events on elements",syntax:["trigger <event> on <target>","trigger <event>(<detail>) on <target>","send <event> to <target>","send <event>(<detail>) to <target>"],examples:["trigger click on #button","trigger customEvent on me","send dataEvent to #target","send myEvent(count: 42) to me"],sideEffects:["event-dispatch"],aliases:["send"]}),xs({name:"trigger",category:"event"})],n=[];return e=class{async parseInput(t,e,r){const n="send"===t.commandName?.toLowerCase()?"send":"trigger",s=n;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,r))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,r);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,r,s);else{const n=t.args.findIndex((t,e)=>{if(0===e)return!1;const r=t.name||t.value;return"on"===r||"to"===r});if(-1!==n&&t.args.length-1>n){const i=t.args.slice(n+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,r,s)}else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,r),mode:n}}async execute(t,e){const r=function(t,e,r={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(r);e.it=r}async resolveTargets(t,e,r,n){const s=[];for(const n of t){const t=await e.evaluate(n,r);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&r.me)s.push(r.me);else if("you"===t&&r.you)s.push(r.you);else if("it"===t&&r.it)s.push(r.it);else if(Ss(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(Ss));else if(Array.isArray(t))s.push(...t.filter(Ss));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(Ss));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(t,e,r){if(!t?.length)return;if(1===t.length){const n=t[0];if("objectLiteral"!==n?.type)return await e.evaluate(n,r)}const n={};for(const s of t){const t=await e.evaluate(s,r);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,r]=t.split(":",2);n[e.trim()]=wi(r.trim())}}else Object.assign(n,t)}return Object.keys(n).length?n:void 0}async parseEventOptions(t,e,r){const n={bubbles:!0,cancelable:!0,composed:!1},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return n;for(const i of t.slice(s+1)){const t=await e.evaluate(i,r);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?n.bubbles=!0:"nobubbles"===e?n.bubbles=!1:"cancelable"===e?n.cancelable=!0:"nocancelable"===e?n.cancelable=!1:"composed"===e&&(n.composed=!0)}}return n}},ls(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})();const ki=As(xi),Ai=As(xi);function Si(t,e,r){return t?new Promise(r=>{const n=function(r,n){let i=!1;return r=>{i||(i=!0,t.removeEventListener(e,s),n(r))}}(0,r),s=t=>{n({event:t,timedOut:!1,cancelled:!1})};t.addEventListener(e,s)}):Promise.reject(Error("waitForEvent: no target provided"))}function Ci(t){return new Promise(e=>setTimeout(e,t))}const Ni=As((()=>{let t,e,r=[ks({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"]}),xs({name:"wait",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,r);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r);const n=t.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,t.args[1],e,r):this.parseTimeWait(t.args[0],e,r)}async execute(t,e){const r=Date.now();if("time"===t.type)return await Ci(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await Si(n,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const r of t.destructure)r in s&&e.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.destructure)t in n&&e.locals.set(t,n[t]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(t,e,r){return{type:"time",milliseconds:zs(await e.evaluate(t,r))}}async parseEventWait(t,e,r,n){const s=await r.evaluate(t,n);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await r.evaluate(e,n);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=n.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,r,n){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",r=[];for(const n of t.properties){const t=n.key?.name||n.key?.value;"name"===t&&n.value?e=n.value.value||"":"args"===t&&n.value?.elements&&(r=n.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:r})}}let i;if(e){const t=await r.evaluate(e,n);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=n.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,r){const n=[];t.modifiers.for?n.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,r)):t.args[0]&&n.push(await this.parseTimeWait(t.args[0],e,r));const s=await e.evaluate(t.modifiers.or,r),i=Array.isArray(s)?s:[s];for(const t of i)try{n.push({type:"time",milliseconds:zs(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);n.push(e?{type:"event",eventName:e[1],target:r.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:r.me??void 0})}}if(2>n.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:n}}async executeRace(t,e){const r=t.map(t=>"time"===t.type?Ci(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Si(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},ls(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Ti=new Map;const Oi=As((()=>{let t,e,r=[ks({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }'],sideEffects:["network","event-dispatching"]}),xs({name:"fetch",category:"async"})],n=[];return e=class{async parseInput(t,e,r){if(!t.args?.length)throw Error("fetch requires a URL");return{url:await this.parseURL(t.args[0],e,r),responseType:this.parseResponseType(t.modifiers.as),options:await this.parseRequestOptions(t.modifiers.with,e,r)}}async execute(t,e){const r=Date.now(),{url:n,responseType:s,options:i}=t,o=new AbortController;let a;e.me&&(a=()=>o.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...i,signal:o.signal},l=Ti.get(s);if(l?.accept){const t=new Headers(c.headers);t.has("Accept")||t.set("Accept",l.accept),c.headers=t}if(e.me){const t={...c,sender:e.me,headers:c.headers||{}};this.dispatchEvent(e.me,"fetch:beforeRequest",t),c.headers=t.headers}let u;i.timeout&&(u=setTimeout(()=>o.abort(),i.timeout));try{let t=await fetch(n,c);if(e.me){const r={response:t};this.dispatchEvent(e.me,"fetch:afterResponse",r),t=r.response}const i=await this.handleResponse(t,s,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:i});const o={status:t.status,statusText:t.statusText,headers:t.headers,data:i,url:t.url,duration:Date.now()-r};return Object.assign(e,{it:i}),o}catch(t){if(e.me&&this.dispatchEvent(e.me,"fetch:error",{reason:t instanceof Error?t.message:t+"",error:t}),t instanceof Error&&"AbortError"===t.name)throw Error("Fetch aborted for "+n);throw Error(`Fetch failed for ${n}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,r){const n=await e.evaluate(t,r);if("string"!=typeof n||!n)throw Error("fetch: URL must be a non-empty string");return n}parseResponseType(t){if(!t)return"text";if(("identifier"===t.type||"expression"===t.type)&&t.name){const e=t.name.toLowerCase();if("object"===e)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(e))return"arraybuffer"===e?"arrayBuffer":e;if(Ti.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,r){if(!t)return{};const n=await e.evaluate(t,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[r,n]of Object.entries(t))e.set(r,n+"");return e}parseBody(t){return null==t?null:t instanceof FormData||t instanceof Blob||t instanceof ArrayBuffer||t instanceof URLSearchParams||"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):t+""}async handleResponse(t,e,r){switch(e){case"response":return t;case"json":return t.json();case"html":return this.parseHTML(await t.text());case"blob":return t.blob();case"arrayBuffer":return t.arrayBuffer();case"text":return t.text();default:{const n=Ti.get(e);return n?n.handler(t,r):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),r=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>r.appendChild(t.cloneNode(!0))),1===r.childNodes.length&&Ss(r.firstChild)?r.firstChild:r}dispatchEvent(t,e,r){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:!0,cancelable:!0}))}},ls(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Li=As((()=>{let t,e,r=[ks({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"',"go to top of #header"],sideEffects:["navigation","scrolling"]}),xs({name:"go",category:"navigation"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{args:[]}}async execute(t,e){const{args:r}=t;if(0===r.length)throw Error("Go command requires arguments");return"string"==typeof r[0]&&"back"===r[0].toLowerCase()?(await this.goBack(),{result:"back",type:"back"}):this.isUrlNavigation(r)?{result:await this.navigateToUrl(r,e),type:"url"}:{result:await this.scrollToElement(r,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const r=t.findIndex(t=>"url"===t),n=t[r+1];if(!n)throw Error('URL is required after "url" keyword');const s="string"==typeof n?n:n+"",i=t.includes("new")&&t.includes("window");if(!this.isValidUrl(s))throw Error(`Invalid URL: "${s}"`);if(i){if("undefined"!=typeof window&&window.open){const t=window.open(s,"_blank");t?.focus&&t.focus()}}else s.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=s):"undefined"!=typeof window&&(window.location.assign?.(s)??(window.location.href=s));return s}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const r=this.parseScrollPosition(t),n=this.parseScrollTarget(t),s=this.parseScrollOffset(t),i=!t.includes("instantly"),o=this.resolveScrollTarget(n,e);if(!o)throw Error("Target element not found: "+n);if("undefined"!=typeof window){const t=i?"smooth":"instant",e=this.mapVerticalPosition(r.vertical),n=this.mapHorizontalPosition(r.horizontal);if(0!==s){o.scrollIntoView?.({behavior:t,block:e,inline:n});const{x:i,y:a}=this.calculateScrollPosition(o,r,s);window.scrollTo?.({left:i,top:a,behavior:t})}else o.scrollIntoView?.({behavior:t,block:e,inline:n})}return o}mapVerticalPosition(t){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[t]||"start"}mapHorizontalPosition(t){return{left:"start",center:"center",right:"end",nearest:"nearest"}[t]||"nearest"}parseScrollPosition(t){const e={vertical:"top",horizontal:"nearest"},r=["top","middle","bottom"],n=["left","center","right"];let s=!1,i=!1;for(const o of t)"string"==typeof o&&(r.includes(o)?(e.vertical=o,s=!0):n.includes(o)&&(e.horizontal=o,i=!0));return i&&!s&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let r=t[e+1];return"the"===r&&t.length>e+2&&(r=t[e+2]),r}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const r=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!r.includes(e)&&(e.startsWith("#")||e.startsWith(".")||e.includes("[")||/^[a-zA-Z][a-zA-Z0-9-]*$/.test(e)))return e;return"body"}parseScrollOffset(t){for(let e=0;t.length>e;e++){const r=t[e];if("string"==typeof r){const t=r.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===r||"-"===r)&&t.length>e+1){const n=t[e+1],s="number"==typeof n?n:parseInt((n+"").replace("px",""),10);if(!isNaN(s))return"-"===r?-s:s}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const r="string"==typeof t?t:t+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&Ss(e.me))return e.me;if("it"===r&&Ss(e.it))return e.it;if("you"===r&&Ss(e.you))return e.you;const n=di(r,e);if(Ss(n))return n;if("undefined"!=typeof document)try{const t=document.querySelector(r);if(t)return t}catch{try{const t=document.getElementsByTagName(r);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,r){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const n=t.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=s,l=i;switch(e.horizontal){case"left":c=n.left+s;break;case"center":c=n.left+s+n.width/2-o/2;break;case"right":c=n.right+s-o}switch(e.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-a/2+r;break;case"bottom":l=n.bottom+i-a+r}return{x:Math.max(0,c),y:Math.max(0,l)}}},ls(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),$i=As((()=>{let t,e,r=[ks({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"]}),xs({name:"log",category:"utility"})],n=[];return e=class{async parseInput(t,e,r){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,r)))}:{values:[]}}async execute(t,e){const r="undefined"!=typeof window?window.console:console;0===t.values.length?r.log():r.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}},ls(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;as(null,t={value:e},r,{kind:"class",name:e.name,metadata:s},null,n),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s}),cs(e,n)})(),e})()),Ri=function(t,e){const r=new Xn(e.expressionEvaluator);for(const e of t)r.register(e);return new is({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Fs(),Hs(),ii(),ci(),ui(),hi(),yi(),vi(),bi(),Ei(),Ai(),ki(),Ni(),Oi(),Li(),$i()],{expressionEvaluator:new class extends hr{constructor(t){super();for(const e of t)this.registerCategory(e)}}([Mr,wn,Wn,$n,Bn])}),Ii={parse:t=>je(t),execute:async(t,e)=>{const r=function(t){if(!t)return qe();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=qe(t.me instanceof Element?t.me:null);return void 0!==t.it&&(e.it=t.it),void 0!==t.you&&(e.you=t.you),void 0!==t.result&&(e.result=t.result),void 0!==t.event&&Object.assign(e,{event:t.event}),e}(e),n=je(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Ri.execute(n.node,r)}},ji=function(t){return new os(t)}(Ii),Mi={runtime:Ii,parse:t=>Ii.parse(t),execute:async(t,e)=>Ii.execute(t,e),createContext:qe,attributeProcessor:ji,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","set","increment","decrement","send","trigger","wait","fetch","go","log"],eval:async(t,e)=>Ii.execute(t,e),init:()=>{ji.init()}};return"undefined"!=typeof window&&(window.hyperfixi=Mi,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ji.init()}):ji.init()),Mi}();
2
2
  //# sourceMappingURL=hyperfixi-standard.js.map