@hyperfixi/core 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/hyperscript-api.d.ts +6 -1
- package/dist/chunks/{bridge-CZfeDyEz.js → bridge-D2DBo02Z.js} +2 -2
- package/dist/chunks/browser-modular-BA3JFmkq.js +2 -0
- package/dist/chunks/index-C6Fn0jGB.js +2 -0
- package/dist/commands/dom/toggle.d.ts +2 -0
- package/dist/commands/index.js +35 -0
- package/dist/commands/index.mjs +35 -0
- package/dist/expressions/index.js +0 -27
- package/dist/expressions/index.mjs +0 -27
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-minimal.js +1 -1
- package/dist/hyperfixi-multilingual.js +1 -1
- package/dist/hyperfixi-standard.js +1 -1
- package/dist/hyperfixi.js +1 -1
- package/dist/hyperfixi.mjs +1 -1
- package/dist/i18n/error-catalog.d.ts +12 -0
- package/dist/index.js +31352 -23495
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +31352 -23495
- package/dist/lokascript-browser-classic-i18n.js +1 -1
- package/dist/lokascript-browser-minimal.js +1 -1
- package/dist/lokascript-browser-standard.js +1 -1
- package/dist/lokascript-browser.js +1 -1
- package/dist/lokascript-multilingual.js +1 -1
- package/dist/lse/index.d.ts +15 -0
- package/dist/lse/index.js +84 -0
- package/dist/lse/index.mjs +71 -0
- package/dist/parser/full-parser.js +596 -240
- package/dist/parser/full-parser.mjs +596 -240
- package/dist/parser/helpers/ast-helpers.d.ts +1 -0
- package/dist/parser/parser-types.d.ts +22 -7
- package/dist/parser/parser.d.ts +7 -0
- package/dist/parser/pratt-parser.d.ts +42 -0
- package/dist/parser/token-consumer.d.ts +1 -2
- package/dist/parser/tokenizer.d.ts +0 -33
- package/dist/registry/index.js +0 -27
- package/dist/registry/index.mjs +0 -27
- package/dist/runtime/runtime-base.d.ts +3 -0
- package/dist/types/base-types.d.ts +11 -0
- package/dist/types/core.d.ts +1 -0
- package/package.json +12 -3
- package/dist/chunks/browser-modular-CwTpxqdt.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,V;function B(t){switch(t){case V.KEYWORD:case V.COMMAND:case V.EXPRESSION:case V.CONTEXT_VAR:case V.GLOBAL_VAR:case V.EVENT:case V.IDENTIFIER:return P.IDENTIFIER;case V.STRING:return P.STRING;case V.NUMBER:return P.NUMBER;case V.BOOLEAN:return P.IDENTIFIER;case V.TEMPLATE_LITERAL:return P.TEMPLATE;case V.CSS_SELECTOR:case V.ID_SELECTOR:case V.CLASS_SELECTOR:case V.QUERY_REFERENCE:return P.SELECTOR;case V.OPERATOR:case V.LOGICAL_OPERATOR:case V.COMPARISON_OPERATOR:return P.OPERATOR;case V.TIME_EXPRESSION:return P.TIME;case V.COMMENT:return P.COMMENT;case V.SYMBOL:return P.SYMBOL;default:return P.UNKNOWN}}!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={})),function(t){t.KEYWORD="keyword",t.COMMAND="command",t.EXPRESSION="expression",t.STRING="string",t.NUMBER="number",t.BOOLEAN="boolean",t.TEMPLATE_LITERAL="template_literal",t.CSS_SELECTOR="css_selector",t.ID_SELECTOR="id_selector",t.CLASS_SELECTOR="class_selector",t.QUERY_REFERENCE="query_reference",t.CONTEXT_VAR="context_var",t.GLOBAL_VAR="global_var",t.EVENT="event",t.OPERATOR="operator",t.LOGICAL_OPERATOR="logical_operator",t.COMPARISON_OPERATOR="comparison_operator",t.TIME_EXPRESSION="time_expression",t.OBJECT_LITERAL="object_literal",t.ARRAY_LITERAL="array_literal",t.SYMBOL="symbol",t.COMMENT="comment",t.IDENTIFIER="identifier",t.UNKNOWN="unknown"}(V||(V={}));const F=D,_=new Set(["+","-","*","/","mod"]),q=new Set(["ms","s","seconds","minutes","hours","days"]);function H(t,e=1){const r=t.position+e;return t.input.length>r?t.input[r]:""}function U(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 W(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;U(t)}}function z(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:B(e),value:r,start:i,end:o,line:J(t,i),column:a};t.tokens.push(c)}function J(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(U(t),U(t);t.input.length>t.position&&"\n"!==t.input[t.position];)r+=U(t);z(t,V.COMMENT,"--"+r,e)}function G(t){const e=t.position,r=U(t);let n=r;for(;t.input.length>t.position;){const e=U(t);if(n+=e,e===r)break;"\\"===e&&t.input.length>t.position&&(n+=U(t))}z(t,V.STRING,n,e)}function X(t){const e=t.position;U(t);let r="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){U(t);break}if("\\"===e){if(U(t),t.input.length>t.position){const e=U(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+=U(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-r.length}`);z(t,V.TEMPLATE_LITERAL,r,e)}function Y(t){const e=t.position,r=U(t);let n=r;for(;t.input.length>t.position;){const e=t.input[t.position];if(!it(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=U(t)}z(t,"#"===r?V.ID_SELECTOR:V.CLASS_SELECTOR,n,e)}function K(t){const e=t.position;let r="";for(r+=U(t);t.input.length-1>t.position;){const e=t.input[t.position],n=t.input[t.position+1];if(r+=U(t),"/"===e&&">"===n){r+=U(t);break}}z(t,V.QUERY_REFERENCE,r,e)}function Q(t){const e=t.position;let r=U(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!it(e)&&"_"!==e&&"-"!==e)break;r+=U(t)}z(t,V.SYMBOL,r,e)}function tt(t){const e=t.position;let r="";const n=t.input[t.position];if(("'"===n||"'"===n)&&"s"===H(t,1))return r="'s",U(t),U(t),void z(t,V.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,U(t),U(t),U(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,U(t),U(t)):r=U(t);let o=V.OPERATOR;j.has(r)?o=V.COMPARISON_OPERATOR:["&&","||"].includes(r)?o=V.LOGICAL_OPERATOR:_.has(r)&&(o=V.OPERATOR),z(t,o,r,e)}function et(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+=U(t)}if(n>t.position&&"."===r[t.position]&&(t.position+1>=n||"."!==r[t.position+1]))for(s+=U(t);n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=U(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+=U(t),"+"!==r[t.position]&&"-"!==r[t.position]||(s+=U(t));n>t.position;){const e=r[t.position];if("0">e||e>"9")break;s+=U(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+=U(t)}q.has(o)?z(t,V.TIME_EXPRESSION,s+o,e):(t.position=i,z(t,V.NUMBER,s,e))}function rt(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+=U(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&&("identifier"===i.kind||"id_selector"===i.kind||"class_selector"===i.kind||"context_var"===i.kind)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}W(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+=U(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){W(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+=U(t)}const s=r.toLowerCase();if("start"===s||"end"===s){W(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+=U(t)}if("of"===e.toLowerCase())return z(t,V.KEYWORD,`at the ${s} of`,n),!0}return t.position=e,!1}if("start"===i||"end"===i){W(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+=U(t)}return"of"===r.toLowerCase()?(z(t,V.KEYWORD,`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&&(W(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+=U(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 z(t,V.COMPARISON_OPERATOR,a,r),!0;if(j.has(s))return z(t,V.COMPARISON_OPERATOR,s,r),!0}return j.has(n)?(t.position=s,z(t,V.COMPARISON_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?V.COMPARISON_OPERATOR:I.has(e)?V.LOGICAL_OPERATOR:_.has(t)||_.has(e)?V.OPERATOR:j.has(e)?V.COMPARISON_OPERATOR:"I"===t||R.has(e)?V.CONTEXT_VAR:w.has(e)?V.COMMAND:M.has(e)?V.EVENT:["true","false","null","undefined"].includes(e)?V.BOOLEAN:F.has(e)?V.KEYWORD:V.IDENTIFIER}(s);z(t,o,s,e)}function nt(t){const e=t.position,r=t.input,n=r.length;U(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+=U(t)}z(t,V.GLOBAL_VAR,s,e)}function st(t){return/[a-zA-Z]/.test(t)}function it(t){return/[a-zA-Z0-9]/.test(t)}function ot(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(it(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 at(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const ct=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}(),lt=ct,ut=ct,ht=ct,ft=ct,dt=ct,pt=(...t)=>{lt&&console.log("🔧",...t)},mt=(...t)=>{ut&&console.log("🎯",...t)},yt=(...t)=>{ht&&console.log("📝",...t)},vt=(...t)=>{ft&&console.log("🔍",...t)},gt=(...t)=>{dt&&console.log("🚀",...t)};let bt=!1,Et=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(bt=!0,Et=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let wt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class xt{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(xt.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const r=t.toLowerCase();return!!/\bjs\b/.test(r)||!!/\btell\b/.test(r)}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(bt){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(!bt)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(),Et){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});Et.dispatchEvent(e)}}(a),r=a,wt.totalParses++,r.semanticSuccess?wt.semanticSuccesses++:r.fallbackTriggered?wt.semanticFallbacks++:wt.traditionalParses++,wt.confidenceHistory.push(r.confidence),wt.confidenceHistory.length>100&&wt.confidenceHistory.shift(),wt.averageConfidence=wt.confidenceHistory.reduce((t,e)=>t+e,0)/wt.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 kt(t){return t.kind===P.IDENTIFIER&&w.has(t.value.toLowerCase())}function At(t){return t.kind===P.IDENTIFIER&&D.has(t.value.toLowerCase())}function St(t){return t.kind===P.IDENTIFIER&&M.has(t.value.toLowerCase())}function Ct(t){return t.kind===P.IDENTIFIER&&R.has(t.value.toLowerCase())}function Nt(t){return j.has(t.value.toLowerCase())}function Tt(t){return t.kind===P.IDENTIFIER}function Ot(t){return t.kind===P.SELECTOR}function Lt(t){return t.kind===P.SELECTOR&&!t.value.startsWith("<")}function $t(t){return t.kind===P.STRING||t.kind===P.NUMBER||t.kind===P.TEMPLATE}function Rt(t){return t.kind===P.IDENTIFIER}function It(t){return t.kind===P.TIME}function jt(t){return t.kind===P.SYMBOL}function Mt(t){return t.kind===P.COMMENT}function Dt(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 Pt(t){return t.kind===P.STRING}function Vt(t){return t.kind===P.NUMBER}function Bt(t){if(t.kind===P.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function Ft(t){return t.kind===P.TEMPLATE}function _t(t){return t.kind===P.SELECTOR&&t.value.startsWith("<")}function qt(t){return t.kind===P.SELECTOR&&t.value.startsWith("#")}function Ht(t){return t.kind===P.SELECTOR&&t.value.startsWith(".")}function Ut(t){return t.kind===P.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function Wt(t){if(t.kind!==P.OPERATOR)return!1;const e=t.value.toLowerCase();return!I.has(e)&&!j.has(e)}function zt(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function Jt(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 Gt(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 Xt(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Yt(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Kt(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Qt(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}xt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const te=[{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 ee(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const re=[t,n,e,r];function ne(t,e=[]){if(t.isAtEnd())return!0;for(const e of re)if(t.check(e))return!0;for(const r of e)if(t.check(r))return!0;return!!t.checkIsCommand()}function se(t,e=[]){if(!ne(t,e))return t.parseExpression()}function ie(t,e,r){return!!t.check(e)&&(t.advance(),r.push(t.createIdentifier(e)),!0)}function oe(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function ae(t,e){return!!t.check(e)&&(t.advance(),!0)}class ce{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new ce(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 ce(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 ce(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 ce(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 le(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})}for(;!ne(t);)r.push(t.parsePrimary());let a=-1,c="on";for(let t=0;r.length>t;t++){const e=r[t],n=e.name||e.value;if(!("identifier"!==e.type&&"literal"!==e.type&&"keyword"!==e.type||"on"!==n&&"to"!==n)){a=t,c=n;break}}const l=[];if(-1===a)l.push(...r);else{const e=r.slice(0,a),n=r.slice(a+1);l.push(...e),l.push(t.createIdentifier(c)),l.push(...n)}return ce.fromIdentifier(e).withArgs(...l).endingAt(t.getPosition()).build()}function ue(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 ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function he(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(Xt(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=he(n,t);i.push(Xt([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(Xt(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(Xt([t],{start:s.start,end:n.getPosition().end,line:s.line,column:s.column}))}}return ce.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function fe(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=ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function de(t,e){const r=[],n=se(t,[f]);n&&r.push(n),ie(t,f,r);const s=se(t);return s&&r.push(s),ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function pe(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=se(t,[n]);i&&r.push(i),ie(t,n,r);const o=se(t,[f,m,s]);if(o&&r.push(o),oe(t,[f,m],r)){const e=se(t);e&&r.push(e)}return ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=se(t,[f,m]);if(i&&r.push(i),oe(t,[f,m],r)){const e=se(t);e&&r.push(e)}return ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function me(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)?(ae(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?ce.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const ye=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function ve(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,e){if(!t.check(b))return null;const r=t.savePosition();t.advance();const n=t.peek(),s=t.peekAt(1);if(n&&s&&s.value===p){const r=t.advance();if(t.check(p)){t.advance();const n=t.advance(),s=n.value.startsWith("#");return{type:"propertyOfExpression",property:{type:"identifier",name:r.value,start:r.start,end:r.end},target:{type:s?"idSelector":"cssSelector",value:n.value,start:n.start,end:n.end},start:e,end:t.savePosition()}}return t.restorePosition(e),null}if(n&&s&&s.value===h){const e=t.advance();return{type:"identifier",name:e.value,start:e.start,end:e.end}}return t.restorePosition(r),null}(s,o),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:(o=Zt(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),a={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},c={start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1},{type:"propertyOfExpression",property:o,target:a,start:c.start,end:c.end,line:c.line,column:c.column}),tokens:[]}}}var o,a,c;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),ce.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function ge(t,e){const r=[];for(;!ne(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function be(t){if(t.isAtEnd())return!0;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ne(t)}function Ee(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function we(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}}class xe{constructor(t,e,r){this.current=0,this.warnings=[],this.tokens=t,this.keywordResolver=e?.keywords,this.registryIntegration=e?.registryIntegration,e?.semanticAnalyzer&&e?.language&&(this.semanticAdapter=new xt({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(){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")){yt("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];yt(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let r=0;for(;!this.isAtEnd()&&this.check("on");){yt(`✅ PARSER: Parsing event handler #${r+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(yt("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),r++,yt(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),yt(`✅ 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 yt("⚠️ 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};yt("✅ PARSER: No more event handlers, at end of input");break}}return yt(`✅ 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.parseAssignment()}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(xe.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(xe.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()){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 me(s,i);case"trigger":case"send":return le(s,i);case"remove":return de(s,i);case"toggle":return pe(s,i);case"set":return ve(s,i);case"halt":return ue(s,i);case"measure":return fe(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;for(;!t.check(r)&&!t.isAtEnd();)t.advance();const i=t.peek().start;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 ce.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 ce.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();ye.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),ce.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 ce.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return ge(s,i)}}(this.getContext(),s)}parsePutCommand(t){return me(this.getContext(),t)}parseSetCommand(t){return ve(this.getContext(),t)}parseHaltCommand(t){return ue(this.getContext(),t)}parseMeasureCommand(t){return fe(this.getContext(),t)}parseTriggerCommand(t){return le(this.getContext(),t)}parseCommandListUntilEnd(){const t=[];for(yt("🔄 parseCommandListUntilEnd: Starting to parse command list");!this.isAtEnd()&&!this.check("end");){yt("📍 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){yt(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&&(yt("⚠️ parseCommandListUntilEnd: Command parsing added error, restoring error state. Error was:",this.error.message),this.error=n),r&&(yt("✅ Parsed command:",r.name),t.push(r),e=!0)}catch(t){yt("⚠️ parseCommandListUntilEnd: Command parsing threw exception, restoring error state:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&yt("❌ IDENTIFIER is not a command:",this.peek().value);if(!e){yt("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(yt("📍 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(","));)yt("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))yt("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){yt("📍 No separator and no command, breaking. Current token:",this.peek().value);break}yt("✅ Next token is a command, continuing without separator")}}if(yt('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw yt('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return yt('✅ Found "end", consuming it'),this.advance(),yt("✅ 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();Tt(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(yt("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!Tt(e)&&!St(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),yt("✅ Got event name:",h,"Next token:",t.peek().value),yt('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){yt('✅ Found "from", advancing...'),t.advance(),yt('📍 After consuming "from", current token:',t.peek().value),ae(t,b)&&yt('✅ Found "the", advancing...');const e=t.peek();yt("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),yt("✅ After parsePrimary, eventTarget:",p)}else yt('❌ 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();Tt(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(Yt(g,k)),v&&r.push(v),m&&r.push(m),E&&r.push(E),h&&r.push(Yt(h,k)),p&&r.push(p),w&&r.push(Yt(w,k)),r.push(Xt(x,{...k,end:k.end||0})),ce.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(!Tt(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();Tt(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(Yt(n,c)),r.push(s),o&&r.push(Yt(o,c)),r.push(Xt(a,{...c,end:c.end||0})),ce.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()){const n=t.parsePrimary();return r.push(n),ce.from(e).withArgs(...r).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const n=[];do{const e=t.peek();if(!Tt(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(!Tt(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(),ae(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};r.push(Qt(n.map(t=>Kt([{key:Zt("name",i),value:Jt(t.name,`"${t.name}"`,i)},{key:Zt("args",i),value:Qt(t.params.map(t=>Jt(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return ce.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(Kt(n.map(t=>({key:t.name?Zt(t.name,s):Jt("_positional","_positional",s),value:t.value})),s))}}return ce.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(Tt(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 ce.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=se(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=se(t);e&&r.push(e)}return ce.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return he(this.getContext(),t)}parseRemoveCommand(t){return de(this.getContext(),t)}parseToggleCommand(t){return pe(this.getContext(),t)}parseRegularCommand(t){return ge(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=jt(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()&&Tt(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(Dt)||this.matchPredicate(At)||this.matchPredicate(Ct)||this.matchPredicate(kt)||this.matchPredicate(St))){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(jt(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(Dt))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(Dt))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(!(xe.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||Dt(n)&&!this.isCommand(n.value)||Ct(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}}),xe.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&&(yt("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return yt("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){yt("🔧 parseEventHandler: ENTRY - parsing event handler");const t=[],e=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(e),yt("🔧 parseEventHandler: Parsed first event name: "+e);this.check("or");){this.advance(),yt("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),yt("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(yt("🔧 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,yt(`🔧 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"),yt("🔧 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,yt("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=!0,yt("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=!0,yt("🔧 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,yt(`🔧 parseEventHandler: Parsed modifier '.debounce(${r})'`)):(s.throttle=r,yt(`🔧 parseEventHandler: Parsed modifier '.throttle(${r})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else yt(`🔧 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,yt(`🔧 parseEventHandler: Parsed '${t} at ${r.value}' (${n}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);s[e]=r,yt(`🔧 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&&yt("🔧 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,yt(`🔧 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,yt("🔧 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(yt("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),yt("🔧 parseEventHandler: Parsed watch target expression"));const u=[];for(yt(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(yt(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){yt("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())yt("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){yt("✅ 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),yt("✅ 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){yt("⚠️ 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 yt(`🔧 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.peek().value;this.advance();const r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Dt(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")||(yt("⚠️ 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"));)yt("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){yt('✅ 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}this.addError("Expected command, got: "+this.peek().value);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 te.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return ee(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!ne(t,["catch","finally",...n.keywords])&&!ee(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&ee(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&ee(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!ee(t.peek(),n.keywords))break}const o=ce.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?(yt(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(yt(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return yt("[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(kt(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()&&!be(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"),ce.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=Ee(t)?we(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||ae(t,"a")||ae(t,"an"),r.as=t.parsePrimary();const s=ce.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=Jt(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=Gt(n,i,o,c),u=[a,Zt(h,c),l];return ce.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(jt(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)&&yt(`💡 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 Jt(t,e,this.getPosition())}createIdentifier(t){return Zt(t,this.getPosition())}createBinaryExpression(t,e,r){return Gt(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(yt(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return yt("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return yt(`✅ 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 yt(`✅ 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!(!Wt(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(Lt)}matchSelector(){return this.matchPredicate(Lt)}checkAnySelector(){return this.checkPredicate(Ot)}checkLiteral(){return this.checkPredicate($t)}checkIdentifierLike(){return this.checkPredicate(Tt)}checkIsCommand(){return this.checkPredicate(kt)}checkCommandTerminator(){return this.checkPredicate(zt)}checkReference(){return this.checkPredicate(Rt)}checkTimeExpression(){return this.checkPredicate(It)}checkEvent(){return this.checkPredicate(St)}checkContextVar(){return this.checkPredicate(Ct)}checkComment(){return this.checkPredicate(Mt)}checkIdentifier(){return this.checkPredicate(Dt)}checkKeyword(){return this.checkPredicate(At)}checkString(){return this.checkPredicate(Pt)}matchString(){return this.matchPredicate(Pt)}checkNumber(){return this.checkPredicate(Vt)}matchNumber(){return this.matchPredicate(Vt)}checkBoolean(){return this.checkPredicate(Bt)}matchBoolean(){return this.matchPredicate(Bt)}checkTemplateLiteral(){return this.checkPredicate(Ft)}matchTemplateLiteral(){return this.matchPredicate(Ft)}checkQueryReference(){return this.checkPredicate(_t)}matchQueryReference(){return this.matchPredicate(_t)}checkIdSelector(){return this.checkPredicate(qt)}checkClassSelector(){return this.checkPredicate(Ht)}checkCssSelector(){return this.checkPredicate(Ut)}checkBasicOperator(){return this.checkPredicate(Wt)}matchBasicOperator(){return this.matchPredicate(Wt)}matchTimeExpression(){return this.matchPredicate(It)}matchIdentifierLike(){return this.matchPredicate(Tt)}matchComparisonOperator(){return this.matchPredicate(Nt)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Dt,t)}consumeIdentifierLike(t){return this.consumePredicate(Tt,t)}consumeEvent(t){return this.consumePredicate(St,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)}}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 ke(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&&(W(e),r>e.position);){const r=t[e.position];if("-"!==r||"-"!==H(e,1))if('"'!==r){if("'"===r||"'"===r){const t=H(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)G(e);else{const t=e.position;U(e),U(e),z(e,V.OPERATOR,"'s",t)}continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===H(e,1)){const t=e.position;U(e),U(e),z(e,V.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)&&st(H(e))){Y(e);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const t=e.tokens[e.tokens.length-1],r=t&&(t.kind===V.EVENT||t.kind===V.IDENTIFIER&&M.has(t.value))&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==V.IDENTIFIER&&t.kind!==V.CONTEXT_VAR&&")"!==t.value&&"]"!==t.value||r)&&r?(z(e,V.SYMBOL,"["),U(e)):(z(e,V.OPERATOR,"["),U(e));continue}if("]"!==r){if("$"===r){const t=H(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){nt(e);continue}}at(r)?tt(e):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(z(e,V.UNKNOWN,r),U(e)):rt(e):et(e)}else z(e,V.OPERATOR,"]"),U(e)}else z(e,V.OPERATOR,"}"),U(e);else z(e,V.OPERATOR,"{"),U(e);else Q(e)}else Y(e);else ot(e)?K(e):tt(e);else X(e)}else G(e);else Z(e)}return e.tokens}(t);return new xe(r,e,t).parse()}xe.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),xe.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ae{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 Se(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ce(t){return{ok:!0,value:t}}function Ne(t){return{ok:!1,error:t}}function Te(t){return!0===t.ok}class Oe{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&>(`CleanupRegistry: Removed listener '${r}'`)},description:r+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&>("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&>("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&>("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&>("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&>(`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&>("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&>(`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&>("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&>(`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 Le=new Map;function $e(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||Le,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class Re{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 Ie{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 je=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 Me(t){const e=je.get("String");return e?e.isType(t):"string"==typeof t}function De(t){const e=je.get("Number");return e?e.isType(t):"number"==typeof t}function Pe(t){const e=je.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ve(t){const e=je.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Be(t){const e=je.get("Function");return e?e.isType(t):"function"==typeof t}function Fe(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function _e(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 He(t,e){return qe.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Ue={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=>Fe(t)?t.tabIndex:void 0,hidden:t=>Fe(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 We(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 He(t,e.slice(1));const r=Ue[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return He(t,e);const n=t[e];return Be(n)?n.bind(t):n}function ze(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 Je(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function Ze(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 Ge(t,e){if(t.includes(".")){const r=t.split(".");let n=Ze(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return Ze(t,e)}async function Xe(t,e){if(vt(`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 vt(`RESOLVE: Found '${t}' in locals:`,r),r}if(e.globals&&e.globals.has(t)){const r=e.globals.get(t);return vt(`RESOLVE: Found '${t}' in globals:`,r),r}if(e.variables&&e.variables.has(t)){const r=e.variables.get(t);return vt(`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 vt(`RESOLVE: Property access failed at '${r[t-1]}'`);s=s[r[t]]}return vt(`RESOLVE: Property access '${t}' =`,s),s}}return t}async function Ye(t,e){vt("EVAL: Evaluating expression:",t);const r=t.match(/^(.+?)\s*\?(?![\.\[])\s*(.+?)\s*:\s*(.+)$/);if(r){const[,t,n,s]=r;vt("EVAL: Parsed ternary:",{conditionExpr:t,trueExpr:n,falseExpr:s});const i=await Xe(t.trim(),e);if(vt("EVAL: Ternary condition value:",i),i){const t=await Xe(n.trim(),e);return vt("EVAL: Ternary returned true branch:",t),t}{const t=await Xe(s.trim(),e);return vt("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;vt("EVAL: Parsed arithmetic:",{left:t,operator:r,right:s});const i=await Xe(t.trim(),e),o=await Xe(s.trim(),e);vt("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 vt("EVAL: Arithmetic result:",t),t}}const s=await Xe(t.trim(),e);return vt("EVAL: Fallback result:",s),s}function Ke(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 Qe(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=ze(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 tr{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 vt("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);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return Ce(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ne({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ne({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ne({type:"break"});if(e.isContinue)return Ne({type:"continue"});if(e.isReturn)return Ne({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||"";vt("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 Ge(i,e);vt(`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;vt("TEMPLATE: Evaluating expression:",i);const l=i.trim();e.locals.has(l)?(c=e.locals.get(l),vt(`TEMPLATE: Found in locals: ${l} =`,c)):e.globals&&e.globals.has(l)?(c=e.globals.get(l),vt(`TEMPLATE: Found in globals: ${l} =`,c)):e.variables&&e.variables.has(l)?(c=e.variables.get(l),vt(`TEMPLATE: Found in variables (legacy): ${l} =`,c)):(c=await Ye(i,e),vt(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return Ye(t,e)}async resolveValue(t,e){return Xe(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 vt("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=ze(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=ze(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?He(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 Ke(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=Ke(c),r=Ke(l);if("string"==typeof t||"string"==typeof r){const n=s.get("stringConcatenation");if(n){vt("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){vt("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 Ke(c)-Ke(l);case"*":return Ke(c)*Ke(l);case"/":return Ke(c)/Ke(l);case"%":case"mod":return Ke(c)%Ke(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 Qe(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 Qe(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=Je(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?He(e.me,t.attributeName):"@"+t.attributeName}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=ze(n);return"string"==typeof i&&_e(s)?We(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=Je(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=Je(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=Je(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=_e(r)?We(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=_e(s)?We(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const er={1:"one",2:"two",3:"three",4:"four",5:"five"};function rr(t,e,r,n){if(t.length!==e){return`${r} requires exactly ${s=e,er[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`}var s;return null}function nr(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function sr(t,e,r){return rr(t,1,e,r)??nr(t,0,e,r)}function ir(t,e){return rr(t,2,e,"left, right")}function or(){return null}function ar(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 cr(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function lr(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const ur="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 hr;function fr(){return hr({validate:t=>({success:!0,data:t})})}function dr(t,e){if(ur)return fr();const r=hr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:lr("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:lr("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:lr("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:!1,error:lr("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=()=>dr(t,{strict:!0}),r}hr=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 hr(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:lr("runtime-error",`String must be at least ${t} characters long`)}:n}};return hr(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:lr("runtime-error",`String must be at most ${t} characters long`)}:n}};return hr(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 hr(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:lr("runtime-error",e||"Refinement validation failed")}:s}};return hr(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 pr=t=>function(t={}){return ur?fr():hr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:lr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:lr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:lr("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:lr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:lr("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),mr=t=>function(t={}){return ur?fr():hr({validate:e=>{const r=Number(e);return isNaN(r)?{success:!1,error:lr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:!1,error:lr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:!1,error:lr("runtime-error","Number must be at most "+t.max)}:{success:!0,data:r}}})}(t||{}),yr=()=>ur?fr():hr({validate:t=>"boolean"!=typeof t?{success:!1,error:lr("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),vr=t=>dr(t),gr=t=>function(t){return ur?fr():hr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:lr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:lr("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:lr("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(t),br=()=>fr(),Er=()=>fr(),wr=()=>function(t,e="Custom validation failed"){return ur?fr():hr({validate:r=>t(r)?{success:!0,data:r}:{success:!1,error:lr("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class xr{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||De(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":Ve(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":Me(t)?"String":De(t)?"Number":Pe(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):Me(t)?t.split(""):null==t?[]:Ve(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(De(t)&&Number.isFinite(t))return t;if(Me(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Pe(t)?t?1:0:null}}const kr=vr({selector:pr().min(1),single:yr().optional().default(!1)});new class extends xr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=wr(),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 xr{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=wr(),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 xr{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=wr(),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 xr{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=kr,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 Ar={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:or},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:or},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:or},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:or},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:or},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=>sr(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=>sr(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=>sr(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=>sr(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:or},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:or},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:or},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=>sr(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=>cr(t,1,2,"styleRef","property, optional element")??nr(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=>rr(t,2,"possessiveStyleRef","possessor, property")??nr(t,0,"possessiveStyleRef","possessor")??nr(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=>rr(t,2,"ofStyleRef","property, reference")??nr(t,0,"ofStyleRef","property")??nr(t,1,"ofStyleRef","reference")}};class Sr{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 Cr=new class{constructor(){this.domQueryCache=new Sr(200,3e3),this.exprResultCache=new Sr(500,2e3),this.cssMatchCache=new Sr(100,5e3),this.formValueCache=new Sr(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(()=>{Cr.cleanup()},1e4);const Nr=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=Cr.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 Tr(){Cr.cleanup(),Nr.getMetrics().memoryUsage>52428800&&Nr.reset()}let Or=null;function Lr(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 Lr(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 $r(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 Rr(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=$r(t),n=$r(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 Ir(t,e);case"!=":return!Ir(t,e);default:return!1}}function Ir(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?Ir(t?1:0,e):"boolean"==typeof e?Ir(t,e?1:0):t+""==e+""}function jr(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){Or&&clearInterval(Or),Or=setInterval(Tr,t)}();const Mr=vr({left:br().describe("Left operand value"),right:br().describe("Right operand value")}).strict(),Dr=vr({operand:br().describe("Operand value to negate")}).strict();function Pr(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends xr{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=Mr,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 xr{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=Mr,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 xr{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=Dr,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 Vr=gr([br(),br()]),Br=gr([br(),pr()]),Fr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return jr(this,t,[e,r],e==r,n)}catch(s){throw jr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>ir(t,"equals"),inputSchema:Vr,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"]}},_r={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&&jr(this,t,[e,r],i,s),i},validate:t=>ir(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&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"notEquals")},Hr={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&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"strictNotEquals")},Ur={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=Rr(e,r,"<");return n&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"lessThan")},Wr={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=Rr(e,r,"<=");return n&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"lessThanOrEqual")},zr={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=Rr(e,r,">");return n&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"greaterThan")},Jr={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=Rr(e,r,">=");return n&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"greaterThanOrEqual")},Zr={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return jr(this,t,[e,r],e&&r,n)}catch(s){throw jr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>ir(t,"and"),inputSchema:Vr,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"]}},Gr={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&&jr(this,t,[e,r],i,s),i},validate:t=>ir(t,"or")},Xr={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&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"not","operand")},Yr={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||(Me(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!Ve(e)||0!==Object.keys(e).length)),r&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"isEmpty","value")},Kr={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:!(Me(e)||e instanceof Node||e instanceof Element||!Ve(e)||0!==Object.keys(e).length)),r&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"no","value")},Qr={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 Yr.evaluate(t,e);return r&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"isNotEmpty","value")},tn={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&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"exists","value")},en={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&&jr(this,t,[e],s,n),s},validate:t=>rr(t,1,"doesNotExist","value")},rn={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(Pr(e)&&Pr(r))return i=e.contains(r),n&&jr(this,t,[e,r],i,s),i;if(Me(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Pr(r))return i=o.contains(r),n&&jr(this,t,[e,r],i,s),i;if(o&&Me(r)&&r.match(/^[.#][\w-]+$/)){const a=document.querySelector(r);return i=!!a&&o.contains(a),n&&jr(this,t,[e,r],i,s),i}}if(Me(r)&&r.match(/^[.#][\w-]+$/)&&Pr(e)){const o=document.querySelector(r);return i=!!o&&e.contains(o),n&&jr(this,t,[e,r],i,s),i}}return i=Me(e)&&Me(r)||Array.isArray(e)?e.includes(r):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(r):!(!Ve(e)||!Me(r))&&r in e,n&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"contains","container, value")},nn={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 rn.evaluate(t,e,r);return n&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"doesNotContain","container, value")},sn={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=!(!Me(e)||!Me(r))&&e.startsWith(r);return n&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"startsWith","str, prefix")},on={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=!(!Me(e)||!Me(r))&&e.endsWith(r);return n&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"endsWith","str, suffix")},an={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,r){const n=Date.now();try{let s;if(e instanceof Element&&Me(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 Cr.matches(t,e)}(e,t)}catch(t){s=!1}else s=!1}else if(Me(e)&&Me(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 jr(this,t,[e,r],s,n)}catch(s){throw jr(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>rr(t,2,"matches","element, selector"),inputSchema:Br,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"]}},cn={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&&Me(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&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"has","element, selector")},ln={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 cn.evaluate(t,e,r);return n&&jr(this,t,[e,r],i,s),i},validate:t=>rr(t,2,"doesNotHave","element, selector")},un={equals:Fr,strictEquals:_r,notEquals:qr,strictNotEquals:Hr,lessThan:Ur,lessThanOrEqual:Wr,greaterThan:zr,greaterThanOrEqual:Jr,and:Zr,or:Gr,not:Xr,no:Kr,isEmpty:Yr,isNotEmpty:Qr,exists:tn,doesNotExist:en,contains:rn,doesNotContain:nn,startsWith:sn,endsWith:on,matches:an,has:cn,doesNotHave:ln};function hn(t,e,r,n,s="runtime-error"){return{success:!1,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function fn(t,e){return{success:!0,value:t,type:e}}function dn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const pn={Array:(t,e)=>{try{return Array.isArray(t)?fn(t,"array"):t instanceof NodeList?fn(Array.from(t),"array"):fn(null==t?[]:[t],"array")}catch(t){return hn("Array","ARRAY_CONVERSION_FAILED",dn("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?fn("","string"):Me(t)?fn(t,"string"):Ve(t)?fn(JSON.stringify(t),"string"):fn(t+"","string")}catch(t){return hn("String","STRING_CONVERSION_FAILED",dn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Pe(t))return fn(t,"boolean");if(null==t)return fn(!1,"boolean");if(Me(t)){const e=t.toLowerCase().trim();return fn("false"!==e&&"0"!==e&&""!==e,"boolean")}return De(t)?fn(0!==t&&!isNaN(t),"boolean"):fn(!!t,"boolean")}catch(t){return hn("Boolean","BOOLEAN_CONVERSION_FAILED",dn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(De(t))return fn(t,"number");if(null==t)return fn(0,"number");const e=Number(t);return isNaN(e)?hn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):fn(e,"number")}catch(t){return hn("Number","NUMBER_CONVERSION_FAILED",dn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=pn.Number(t,e);return r.success?fn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=pn.Number(t,e);return r.success?fn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return fn(t,"object");if(null==t)return fn(new Date(""),"object");if(Me(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return fn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?hn("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"):fn(e,"object")}catch(t){return hn("Date","DATE_CONVERSION_FAILED",dn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return fn(JSON.stringify(t),"string")}catch(t){return hn("JSON","JSON_STRINGIFY_FAILED",dn("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(Ve(t))return fn(t,"object");if(Me(t))try{return fn(JSON.parse(t),"object")}catch(t){return hn("Object","JSON_PARSE_FAILED",dn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return fn({},"object")}catch(t){return hn("Object","OBJECT_CONVERSION_FAILED",dn("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 fn(gn(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=bn(e);void 0!==t&&(r[e.name]=t)}}),fn(r,"object")}return fn({},"object")}catch(t){return hn("FormValues","FORM_VALUES_EXTRACTION_FAILED",dn("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},mn=vr({value:Er(),type:pr().min(1)}),yn=vr({value:Er(),type:pr().min(1)});new class extends xr{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=mn,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=pn.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=pn[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=pn[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 xr{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=yn,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=Me(s);break;case"number":a=De(s)&&!isNaN(s);break;case"boolean":a=Pe(s);break;case"object":a=Ve(s);break;case"array":a=Array.isArray(s);break;case"function":a=Be(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||Ve(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 vn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":Me(t)?t:Ve(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Pe(t))return t;if(null==t)return!1;if(Me(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return De(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(De(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(De(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(!De(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=vn.Number(t);return Math.trunc(e)},Float:t=>{const e=vn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(Me(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(Ve(t))return t;if(Me(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{Me(t)||(t=vn.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>Me(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:vn.String(t)).join(""):t instanceof Element?t.outerHTML:vn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return gn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=bn(t))}),r}return{}},"Values:Form":(t,e)=>{const r=vn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=vn.Values(t,e);return JSON.stringify(r)}};function gn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=bn(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 bn(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 En={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 vn.Number(r).toFixed(t||2)}let s=vn[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=vn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>rr(t,2,"as","value, type")??nr(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(!Me(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 Me(r);case"number":return De(r)&&!isNaN(r);case"boolean":return Pe(r);case"object":return Ve(r);case"array":return Array.isArray(r);case"function":return Be(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||Ve(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>rr(t,2,"is","value, type")??nr(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>rr(t,1,"async","expression")}},wn={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"},xn=vr({collection:br().describe("Collection to operate on (array, NodeList, or string)")}).strict(),kn=vr({collection:br().describe("Collection to access"),index:mr().describe("Index position to access")}).strict(),An=vr({collection:br().describe("Collection to select random item from")}).strict();function Sn(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?Sn(n,e):null}function Cn(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?Cn(n,e):null}function Nn(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 xr{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=xn,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:wn[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 xr{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=xn,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:wn[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 xr{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=kn,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:wn[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 xr{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=An,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:wn[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 Tn={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:Me(r)?r.length>0?r[0]:null:Ve(r)&&"length"in r&&De(r.length)&&r.length>0?r[0]:null},validate:t=>ar(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 Me(r)?r.length>0?r[r.length-1]:null:Ve(r)&&"length"in r&&De(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>ar(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!De(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(Me(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Ve(i)&&"length"in i&&De(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>cr(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?Sn(s,r):s.nextElementSibling:null},validate:t=>ar(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?Cn(s,r):s.previousElementSibling:null},validate:t=>ar(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=Nn(t);for(const t of n)if(Nn(t)>s)return t;return null}(i,r,o):null},validate:t=>cr(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=Nn(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>Nn(e))return e}return null}(i,r,o):null},validate:t=>cr(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")}},On=new Set(["__proto__","constructor","prototype"]),Ln={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 We(r,n);if(Ve(r)){if(On.has(n))return;return r[n]}return r[n]}},validate:t=>rr(t,2,"possessive","element, property")??nr(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 We(t.me,r);if(Ve(t.me)){if(On.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>sr(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 We(n,r);if(Ve(n)){if(On.has(r))return;return n[r]}return n[r]},validate:t=>sr(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 We(t.you,r);if(Ve(t.you)){if(On.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>sr(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 We(n,r);if(Ve(n)){if(On.has(r))return;return n[r]}return n[r]}},validate:t=>rr(t,2,"of","property, object")??nr(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=>cr(t,1,2,"attribute","attributeName, optional element")??nr(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=>cr(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??nr(t,0,"attributeWithValue","attribute name")??nr(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=>sr(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=>sr(t,"idReference","idValue")}},$n=vr({value:pr().describe("String literal value")}).strict(),Rn=vr({value:mr().describe("Number literal value")}).strict(),In=vr({value:yr().describe("Boolean literal value")}).strict(),jn=vr({left:br().describe("Left operand"),right:br().describe("Right operand")}).strict();const Mn={stringLiteral:new class extends xr{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=$n,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 xr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Rn,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 xr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=In,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 xr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=jn,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=Lr(e.left,"left operand")+Lr(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 xr{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=jn,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=jn.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(Me(t))return t;if(De(t))return""+t;if(Pe(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends xr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=jn,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=Lr(e.left,"left operand")*Lr(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 Dn extends tr{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(Ar),this.registerCategory(un),this.registerCategory(En),this.registerCategory(Tn),this.registerCategory(Ln),this.registerCategory(Mn)}}class Pn{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 Vn{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new Dn,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(pt(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return void pt(`CommandAdapterV2: '${this.name}' intercepted by hook`);t.locals||(t.locals=new Map),t.locals.set("__evaluator",this.expressionEvaluator);const s=Pn.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(pt(`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 pt(`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 pt(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;return pt("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),pt("CommandAdapterV2: Command result:",o),Object.assign(t,Pn.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(Un(t)||pt(`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 Bn{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);gt(`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();gt(`CommandRegistryV2: Registering command '${r}'`),this.implementations.set(r,t);const n=new Vn(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 Fn=null;function _n(){return Fn||(Fn=function(t){const e=t?.commands??new Bn,r=t?.eventSources??new Re,n=t?.context??new Ie,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}()),Fn}class qn{constructor(t={}){this.contextCache=new WeakMap;const e=_n();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,gt(`[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),gt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return gt("[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 gt(`[RegistryIntegration] Found event source for '${t}'`),e;const r=this.eventSourceRegistry.findSourceForEvent(t);if(r){const e=this.eventSourceRegistry.get(r);return gt(`[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 gt(`[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,gt("[RegistryIntegration] Destroyed")}}function Hn(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 Un(t){return t instanceof Error&&(null!==Se(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function Wn(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 zn(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Jn=new WeakMap;class Zn{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,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=Le,this.hookRegistry=new Ae,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Oe,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new qn("object"==typeof t.registryIntegration?t.registryIntegration:{}),gt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),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&>(`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(),gt("RuntimeBase: Destroyed")}async execute(t,e){gt(`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{switch(t.type){case"command":if(this.options.enableResultPattern)try{const r=await this.processCommandWithResult(t,e);if(!Te(r))throw Hn(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(!Te(n))throw Hn(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(!Te(r))throw Hn(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(pt(`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 Un(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=Se(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(pt(`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 Ce(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ne(e);throw console.error(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let r;for(const n of t)if("command"===n.type){const t=await this.processCommandWithResult(n,e);if(!Te(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}),Ce(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!Te(t))return t;r=t.value}return Ce(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return zn(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!Te(r))return r;const n=r.value;if(zn(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return Ce(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ne(e);throw t}}return Ce(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(Un(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(Un(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(Un(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(Un(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(Un(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}),gt(`RUNTIME BASE: Registered imperative behavior '${r}'`)):(this.behaviorRegistry.set(r,{name:r,parameters:n,eventHandlers:s,initBlock:i}),gt(`RUNTIME BASE: Registered behavior '${r}'`))}async installBehaviorOnElement(t,e,r){gt("BEHAVIOR: installBehaviorOnElement called: "+t);const n=this.behaviorRegistry.get(t);if(!n)throw Error(`Behavior "${t}" not found`);if("imperative"===n.type&&"function"==typeof n.install)return gt(`BEHAVIOR: Installing imperative behavior '${t}'`),n.install(e,r),void gt(`BEHAVIOR: Finished installing imperative behavior '${t}'`);gt("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){gt("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))]),gt("BEHAVIOR: Init block completed for "+t)}catch(e){if(gt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Un(e)))throw e}}if(gt(`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))])}gt("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];gt(`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);gt(`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 gt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void gt(`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){gt(`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);gt(`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);gt(`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=Zn.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=Jn.get(i)??0;if(o>=100)return;if(Jn.set(i,o+1),n&&i.target instanceof Element)try{if(!i.target.matches(n)&&!i.target.closest(n))return}catch{gt(`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=Wn(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(Un(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){gt(`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){mt(`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(Un(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),gt("RUNTIME BASE: MutationObserver attached to",s,`for attribute '${e}'`)}}async setupChangeObserver(t,e,r){gt("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))),gt(`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){mt("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(Un(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),gt("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 gt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}class Gn{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=$e(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function Xn(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 Yn(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 Kn(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 Qn(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function ts(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 es(t,e){for(const r of t)e(r);return t}function rs(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function ns(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 ss(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&&os(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&&os(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&os(r)?[r]:[]}function is(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function os(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!is(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function as(t,e){return t.map(t=>{if(is(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 cs=Symbol("command:name"),ls=Symbol("command:category"),us=Symbol("command:metadata");function hs(t){return function(e,r){const n=e;n[cs]=t.name,n[ls]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function fs(t){return function(e,r){const n=e,s=n[ls];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[us]=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 ds(t){return()=>new t}function ps(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function ms(t,e){if(ps(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 vs(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return vs(e.me)}if("it"===r){if(!ps(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 vs(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(!ps(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function ys(t,e){if(Array.isArray(t))return t.filter(ps);if(t instanceof NodeList)return Array.from(t).filter(ps);if(ps(t))return[t];if(!t){const t=e.me;return t&&ps(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&ps(e.me)?[e.me]:[];if("it"===r)return ps(e.it)?[e.it]:[];if("you"===r)return e.you&&ps(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(ps)}}return[]}function vs(t){if(ps(t))return t;throw Error("Value is not an HTMLElement")}function gs(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!ps(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(!ps(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(!ps(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const bs=["on","from","to","in","with","at"];async function Es(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||!bs.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(!ps(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(ps(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(ps);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(ps);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(ps);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(!ps(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function ws(t){return"string"==typeof t&&t.trim().startsWith("*")}function xs(t,e,r){t.style.setProperty(e,r)}const ks=["dialog","details","summary","select"];function As(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 Ss(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=As(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=As(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:As(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=As(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:As(n)),extractedFromNode:!0}:{value:await e.evaluate(t,r),extractedFromNode:!1};var n}class Cs{async resolveTargets(t,e,r,n){return Es(t,e,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Ss(t,e,r)}parseClassNames(t){return ss(t)}isAttribute(t){return Qn(t.trim())}isCSSProperty(t){return ws(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>ps(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 Ns=(()=>{let t,e,r=[fs({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"]}),hs({name:"add",category:"dom"})],n=[],s=Cs;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=ts(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=as(t.classes,e);r.length>0&&rs(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,es(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":!function(t,e){rs(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}},Kn(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Xn(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}),Yn(e,n)})(),e})();const Ts=ds(Ns);function Os(t){return!!t.parentNode&&(t.remove(),!0)}let Ls=(()=>{let t,e,r=[fs({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"]}),hs({name:"remove",category:"dom"})],n=[],s=Cs;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(ps(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&ps(n[0]))return{type:"element",targets:n.filter(t=>ps(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:ts(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=as(t.classes,e);r.length>0&&rs(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,es(t.targets,t=>{t.removeAttribute(r)});break;case"styles":!function(t,e){rs(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Os(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}},Kn(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Xn(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}),Yn(e,n)})(),e})();const $s=ds(Ls);function Rs(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 Is(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Rs(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function js(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Ms(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&ns(t,r)}}function Ds(t,e,r,n){const s=Ms(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Ps(t,e,r,n){const s=Ms(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:!0}),()=>{t.removeEventListener(n,i)}}function Vs(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 Bs=/^the\s+(.+?)\s+of\s+(.+)$/i,Fs=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 _s(t){return"string"==typeof t&&Bs.test(t)}function qs(t,e){const r=t.match(Bs);if(!r)return null;try{return{element:ms(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function Hs(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]),ps(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]),ps(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]),!ps(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function Us(t,e){const{element:r,property:n}=t;n.startsWith("*")?xs(r,n.substring(1),e+""):Vs(r,n,e)}async function Ws(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=Rs(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 zs(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 ks.includes(e)}(e)}(e);if(ps(t)||Array.isArray(t)&&t.every(t=>ps(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 ks.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const Js=ds((()=>{let t,e,r=[fs({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"]}),hs({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 Ws(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 Es(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 Hs(n,e,r);if(i)return{type:"property",target:i};const{duration:o,untilEvent:a}=await Ws(t.modifiers,e,r),{value:c}=await Ss(n,e,r);if(_s(c)){const t=qs(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=zs(c,n),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=ts(u);return{type:"attribute",name:n,value:s,targets:await Es(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=function(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}(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await Es(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(ps(c))s=[c];else if(Array.isArray(c)&&c.every(t=>ps(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>ps(t))}else s=await Es([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:js(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:ss(u),targets:s,duration:o,untilEvent:a}}default:{const n=ss(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Es(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=as(t.classes,e);if(0===r.length)return[...t.targets];if(rs(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&Ds(e,"class",r[0],t.duration),t.untilEvent&&Ps(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,es(t.targets,t=>{ns(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Ds(e,"attribute",t.name,t.duration),t.untilEvent&&Ps(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return es(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)):We(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||Fs.has(n)||Fs.has(n.toLowerCase())){const r=!e;return Us(t,r),r}if("number"==typeof e){const r=0===e?1:0;return Us(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(Us(t,s),s):(t.element[n]=e,Us(t,""),"")}Us(t,!e)}(t.target),[t.target.element];case"dialog":return es(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 es(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return es(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&&Ds(e,"class",t.classA,t.duration),t.untilEvent&&Ps(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},Kn(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})());class Zs{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await Es(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=>ps(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 Gs=(()=>{let t,e,r=[fs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),hs({name:"show",category:"dom"})],n=[],s=Zs;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=>ps(t))&&"string"==typeof e.defaultDisplay}},Kn(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Xn(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}),Yn(e,n)})(),e})();const Xs=ds(Gs);let Ys=(()=>{let t,e,r=[fs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),hs({name:"hide",category:"dom"})],n=[],s=Zs;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=>ps(t))}},Kn(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Xn(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}),Yn(e,n)})(),e})();const Ks=ds(Ys);const Qs=ds((()=>{let t,e,r=[fs({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"]}),hs({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 Hs(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&&_s(t)){const e=qs(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||!ps(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>ps(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return ps(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(ps(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 ps(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(ps(t))return[t];if(Array.isArray(t)){const e=t.filter(ps);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(ps);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}},Kn(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})());function ti(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 ei(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 ri(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 ni(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:ei(t,e)}const si=ds((()=>{let t,e,r=[fs({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"]}),hs({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(ps(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&&ri(s,i,e),i}},Kn(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})()),ii=ds((()=>{let t,e,r=[fs({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"]}),hs({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 Hs(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(ps(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(_s(o)){const n=qs(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&&ws(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&&Qn(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=gs(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(ps(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&ps(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");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 Vs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return xs(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))Vs(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=gs(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 ms(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return ys(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=ms(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&&ps(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&ps(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&ps(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}}},Kn(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})());let oi=(()=>{let t,e,r=[fs({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"]}),hs({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(ps(t)){const r=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?ti(r.getAttribute(e)):ti(r[e]):ti(r.value||r.textContent)}return"string"==typeof t?"global"===r?ti(ei(t,n,"global")):t.includes(".")?function(t,e){const r=t.split("."),n=r[1],s=ni(r[0],e);return s?ti(s[n]):0}(t,n):ti("me"===t&&n.me?n.me.value||0:"it"===t?n.it||0:"you"===t&&n.you?n.you.value||0:ei(t,n)):ti(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(ps(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 ri(t,n,s,"global");if(t.includes("."))return void function(t,e,r){const n=t.split("."),s=n[1],i=ni(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);ri(t,n,s)}}(r,n,s,c,e),Object.assign(e,{it:c}),c}},Kn(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})();const ai=ds(oi),ci=ds(oi);function li(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 ui=(()=>{let t,e,r=[fs({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"]}),hs({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(ps(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(ps));else if(Array.isArray(t))s.push(...t.filter(ps));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(ps));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()]=li(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}},Kn(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})();const hi=ds(ui),fi=ds(ui);function di(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 pi(t){return new Promise(e=>setTimeout(e,t))}const mi=ds((()=>{let t,e,r=[fs({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"]}),hs({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 pi(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await di(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:Is(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:Is(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?pi(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):di(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},Kn(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})()),yi=new Map;const vi=ds((()=>{let t,e,r=[fs({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"]}),hs({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=yi.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(yi.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=yi.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&&ps(r.firstChild)?r.firstChild:r}dispatchEvent(t,e,r){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:!0,cancelable:!0}))}},Kn(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})()),gi=ds((()=>{let t,e,r=[fs({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"]}),hs({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&&ps(e.me))return e.me;if("it"===r&&ps(e.it))return e.it;if("you"===r&&ps(e.you))return e.you;const n=ei(r,e);if(ps(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)}}},Kn(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})()),bi=ds((()=>{let t,e,r=[fs({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"]}),hs({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)}},Kn(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Xn(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}),Yn(e,n)})(),e})()),Ei=function(t,e){const r=new Bn(e.expressionEvaluator);for(const e of t)r.register(e);return new Zn({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Ts(),$s(),Js(),Xs(),Ks(),Qs(),si(),ii(),ai(),ci(),fi(),hi(),mi(),vi(),gi(),bi()],{expressionEvaluator:new class extends tr{constructor(t){super();for(const e of t)this.registerCategory(e)}}([Ar,un,Mn,En,Tn])}),wi={parse:t=>ke(t),execute:async(t,e)=>{const r=function(t){if(!t)return $e();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=$e(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=ke(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await Ei.execute(n.node,r)}},xi=function(t){return new Gn(t)}(wi),ki={runtime:wi,parse:t=>wi.parse(t),execute:async(t,e)=>wi.execute(t,e),createContext:$e,attributeProcessor:xi,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)=>wi.execute(t,e),init:()=>{xi.init()}};return"undefined"!=typeof window&&(window.hyperfixi=ki,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{xi.init()}):xi.init()),ki}();
|
|
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 W(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 z(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);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&>.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 Wt(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function zt(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:"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 Kt=[{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 Qt(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const te=[t,n,e,r];function ee(t,e=[]){if(t.isAtEnd())return!0;for(const e of te)if(t.check(e))return!0;for(const r of e)if(t.check(r))return!0;return!!t.checkIsCommand()}function re(t,e=[]){if(!ee(t,e))return t.parseExpression()}function ne(t,e,r){return!!t.check(e)&&(t.advance(),r.push(t.createIdentifier(e)),!0)}function se(t,e,r){for(const n of e)if(t.check(n))return t.advance(),r.push(t.createIdentifier(n)),n;return null}function ie(t,e){return!!t.check(e)&&(t.advance(),!0)}class oe{constructor(t){this.args=[],this.isBlocking=!1,this.name=t}static from(t){const e=new oe(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 oe(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 oe(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 oe(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 ae(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})}for(;!ee(t);)r.push(t.parsePrimary());let a=-1,c="on";for(let t=0;r.length>t;t++){const e=r[t],n=e.name||e.value;if(!("identifier"!==e.type&&"literal"!==e.type&&"keyword"!==e.type||"on"!==n&&"to"!==n)){a=t,c=n;break}}const l=[];if(-1===a)l.push(...r);else{const e=r.slice(0,a),n=r.slice(a+1);l.push(...e),l.push(t.createIdentifier(c)),l.push(...n)}return oe.fromIdentifier(e).withArgs(...l).endingAt(t.getPosition()).build()}function ce(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 oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function le(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=le(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 oe.from(s).withArgs(...i).endingAt(n.getPosition()).build()}function ue(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=oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function he(t,e){const r=[],n=re(t,[f]);n&&r.push(n),ne(t,f,r);const s=re(t);return s&&r.push(s),oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function fe(t,e){const r=[];if(t.check("between")){t.advance(),r.push(t.createIdentifier("between"));const i=re(t,[n]);i&&r.push(i),ne(t,n,r);const o=re(t,[f,m,s]);if(o&&r.push(o),se(t,[f,m],r)){const e=re(t);e&&r.push(e)}return oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}const i=re(t,[f,m]);if(i&&r.push(i),se(t,[f,m],r)){const e=re(t);e&&r.push(e)}return oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function de(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)?(ie(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?oe.fromIdentifier(e).withArgs(n,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const pe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function me(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,e){if(!t.check(b))return null;const r=t.savePosition();t.advance();const n=t.peek(),s=t.peekAt(1);if(n&&s&&s.value===p){const r=t.advance();if(t.check(p)){t.advance();const n=t.advance(),s=n.value.startsWith("#");return{type:"propertyOfExpression",property:{type:"identifier",name:r.value,start:r.start,end:r.end},target:{type:s?"idSelector":"cssSelector",value:n.value,start:n.start,end:n.end},start:e,end:t.savePosition()}}return t.restorePosition(e),null}if(n&&s&&s.value===h){const e=t.advance();return{type:"identifier",name:e.value,start:e.start,end:e.end}}return t.restorePosition(r),null}(s,o),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:(o=Wt(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),a={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},c={start:i[0].start??0,end:r.end??0,line:i[0].line??1,column:i[0].column??1},{type:"propertyOfExpression",property:o,target:a,start:c.start,end:c.end,line:c.line,column:c.column}),tokens:[]}}}var o,a,c;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),oe.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function ye(t,e){const r=[];for(;!ee(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)r.push(t.parsePrimary());return oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}function ve(t){if(t.isAtEnd())return!0;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||ee(t)}function ge(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function be(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 Ee=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),we=new Set([")","]","}",","]);function xe(...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 ke(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 Ae(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 Se(t,e){return{prefix:{bp:t,handler:e??((e,r)=>({type:"unaryExpression",operator:e.value,operand:r.parseExpr(t),start:e.start}))}}}const Ce=new Map([["or",ke(10)],["||",ke(10)],["and",ke(20)],["&&",ke(20)],["==",ke(30)],["!=",ke(30)],["<",ke(30)],[">",ke(30)],["<=",ke(30)],[">=",ke(30)],["is",ke(30)],["matches",ke(30)],["contains",ke(30)],["+",{...ke(40),...Se(80)}],["-",{...ke(40),...Se(80)}],["*",ke(50)],["/",ke(50)],["%",ke(50)],["mod",ke(50)],["^",Ae(60)],["**",Ae(60)],["as",ke(70,(t,e,r)=>({type:"asExpression",expression:t,targetType:r.parseExpr(71),start:t.start}))],["not",Se(80)],["!",Se(80)],["no",Se(80)]]),Ne=new Map([["first",Se(85,(t,e)=>({type:"positionalExpression",position:"first",operand:e.parseExpr(85),start:t.start}))],["last",Se(85,(t,e)=>({type:"positionalExpression",position:"last",operand:e.parseExpr(85),start:t.start}))]]),Te=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})}}]]),Oe=new Map([["===",ke(30)],["!==",ke(30)],["is not",ke(30)],["is a",ke(30)],["is an",ke(30)],["is not a",ke(30)],["is not an",ke(30)],["is in",ke(30)],["is not in",ke(30)],["has",ke(30)],["have",ke(30)],["match",ke(30)],["include",ke(30)],["includes",ke(30)],["equals",ke(30)],["does not contain",ke(30)],["does not include",ke(30)],["in",ke(30)],["of",ke(30)],["really",ke(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",Se(80)]]),Le=new Map([["=",Ae(5)]]);xe(Ce,Ne,Te);const $e=xe(Ce,Oe,Le);class Re{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=Re.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=Re.PRATT_TABLE.get(e.value);if(!r?.infix){if(Ee.has(e.value)||we.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()&&!Re.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||Ee.has(e.value)||we.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(Re.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(Re.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()){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 de(s,i);case"trigger":case"send":return ae(s,i);case"remove":return he(s,i);case"toggle":return fe(s,i);case"set":return me(s,i);case"halt":return ce(s,i);case"measure":return ue(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;for(;!t.check(r)&&!t.isAtEnd();)t.advance();const i=t.peek().start;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 oe.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 oe.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();pe.includes(s)&&(n=s,t.advance(),r.push(t.createIdentifier(n)))}}if("delete"===n){const n=t.parseExpression();return n&&r.push(n),oe.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 oe.fromIdentifier(e).withArgs(...r).endingAt(t.getPosition()).build()}(s,i);default:return ye(s,i)}}(this.getContext(),s)}parsePutCommand(t){return de(this.getContext(),t)}parseSetCommand(t){return me(this.getContext(),t)}parseHaltCommand(t){return ce(this.getContext(),t)}parseMeasureCommand(t){return ue(this.getContext(),t)}parseTriggerCommand(t){return ae(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),ie(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})),oe.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})),oe.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()){const n=t.parsePrimary();return r.push(n),oe.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(),ie(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:Wt("name",i),value:Ut(t.name,`"${t.name}"`,i)},{key:Wt("args",i),value:Xt(t.params.map(t=>Ut(t,`"${t}"`,i)),i)}],i)),i)),s&&r.push(s)}return oe.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(Wt(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?Wt(t.name,s):Ut("_positional","_positional",s),value:t.value})),s))}}return oe.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 oe.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=re(t,[h]);e&&r.push(e)}if(t.check(h)){t.advance();const e=re(t);e&&r.push(e)}return oe.from(e).withArgs(...r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return le(this.getContext(),t)}parseRemoveCommand(t){return he(this.getContext(),t)}parseToggleCommand(t){return fe(this.getContext(),t)}parseRegularCommand(t){return ye(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(!(Re.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}}),Re.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.peek().value;this.advance();const 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=Yt(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 Kt.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return Qt(t,e)}parseMultiWordCommand(t,e){return function(t,e,r){const n=t.getMultiWordPattern(r);if(!n)return null;const s=[],i={};for(;!ee(t,["catch","finally",...n.keywords])&&!Qt(t.peek(),n.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&Qt(t.peek(),n.keywords))break}for(;!t.isAtEnd()&&Qt(t.peek(),n.keywords);){const e=t.advance().value,r=t.parseExpression();if(r&&(i[e]=r),!Qt(t.peek(),n.keywords))break}const o=oe.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()&&!ve(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"),oe.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=ge(t)?be(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||ie(t,"a")||ie(t,"an"),r.as=t.parsePrimary();const s=oe.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=zt(n,i,o,c),u=[a,Wt(h,c),l];return oe.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 Wt(t,this.getPosition())}createBinaryExpression(t,e,r){return zt(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 Ie(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)z(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)&&et(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 z(e);else W(e)}return e.tokens}(t);return new Re(r,e,t).parse()}Re.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty"]),Re.PRATT_TABLE=$e,Re.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class je{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 Me(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function De(t){return{ok:!0,value:t}}function Pe(t){return{ok:!1,error:t}}function Ve(t){return!0===t.ok}class Be{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 Fe=new Map;function _e(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||Fe,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}class qe{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 He{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 Ue=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=Ue.get("String");return e?e.isType(t):"string"==typeof t}function ze(t){const e=Ue.get("Number");return e?e.isType(t):"number"==typeof t}function Je(t){const e=Ue.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Ze(t){const e=Ue.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Ge(t){const e=Ue.get("Function");return e?e.isType(t):"function"==typeof t}function Xe(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Ye(t){return t instanceof Element}const Ke=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Qe(t,e){return Ke.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const tr={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=>Xe(t)?t.tabIndex:void 0,hidden:t=>Xe(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 er(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 Qe(t,e.slice(1));const r=tr[e.toLowerCase()];if(r)return r(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Qe(t,e);const n=t[e];return Ge(n)?n.bind(t):n}function rr(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 nr(t){return t.me?.ownerDocument??("undefined"!=typeof document?document:null)}function sr(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 ir(t,e){if(t.includes(".")){const r=t.split(".");let n=sr(r[0],e);for(let t=1;r.length>t&&null!=n;t++)n=n[r[t]];return n}return sr(t,e)}async function or(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 ar(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 or(t.trim(),e);if(pt("EVAL: Ternary condition value:",i),i){const t=await or(n.trim(),e);return pt("EVAL: Ternary returned true branch:",t),t}{const t=await or(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 or(t.trim(),e),o=await or(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 or(t.trim(),e);return pt("EVAL: Fallback result:",s),s}function cr(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 lr(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=rr(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 ur{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);default:throw Error("Unsupported AST node type for evaluation: "+t.type)}}async evaluateWithResult(t,e){try{return De(await this.evaluate(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Pe({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Pe({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Pe({type:"break"});if(e.isContinue)return Pe({type:"continue"});if(e.isReturn)return Pe({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 ir(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 ar(i,e),pt(`TEMPLATE: Evaluated expression "${i}" =`,c)),o+=c+"",a=s+1}return o}(t,e)}async evaluateSimpleExpression(t,e){return ar(t,e)}async resolveValue(t,e){return or(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=rr(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=rr(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?Qe(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 cr(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=cr(c),r=cr(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 cr(c)-cr(l);case"*":return cr(c)*cr(l);case"/":return cr(c)/cr(l);case"%":case"mod":return cr(c)%cr(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 lr(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 lr(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=nr(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?Qe(e.me,t.attributeName):"@"+t.attributeName}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=rr(n);return"string"==typeof i&&Ye(s)?er(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=nr(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=nr(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=nr(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=Ye(r)?er(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=Ye(s)?er(s,n):s[n],"function"==typeof t?t.bind(s):t}catch(t){throw Error(`Failed to access property "${n}" on target: ${t}`)}}}const hr={1:"one",2:"two",3:"three",4:"four",5:"five"};function fr(t,e,r,n){if(t.length!==e){return`${r} requires exactly ${s=e,hr[s]??s+""} argument${1===e?"":"s"}${n?` (${n})`:""}`}var s;return null}function dr(t,e,r,n){return"string"!=typeof t[e]?`${r} ${n||"argument "+(e+1)} must be a string`:null}function pr(t,e,r){return fr(t,1,e,r)??dr(t,0,e,r)}function mr(t,e){return fr(t,2,e,"left, right")}function yr(){return null}function vr(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 gr(t,e,r,n,s){return e>t.length||t.length>r?`${n} requires ${e}-${r} arguments${s?` (${s})`:""}`:null}function br(t,e,r,n=[]){return{type:t,message:e,suggestions:n,...r&&{path:r}}}const Er="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 wr;function xr(){return wr({validate:t=>({success:!0,data:t})})}function kr(t,e){if(Er)return xr();const r=wr({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:br("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:br("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:br("missing-argument",`Required field "${e}" is missing`,e)};const i=r.validate(t);if(!i.success)return{success:!1,error:br("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=()=>kr(t,{strict:!0}),r}wr=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 wr(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:br("runtime-error",`String must be at least ${t} characters long`)}:n}};return wr(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:br("runtime-error",`String must be at most ${t} characters long`)}:n}};return wr(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 wr(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:br("runtime-error",e||"Refinement validation failed")}:s}};return wr(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 Ar=t=>function(t={}){return Er?xr():wr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:br("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:br("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:br("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:br("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:br("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),Sr=t=>function(t={}){return Er?xr():wr({validate:e=>{const r=Number(e);return isNaN(r)?{success:!1,error:br("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>r?{success:!1,error:br("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&r>t.max?{success:!1,error:br("runtime-error","Number must be at most "+t.max)}:{success:!0,data:r}}})}(t||{}),Cr=()=>Er?xr():wr({validate:t=>"boolean"!=typeof t?{success:!1,error:br("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}}),Nr=t=>kr(t),Tr=t=>function(t){return Er?xr():wr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:br("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:br("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:br("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(t),Or=()=>xr(),Lr=()=>xr(),$r=()=>function(t,e="Custom validation failed"){return Er?xr():wr({validate:r=>t(r)?{success:!0,data:r}:{success:!1,error:br("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class Rr{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||ze(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":Ze(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":We(t)?"String":ze(t)?"Number":Je(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?[]:Ze(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(ze(t)&&Number.isFinite(t))return t;if(We(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Je(t)?t?1:0:null}}const Ir=Nr({selector:Ar().min(1),single:Cr().optional().default(!1)});new class extends Rr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=$r(),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 Rr{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=$r(),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 Rr{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=$r(),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 Rr{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=Ir,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 jr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me instanceof HTMLElement?t.me:null,validate:yr},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you instanceof HTMLElement?t.you:null,validate:yr},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:yr},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:yr},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:yr},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=>pr(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=>pr(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=>pr(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=>pr(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:yr},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:yr},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:yr},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=>pr(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=>gr(t,1,2,"styleRef","property, optional element")??dr(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=>fr(t,2,"possessiveStyleRef","possessor, property")??dr(t,0,"possessiveStyleRef","possessor")??dr(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=>fr(t,2,"ofStyleRef","property, reference")??dr(t,0,"ofStyleRef","property")??dr(t,1,"ofStyleRef","reference")}};class Mr{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 Dr=new class{constructor(){this.domQueryCache=new Mr(200,3e3),this.exprResultCache=new Mr(500,2e3),this.cssMatchCache=new Mr(100,5e3),this.formValueCache=new Mr(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(()=>{Dr.cleanup()},1e4);const Pr=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=Dr.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 Vr(){Dr.cleanup(),Pr.getMetrics().memoryUsage>52428800&&Pr.reset()}let Br=null;function Fr(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 Fr(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 _r(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 qr(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=_r(t),n=_r(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 Hr(t,e);case"!=":return!Hr(t,e);default:return!1}}function Hr(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?Hr(t?1:0,e):"boolean"==typeof e?Hr(t,e?1:0):t+""==e+""}function Ur(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){Br&&clearInterval(Br),Br=setInterval(Vr,t)}();const Wr=Nr({left:Or().describe("Left operand value"),right:Or().describe("Right operand value")}).strict(),zr=Nr({operand:Or().describe("Operand value to negate")}).strict();function Jr(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends Rr{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 Rr{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 Rr{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=zr,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 Zr=Tr([Or(),Or()]),Gr=Tr([Or(),Ar()]),Xr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,r){const n=Date.now();try{return Ur(this,t,[e,r],e==r,n)}catch(s){throw Ur(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>mr(t,"equals"),inputSchema:Zr,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"]}},Yr={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&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"strictEquals")},Kr={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&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"notEquals")},Qr={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&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"strictNotEquals")},tn={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=qr(e,r,"<");return n&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"lessThan")},en={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=qr(e,r,"<=");return n&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"lessThanOrEqual")},rn={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=qr(e,r,">");return n&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"greaterThan")},nn={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=qr(e,r,">=");return n&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"greaterThanOrEqual")},sn={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,r){const n=Date.now();try{return Ur(this,t,[e,r],e&&r,n)}catch(s){throw Ur(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>mr(t,"and"),inputSchema:Zr,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"]}},on={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&&Ur(this,t,[e,r],i,s),i},validate:t=>mr(t,"or")},an={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&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"not","operand")},cn={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||!Ze(e)||0!==Object.keys(e).length)),r&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"isEmpty","value")},ln={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||!Ze(e)||0!==Object.keys(e).length)),r&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"no","value")},un={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 cn.evaluate(t,e);return r&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"isNotEmpty","value")},hn={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&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"exists","value")},fn={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&&Ur(this,t,[e],s,n),s},validate:t=>fr(t,1,"doesNotExist","value")},dn={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(Jr(e)&&Jr(r))return i=e.contains(r),n&&Ur(this,t,[e,r],i,s),i;if(We(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&Jr(r))return i=o.contains(r),n&&Ur(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&&Ur(this,t,[e,r],i,s),i}}if(We(r)&&r.match(/^[.#][\w-]+$/)&&Jr(e)){const o=document.querySelector(r);return i=!!o&&e.contains(o),n&&Ur(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):!(!Ze(e)||!We(r))&&r in e,n&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"contains","container, value")},pn={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 dn.evaluate(t,e,r);return n&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"doesNotContain","container, value")},mn={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&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"startsWith","str, prefix")},yn={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&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"endsWith","str, suffix")},vn={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 Dr.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 Ur(this,t,[e,r],s,n)}catch(s){throw Ur(this,t,[e,r],!1,n,!1,s instanceof Error?s:Error(s+"")),s}},validate:t=>fr(t,2,"matches","element, selector"),inputSchema:Gr,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"]}},gn={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&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"has","element, selector")},bn={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 gn.evaluate(t,e,r);return n&&Ur(this,t,[e,r],i,s),i},validate:t=>fr(t,2,"doesNotHave","element, selector")},En={equals:Xr,strictEquals:Yr,notEquals:Kr,strictNotEquals:Qr,lessThan:tn,lessThanOrEqual:en,greaterThan:rn,greaterThanOrEqual:nn,and:sn,or:on,not:an,no:ln,isEmpty:cn,isNotEmpty:un,exists:hn,doesNotExist:fn,contains:dn,doesNotContain:pn,startsWith:mn,endsWith:yn,matches:vn,has:gn,doesNotHave:bn};function wn(t,e,r,n,s="runtime-error"){return{success:!1,error:{name:t+"ConversionError",type:s,message:r,code:e,suggestions:n}}}function xn(t,e){return{success:!0,value:t,type:e}}function kn(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}const An={Array:(t,e)=>{try{return Array.isArray(t)?xn(t,"array"):t instanceof NodeList?xn(Array.from(t),"array"):xn(null==t?[]:[t],"array")}catch(t){return wn("Array","ARRAY_CONVERSION_FAILED",kn("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?xn("","string"):We(t)?xn(t,"string"):Ze(t)?xn(JSON.stringify(t),"string"):xn(t+"","string")}catch(t){return wn("String","STRING_CONVERSION_FAILED",kn("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(Je(t))return xn(t,"boolean");if(null==t)return xn(!1,"boolean");if(We(t)){const e=t.toLowerCase().trim();return xn("false"!==e&&"0"!==e&&""!==e,"boolean")}return ze(t)?xn(0!==t&&!isNaN(t),"boolean"):xn(!!t,"boolean")}catch(t){return wn("Boolean","BOOLEAN_CONVERSION_FAILED",kn("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(ze(t))return xn(t,"number");if(null==t)return xn(0,"number");const e=Number(t);return isNaN(e)?wn("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):xn(e,"number")}catch(t){return wn("Number","NUMBER_CONVERSION_FAILED",kn("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const r=An.Number(t,e);return r.success?xn(Math.trunc(r.value),"number"):r},Float:(t,e)=>{const r=An.Number(t,e);return r.success?xn(parseFloat(""+r.value),"number"):r},Date:(t,e)=>{try{if(t instanceof Date)return xn(t,"object");if(null==t)return xn(new Date(""),"object");if(We(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,r,n]=t.split("-").map(Number);return xn(new Date(e,r-1,n),"object")}const e=new Date(t);return isNaN(e.getTime())?wn("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"):xn(e,"object")}catch(t){return wn("Date","DATE_CONVERSION_FAILED",kn("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{try{return xn(JSON.stringify(t),"string")}catch(t){return wn("JSON","JSON_STRINGIFY_FAILED",kn("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(Ze(t))return xn(t,"object");if(We(t))try{return xn(JSON.parse(t),"object")}catch(t){return wn("Object","JSON_PARSE_FAILED",kn("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return xn({},"object")}catch(t){return wn("Object","OBJECT_CONVERSION_FAILED",kn("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 xn(Tn(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=On(e);void 0!==t&&(r[e.name]=t)}}),xn(r,"object")}return xn({},"object")}catch(t){return wn("FormValues","FORM_VALUES_EXTRACTION_FAILED",kn("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}}},Sn=Nr({value:Lr(),type:Ar().min(1)}),Cn=Nr({value:Lr(),type:Ar().min(1)});new class extends Rr{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=Sn,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=An.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=An[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=An[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 Rr{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=Cn,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=ze(s)&&!isNaN(s);break;case"boolean":a=Je(s);break;case"object":a=Ze(s);break;case"array":a=Array.isArray(s);break;case"function":a=Ge(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||Ze(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 Nn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":We(t)?t:Ze(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Je(t))return t;if(null==t)return!1;if(We(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return ze(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(ze(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(ze(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(!ze(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=Nn.Number(t);return Math.trunc(e)},Float:t=>{const e=Nn.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(Ze(t))return t;if(We(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{We(t)||(t=Nn.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:Nn.String(t)).join(""):t instanceof Element?t.outerHTML:Nn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return Tn(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),r={};return e.forEach(t=>{t.name&&(r[t.name]=On(t))}),r}return{}},"Values:Form":(t,e)=>{const r=Nn.Values(t,e);return""+new URLSearchParams(r)},"Values:JSON":(t,e)=>{const r=Nn.Values(t,e);return JSON.stringify(r)}};function Tn(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const r=t;if(r.name){const t=On(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 On(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 Ln={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 Nn.Number(r).toFixed(t||2)}let s=Nn[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=Nn[i],s)?s(r,t):(console.warn("Unknown conversion type: "+n),r)},validate:t=>fr(t,2,"as","value, type")??dr(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 ze(r)&&!isNaN(r);case"boolean":return Je(r);case"object":return Ze(r);case"array":return Array.isArray(r);case"function":return Ge(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||Ze(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:t=>fr(t,2,"is","value, type")??dr(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>fr(t,1,"async","expression")}},$n={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"},Rn=Nr({collection:Or().describe("Collection to operate on (array, NodeList, or string)")}).strict(),In=Nr({collection:Or().describe("Collection to access"),index:Sr().describe("Index position to access")}).strict(),jn=Nr({collection:Or().describe("Collection to select random item from")}).strict();function Mn(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?Mn(n,e):null}function Dn(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?Dn(n,e):null}function Pn(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 Rr{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=Rn,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:$n[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 Rr{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=Rn,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:$n[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 Rr{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=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=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:!0,value:o,type:$n[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 Rr{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=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);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:$n[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 Vn={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:Ze(r)&&"length"in r&&ze(r.length)&&r.length>0?r[0]:null},validate:t=>vr(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:Ze(r)&&"length"in r&&ze(r.length)&&r.length>0?r[r.length-1]:null},validate:t=>vr(t,1,"last","collection")},at:{name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[r,n]=e;if(!ze(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(Ze(i)&&"length"in i&&ze(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>gr(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?Mn(s,r):s.nextElementSibling:null},validate:t=>vr(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?Dn(s,r):s.previousElementSibling:null},validate:t=>vr(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=Pn(t);for(const t of n)if(Pn(t)>s)return t;return null}(i,r,o):null},validate:t=>gr(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=Pn(t);for(let t=n.length-1;t>=0;t--){const e=n[t];if(s>Pn(e))return e}return null}(i,r,o):null},validate:t=>gr(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")}},Bn=new Set(["__proto__","constructor","prototype"]),Fn={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 er(r,n);if(Ze(r)){if(Bn.has(n))return;return r[n]}return r[n]}},validate:t=>fr(t,2,"possessive","element, property")??dr(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 er(t.me,r);if(Ze(t.me)){if(Bn.has(r))return;return t.me[r]}return t.me[r]}},validate:t=>pr(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 er(n,r);if(Ze(n)){if(Bn.has(r))return;return n[r]}return n[r]},validate:t=>pr(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 er(t.you,r);if(Ze(t.you)){if(Bn.has(r))return;return t.you[r]}return t.you[r]}},validate:t=>pr(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 er(n,r);if(Ze(n)){if(Bn.has(r))return;return n[r]}return n[r]}},validate:t=>fr(t,2,"of","property, object")??dr(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=>gr(t,1,2,"attribute","attributeName, optional element")??dr(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=>gr(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??dr(t,0,"attributeWithValue","attribute name")??dr(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=>pr(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=>pr(t,"idReference","idValue")}},_n=Nr({value:Ar().describe("String literal value")}).strict(),qn=Nr({value:Sr().describe("Number literal value")}).strict(),Hn=Nr({value:Cr().describe("Boolean literal value")}).strict(),Un=Nr({left:Or().describe("Left operand"),right:Or().describe("Right operand")}).strict();const Wn={stringLiteral:new class extends Rr{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=_n,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 Rr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=qn,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 Rr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Hn,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 Rr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Un,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=Fr(e.left,"left operand")+Fr(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 Rr{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=Un,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=Un.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(ze(t))return""+t;if(Je(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Rr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Un,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=Fr(e.left,"left operand")*Fr(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 zn extends ur{constructor(){super(),this.registerExpressions()}registerExpressions(){this.registerCategory(jr),this.registerCategory(En),this.registerCategory(Ln),this.registerCategory(Vn),this.registerCategory(Fn),this.registerCategory(Wn)}}class Jn{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 Zn{constructor(t,e,r){this.impl=t,this.expressionEvaluator=e??new zn,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=Jn.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,Jn.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,o),o}catch(t){if(ts(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 Gn{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 Zn(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 Xn=null;function Yn(){return Xn||(Xn=function(t){const e=t?.commands??new Gn,r=t?.eventSources??new qe,n=t?.context??new He,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}()),Xn}class Kn{constructor(t={}){this.contextCache=new WeakMap;const e=Yn();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 Qn(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 ts(t){return t instanceof Error&&(null!==Me(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function es(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 rs(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const ns=new WeakMap;class ss{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=Fe,this.hookRegistry=new je,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Be,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Kn("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),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(!Ve(r))throw Qn(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(!Ve(n))throw Qn(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(!Ve(r))throw Qn(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 ts(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=Me(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 De(await o.execute(e,{args:n||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Pe(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(!Ve(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}),De(r.returnValue)}}r=t.value}else{const t=await this.evaluateExpressionWithResult(n,e);if(!Ve(t))return t;r=t.value}}return De(r)}async evaluateExpression(t,e){const r=await this.expressionEvaluator.evaluate(t,e);return rs(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const r=await this.expressionEvaluator.evaluateWithResult(t,e);if(!Ve(r))return r;const n=r.value;if(rs(n)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:n.command,args:[{type:"literal",value:n.selector}]},e);try{return De(await this.executeCommandFromPattern(n.command,n.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Pe(e);throw t}}return De(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(ts(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{r=await this.execute(t,e)}catch(t){if(ts(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{r=await this.execute(t,e)}catch(t){if(ts(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(ts(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(ts(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);const n=this.behaviorRegistry.get(t);if(!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&&ts(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=ss.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=ns.get(i)??0;if(o>=100)return;if(ns.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=es(await t.execute(r,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(t){if(ts(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(ts(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(ts(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 is{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=_e(t);this.runtime.execute(e,r).catch(r=>{console.error('[HyperFixi] Error executing _="" attribute:',r),console.error("Element:",t),console.error("Code:",e)})}}function os(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 as(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 cs(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 ls(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function us(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 hs(t,e){for(const r of t)e(r);return t}function fs(t,e,r){for(const n of t)for(const t of e)r(n,t);return t}function ds(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 ps(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&&ys(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&&ys(t));const e=(t+"").trim(),r=e.startsWith(".")?e.substring(1):e;return r.length>0&&ys(r)?[r]:[]}function ms(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function ys(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!ms(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function vs(t,e){return t.map(t=>{if(ms(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 gs=Symbol("command:name"),bs=Symbol("command:category"),Es=Symbol("command:metadata");function ws(t){return function(e,r){const n=e;n[gs]=t.name,n[bs]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function xs(t){return function(e,r){const n=e,s=n[bs];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[Es]=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 ks(t){return()=>new t}function As(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function Ss(t,e){if(As(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 Ns(t)}if("string"==typeof t){const r=t.trim();if("me"===r){if(!e.me)throw Error('Context reference "me" is not available');return Ns(e.me)}if("it"===r){if(!As(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 Ns(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(!As(s))throw Error("Element found but is not an HTMLElement: "+r);return s}throw Error("Invalid target type: "+typeof t)}function Cs(t,e){if(Array.isArray(t))return t.filter(As);if(t instanceof NodeList)return Array.from(t).filter(As);if(As(t))return[t];if(!t){const t=e.me;return t&&As(t)?[t]:[]}if("string"==typeof t){const r=t.trim();if("me"===r)return e.me&&As(e.me)?[e.me]:[];if("it"===r)return As(e.it)?[e.it]:[];if("you"===r)return e.you&&As(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(As)}}return[]}function Ns(t){if(As(t))return t;throw Error("Value is not an HTMLElement")}function Ts(t,e){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error('No "me" element in context');if(!As(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(!As(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(!As(e.you))throw Error("context.you is not an HTMLElement");return e.you;default:throw Error("Unknown possessive: "+t)}}const Os=["on","from","to","in","with","at"];async function Ls(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||!Os.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(!As(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(As(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(As);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(As);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(As);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(!As(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return a}function $s(t){return"string"==typeof t&&t.trim().startsWith("*")}function Rs(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 Is(t,e,r){t.style.setProperty(e,r)}const js=["dialog","details","summary","select"];function Ms(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 Ds(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=Ms(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=Ms(t);return"string"==typeof r&&r.startsWith("*")}(t)?{value:Ms(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=Ms(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(n=t,"attributeAccess"===n.type?"@"+n.attributeName:Ms(n)),extractedFromNode:!0}:{value:await e.evaluate(t,r),extractedFromNode:!1};var n}class Ps{async resolveTargets(t,e,r,n){return Ls(t,e,r,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},n)}async evaluateFirst(t,e,r){return Ds(t,e,r)}parseClassNames(t){return ps(t)}isAttribute(t){return ls(t.trim())}isCSSProperty(t){return $s(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>As(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 Vs=(()=>{let t,e,r=[xs({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"]}),ws({name:"add",category:"dom"})],n=[],s=Ps;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=us(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=vs(t.classes,e);r.length>0&&fs(t.targets,r,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":r=t.name,n=t.value,hs(t.targets,t=>{t.setAttribute(r,n)});break;case"styles":!function(t,e){fs(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}},cs(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;os(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}),as(e,n)})(),e})();const Bs=ks(Vs);function Fs(t){return!!t.parentNode&&(t.remove(),!0)}let _s=(()=>{let t,e,r=[xs({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"]}),ws({name:"remove",category:"dom"})],n=[],s=Ps;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(As(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&As(n[0]))return{type:"element",targets:n.filter(t=>As(t))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s))return{type:"attribute",name:us(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=vs(t.classes,e);r.length>0&&fs(t.targets,r,(t,e)=>{t.classList.remove(e)});break}case"attribute":r=t.name,hs(t.targets,t=>{t.removeAttribute(r)});break;case"styles":!function(t,e){fs(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Fs(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}},cs(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;os(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}),as(e,n)})(),e})();const qs=ks(_s);function Hs(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 Us(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Hs(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 zs(t,e,r){return()=>{"class"===e?t.classList.toggle(r):"attribute"===e&&ds(t,r)}}function Js(t,e,r,n){const s=zs(t,e,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Zs(t,e,r,n){const s=zs(t,e,r),i=()=>{s(),t.removeEventListener(n,i)};return t.addEventListener(n,i,{once:!0}),()=>{t.removeEventListener(n,i)}}function Gs(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 Xs=/^the\s+(.+?)\s+of\s+(.+)$/i,Ys=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 Ks(t){return"string"==typeof t&&Xs.test(t)}function Qs(t,e){const r=t.match(Xs);if(!r)return null;try{return{element:Ss(r[2].trim(),e),property:r[1].trim()}}catch{return null}}async function ti(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]),As(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]),As(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]),!As(i))return null;const o=s?.name||s?.value;return o&&(o.startsWith("@")||o.startsWith("*"))?{element:i,property:o}:null}return null}function ei(t,e){const{element:r,property:n}=t;n.startsWith("*")?Is(r,n.substring(1),e+""):Gs(r,n,e)}async function ri(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=Hs(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 ni(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 js.includes(e)}(e)}(e);if(As(t)||Array.isArray(t)&&t.every(t=>As(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 js.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const si=ks((()=>{let t,e,r=[xs({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"]}),ws({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 ri(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 Ls(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 ti(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 ri(t.modifiers,e,r),a=Rs(s);if(a){const t=r.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Rs(s);if(o){const{duration:n,untilEvent:s}=await ri(t.modifiers,e,r),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Ls(t.args.slice(i),e,r,"toggle",a,t.modifiers),duration:n,untilEvent:s}}}const{duration:o,untilEvent:a}=await ri(t.modifiers,e,r),{value:c}=await Ds(n,e,r);if(Ks(c)){const t=Qs(c,r);if(t)return{type:"property",target:t}}const{type:l,expression:u}=ni(c,n),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=us(u);return{type:"attribute",name:n,value:s,targets:await Ls(t.args.slice(1),e,r,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const n=Rs(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await Ls(t.args.slice(1),e,r,"toggle",h,t.modifiers)}}case"element":{let s;if(As(c))s=[c];else if(Array.isArray(c)&&c.every(t=>As(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>As(t))}else s=await Ls([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:ps(u),targets:s,duration:o,untilEvent:a}}default:{const n=ps(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await Ls(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=vs(t.classes,e);if(0===r.length)return[...t.targets];if(fs(t.targets,r,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&r.length)for(const e of t.targets)t.duration&&Js(e,"class",r[0],t.duration),t.untilEvent&&Zs(e,"class",r[0],t.untilEvent);return[...t.targets]}case"attribute":if(r=t.name,n=t.value,hs(t.targets,t=>{ds(t,r,n)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Js(e,"attribute",t.name,t.duration),t.untilEvent&&Zs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return hs(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)):er(e,r)}(t),r=t.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof e||Ys.has(n)||Ys.has(n.toLowerCase())){const r=!e;return ei(t,r),r}if("number"==typeof e){const r=0===e?1:0;return ei(t,r),r}if("string"==typeof e){const n="__ht_"+r,s=t.element[n];return""===e&&void 0!==s?(ei(t,s),s):(t.element[n]=e,ei(t,""),"")}ei(t,!e)}(t.target),[t.target.element];case"dialog":return hs(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 hs(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return hs(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&&Js(e,"class",t.classA,t.duration),t.untilEvent&&Zs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var r,n}},cs(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})());class ii{async parseInput(t,e,r){const{targets:n}=await async function(t,e,r,n){return{targets:await Ls(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=>As(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 oi=(()=>{let t,e,r=[xs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),ws({name:"show",category:"dom"})],n=[],s=ii;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=>As(t))&&"string"==typeof e.defaultDisplay}},cs(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;os(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}),as(e,n)})(),e})();const ai=ks(oi);let ci=(()=>{let t,e,r=[xs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),ws({name:"hide",category:"dom"})],n=[],s=ii;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=>As(t))}},cs(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;os(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}),as(e,n)})(),e})();const li=ks(ci);const ui=ks((()=>{let t,e,r=[xs({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"]}),ws({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 ti(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&&Ks(t)){const e=Qs(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||!As(e.me))throw Error("put: no target and context.me is null");return[e.me]}const r=Array.from(document.querySelectorAll(t)).filter(t=>As(t));if(!r.length)throw Error(`No elements: "${t}"`);return r}parseValue(t){return As(t)?t:null==t?"":t+""}insertContent(t,e,r){if("replace"!==r)if(As(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 As(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(As(t))return[t];if(Array.isArray(t)){const e=t.filter(As);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(As);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}},cs(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})());function hi(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 fi(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 di(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 pi(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:fi(t,e)}const mi=ks((()=>{let t,e,r=[xs({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"]}),ws({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(As(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&&di(s,i,e),i}},cs(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})()),yi=ks((()=>{let t,e,r=[xs({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"]}),ws({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 ti(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(As(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(Ks(o)){const n=Qs(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&&$s(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&&ls(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=Ts(n[1],r),i=await this.extractValue(t,e,r);return{type:"property",element:s,property:n[2],value:i}}}if(As(o))return{type:"property",element:o,property:"textContent",value:await this.extractValue(t,e,r)};if(Array.isArray(o)&&o.length>0&&As(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");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 Gs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Is(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))Gs(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=Ts(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 Ss(t?await e.evaluate(t,r):void 0,r)}async resolveTargets(t,e,r){return Cs(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=Ss(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&&As(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&As(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&As(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}}},cs(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})());let vi=(()=>{let t,e,r=[xs({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"]}),ws({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(As(t)){const r=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?hi(r.getAttribute(e)):hi(r[e]):hi(r.value||r.textContent)}return"string"==typeof t?"global"===r?hi(fi(t,n,"global")):t.includes(".")?function(t,e){const r=t.split("."),n=r[1],s=pi(r[0],e);return s?hi(s[n]):0}(t,n):hi("me"===t&&n.me?n.me.value||0:"it"===t?n.it||0:"you"===t&&n.you?n.you.value||0:fi(t,n)):hi(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(As(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 di(t,n,s,"global");if(t.includes("."))return void function(t,e,r){const n=t.split("."),s=n[1],i=pi(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);di(t,n,s)}}(r,n,s,c,e),Object.assign(e,{it:c}),c}},cs(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})();const gi=ks(vi),bi=ks(vi);function Ei(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 wi=(()=>{let t,e,r=[xs({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"]}),ws({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(As(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(As));else if(Array.isArray(t))s.push(...t.filter(As));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(As));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()]=Ei(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}},cs(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})();const xi=ks(wi),ki=ks(wi);function Ai(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 Si(t){return new Promise(e=>setTimeout(e,t))}const Ci=ks((()=>{let t,e,r=[xs({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"]}),ws({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 Si(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-r};if("event"===t.type){const n=t.target??e.me??document,s=(await Ai(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:Us(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:Us(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?Si(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Ai(t.target??e.me??document,t.eventName).then(e=>({result:e.event,winningCondition:t})));return Promise.race(r)}},cs(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})()),Ni=new Map;const Ti=ks((()=>{let t,e,r=[xs({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"]}),ws({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=Ni.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(Ni.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=Ni.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&&As(r.firstChild)?r.firstChild:r}dispatchEvent(t,e,r){t.dispatchEvent(new CustomEvent(e,{detail:r,bubbles:!0,cancelable:!0}))}},cs(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})()),Oi=ks((()=>{let t,e,r=[xs({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"]}),ws({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&&As(e.me))return e.me;if("it"===r&&As(e.it))return e.it;if("you"===r&&As(e.you))return e.you;const n=fi(r,e);if(As(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)}}},cs(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})()),Li=ks((()=>{let t,e,r=[xs({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"]}),ws({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)}},cs(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;os(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}),as(e,n)})(),e})()),$i=function(t,e){const r=new Gn(e.expressionEvaluator);for(const e of t)r.register(e);return new ss({registry:r,expressionEvaluator:e.expressionEvaluator,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Bs(),qs(),si(),ai(),li(),ui(),mi(),yi(),gi(),bi(),ki(),xi(),Ci(),Ti(),Oi(),Li()],{expressionEvaluator:new class extends ur{constructor(t){super();for(const e of t)this.registerCategory(e)}}([jr,En,Wn,Ln,Vn])}),Ri={parse:t=>Ie(t),execute:async(t,e)=>{const r=function(t){if(!t)return _e();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=_e(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=Ie(t);if(!n.success||!n.node)throw Error(n.error?.message||"Parse failed");return await $i.execute(n.node,r)}},Ii=function(t){return new is(t)}(Ri),ji={runtime:Ri,parse:t=>Ri.parse(t),execute:async(t,e)=>Ri.execute(t,e),createContext:_e,attributeProcessor:Ii,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)=>Ri.execute(t,e),init:()=>{Ii.init()}};return"undefined"!=typeof window&&(window.hyperfixi=ji,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{Ii.init()}):Ii.init()),ji}();
|
|
2
2
|
//# sourceMappingURL=hyperfixi-standard.js.map
|