@hyperfixi/core 2.10.0 → 2.11.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/ast-utils/index.js +109 -8
- package/dist/ast-utils/index.mjs +109 -8
- package/dist/behaviors/index.js +2 -1
- package/dist/behaviors/index.mjs +2 -1
- package/dist/chunks/{bridge-CPNAPYAo.js → bridge-De7lnU_9.js} +2 -2
- package/dist/chunks/browser-modular-DpHHlmJ0.js +2 -0
- package/dist/chunks/{index-BQkkNlzO.js → index-D6-8bcsy.js} +2 -2
- package/dist/commands/helpers/dom-mutation.d.ts +3 -2
- package/dist/commands/helpers/index.d.ts +1 -1
- package/dist/commands/index.js +74 -8
- package/dist/commands/index.mjs +74 -8
- package/dist/hyperfixi-browser-classic-i18n.js +1 -1
- package/dist/hyperfixi-browser-minimal.js +1 -1
- package/dist/hyperfixi-browser-standard.js +1 -1
- package/dist/hyperfixi-browser.js +1 -1
- package/dist/hyperfixi-classic-i18n.js +1 -1
- package/dist/hyperfixi-hx-v4.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/index.js +224 -33
- package/dist/index.min.js +1 -1
- package/dist/index.mjs +224 -33
- 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/lsp-metadata.js +2 -2
- package/dist/lsp-metadata.mjs +2 -2
- package/dist/metadata.d.ts +1 -1
- package/dist/metadata.js +13 -11
- package/dist/metadata.mjs +13 -11
- package/dist/reference/index.js +7 -2
- package/dist/reference/index.mjs +7 -2
- package/dist/registry/index.js +6 -4
- package/dist/registry/index.mjs +6 -4
- package/dist/utils/element-check.d.ts +1 -0
- package/dist/version.d.ts +2 -0
- package/package.json +5 -5
- package/dist/chunks/browser-modular-B0lGdcoP.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var hyperfixi=function(){"use strict";const t="then",e="else",n="end",r="and",i="for",s="while",o="until",a="forever",c="times",l="index",u="in",f="to",h="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","prepend","process","pseudo-command","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait","for"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],T=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"]),C=t=>E.has(t.toLowerCase()),$=t=>x.has(t.toLowerCase()),N=t=>T.has(t.toLowerCase()),O=t=>R.has(t.toLowerCase()),R=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"]),j=new Set(["me","it","you","result","my","its","your"]),L=new Set(["and","or","not","no"]),M=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","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","is between","is not between","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","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),I=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"]),P=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 q;!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"}(q||(q={}));const H=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function D(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function F(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 U(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;F(t)}}function V(t,e,n,r,i){const s=r??t.position-n.length,o=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:s,end:o,line:_(t,s),column:a};t.tokens.push(c)}function _(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function z(t){const e=t.position;let n="";for(F(t),F(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=F(t);V(t,q.COMMENT,"--"+n,e)}function W(t){const e=t.position,n=F(t);let r=n;for(;t.input.length>t.position;){const e=F(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=F(t))}V(t,q.STRING,r,e)}function Z(t){const e=t.position;F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){F(t);break}if("\\"===e){if(F(t),t.input.length>t.position){const e=F(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=F(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);V(t,q.TEMPLATE,n,e)}function J(t){const e=t.position;let n=F(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=F(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=F(t),"}"===e)break}V(t,q.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)F(t),t.input.length>t.position&&(n+=F(t));else{if(!nt(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=F(t)}}V(t,q.SELECTOR,n,e)}}function K(t){const e=t.position;if(rt(t))return void function(t,e){const n=t.input;let r="",i=0,s="";for(;n.length>t.position;){const e=n[t.position];if(s)r+=F(t),e===s&&(s="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=F(t);if(n.length>t.position&&(r+=F(t)),i--,0>=i)break;continue}let e=!1,s="";for(;n.length>t.position;){const i=n[t.position];if(s)r+=F(t),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=F(t);break}r+=F(t)}else s=i,r+=F(t)}if(e||i++,0>=i)break;continue}r+=F(t)}else s=e,r+=F(t)}V(t,q.SELECTOR,r,e)}(t,e);let n="";for(n+=F(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=F(t),"/"===e&&">"===r){n+=F(t);break}}V(t,q.SELECTOR,n,e)}function X(t){const e=t.position;let n=F(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!nt(e)&&"_"!==e&&"-"!==e)break;n+=F(t)}V(t,q.SYMBOL,n,e)}function G(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===D(t,1))return n="'s",F(t),F(t),void V(t,q.OPERATOR,n,e);const i=t.input.substring(t.position,t.position+2),s=t.input.substring(t.position,t.position+3);["===","!=="].includes(s)?(n=s,F(t),F(t),F(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,F(t),F(t)):n=F(t),V(t,q.OPERATOR,n,e)}function Y(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=F(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",s=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">s||s>"9"))for(i+=F(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=F(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}}}const s=t.position;let o="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=F(t)}B.has(o)?V(t,q.TIME,i+o,e):(t.position=s,V(t,q.NUMBER,i,e))}function Q(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;i+=F(t)}const s=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return!1;const s=t.tokens[t.tokens.length-1];if(s&&(s.kind===q.IDENTIFIER||s.kind===q.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}U(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+=F(t)}if(o){const e=o.toLowerCase(),i=`${r} ${e}`,s=function(t,e,n,r){const i=e.toLowerCase(),s=n.toLowerCase();if("at"===i){const e=t.position;if("the"===s){U(t);let n="";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;n+=F(t)}const i=n.toLowerCase();if("start"===i||"end"===i){U(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=F(t)}if("of"===e.toLowerCase())return V(t,q.IDENTIFIER,`at the ${i} of`,r),!0}return t.position=e,!1}if("start"===s||"end"===s){U(t);let n="";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;n+=F(t)}return"of"===n.toLowerCase()?(V(t,q.IDENTIFIER,`at ${s} of`,r),!0):(t.position=e,!1)}}return!1}(t,r,e,n);if(s)return!0;const a=function(t,e,n){const r=t.position;let i=`${e} ${n}`,s=t.position;const o=[e,n];for(;8>o.length&&(U(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=F(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");M.has(n)&&(i=n,s=t.position)}return M.has(i)&&i!==`${e} ${n}`?(t.position=s,i):(t.position=r,null)}(t,r,e);if(a)return V(t,q.OPERATOR,a,n),!0;if(M.has(i))return V(t,q.OPERATOR,i,n),!0}return M.has(r)?(t.position=i,V(t,q.OPERATOR,e,n),!0):(t.position=i,!1)}(t,i,e);if(s)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||L.has(e)||H.has(t)||H.has(e)||M.has(e)?q.OPERATOR:q.IDENTIFIER}(i);V(t,o,i,e)}function tt(t){const e=t.position,n=t.input,r=n.length;F(t);let i="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;i+=F(t)}V(t,q.IDENTIFIER,i,e)}function et(t){return/[a-zA-Z]/.test(t)}function nt(t){return/[a-zA-Z0-9]/.test(t)}function rt(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=t.position+1,i="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)i+=e[r],r++;return i.length>0&&-1!==e.indexOf("</"+i+">",r)}function it(t){if(rt(t))return!0;let e=t.position+1,n=!1;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(nt(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,e++;else{if(" "!==r&&"\t"!==r)return!1;e++}if(e-t.position>50)return!1}return!1}function st(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const ot=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}(),at=ot,ct=ot,lt=ot,ut=ot,ft=(...t)=>{at&&console.log("\ud83d\udd27",...t)},ht=(...t)=>{ct&&console.log("\ud83c\udfaf",...t)},dt=(...t)=>{lt&&console.log("\ud83d\udcdd",...t)},pt=(...t)=>{ut&&console.log("\ud83d\ude80",...t)};let mt=!1,yt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(mt=!0,yt=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 vt{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(vt.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const n=t.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[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 r=this.analyzer.analyze(t,this.language),i=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const s=r.confidence>=this.confidenceThreshold&&!!r.command,o=!s&&r.confidence>0;if(mt){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:s,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(t){if(!mt)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),i=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?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),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(),yt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});yt.dispatchEvent(e)}}(a),n=a,gt.totalParses++,n.semanticSuccess?gt.semanticSuccesses++:n.fallbackTriggered?gt.semanticFallbacks++:gt.traditionalParses++,gt.confidenceHistory.push(n.confidence),gt.confidenceHistory.length>100&>.confidenceHistory.shift(),gt.averageConfidence=gt.confidenceHistory.reduce((t,e)=>t+e,0)/gt.confidenceHistory.length}return s?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}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 n=this.analyzer.buildCommandNode?.(e);if(!n)throw Error(`Semantic analyzer cannot build an AST node for '${e.name}' (no buildCommandNode wired \u2014 see createSemanticAdapter's buildAST dep)`);return n}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("patient");"for"==(r?r.value+"":"")&&i&&e.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("event");s&&e.push({type:"string",value:s.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&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;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(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{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=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{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 n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},i=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(s()),n();","===t[e];)e++,n(),r.push(s()),n();return")"===t[e]&&e++,r},s=()=>{n();const s=r();if(!s)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:s,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const s=t[e];if("."===s){e++;const t=r();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("("!==s)break;o={type:"callExpression",callee:o,arguments:i(),start:0,end:0,line:1,column:0}}}return o};return s()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}vt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const bt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),wt=new Set([")","]","}",","]);function Et(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const i=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function xt(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const i=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function kt(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:!0,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function St(t){return(e,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let s=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=!1),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:s,negated:t,start:e.start,end:i.end}}}const At=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",Et(10)],["||",Et(10)],["and",Et(20)],["&&",Et(20)],["==",Et(30)],["!=",Et(30)],["<",Et(30)],[">",Et(30)],["<=",Et(30)],[">=",Et(30)],["is",Et(30)],["matches",Et(30)],["contains",Et(30)],["starts with",Et(30)],["ends with",Et(30)],["does not start with",Et(30)],["does not end with",Et(30)],["is between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!1,start:t.start,end:s.end}})],["is not between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!0,start:t.start,end:s.end}})],["am between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!1,start:t.start,end:s.end}})],["am not between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!0,start:t.start,end:s.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=!0,t)}}],["where",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);let i="asc";const s=n.peek();if(s&&"string"==typeof s.value){const t=s.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),i="asc"):"desc"!==t&&"descending"!==t||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:i,start:t.start,end:r.end}})],["mapped to",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...Et(40),...kt(80)}],["-",{...Et(40),...kt(80)}],["*",Et(50)],["/",Et(50)],["%",Et(50)],["mod",Et(50)],["^",xt(60)],["**",xt(60)],["as",Et(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let i=r(),s={type:"asExpression",expression:t,targetType:i,start:t.start,end:i.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();s={type:"asExpression",expression:s,targetType:t,start:s.start,end:t.end??s.end,line:s.line,column:s.column}}return s})],["not",kt(80)],["!",kt(80)],["no",kt(27)]]),new Map([["===",Et(30)],["!==",Et(30)],["is not",Et(30)],["am",Et(30)],["is in",Et(30)],["is not in",Et(30)],["precedes",Et(30)],["does not precede",Et(30)],["follows",Et(30)],["does not follow",Et(30)],["is a",Et(30,St(!1))],["is an",Et(30,St(!1))],["is not a",Et(30,St(!0))],["is not an",Et(30,St(!0))],["has",Et(30)],["have",Et(30)],["match",Et(30)],["include",Et(30)],["includes",Et(30)],["equals",Et(30)],["does not contain",Et(30)],["does not include",Et(30)],["am in",Et(30)],["am not in",Et(30)],["is really",Et(30)],["is not really",Et(30)],["is equal",Et(30)],["is not equal",Et(30)],["contain",Et(30)],["do not contain",Et(30)],["does not contains",Et(30)],["do not match",Et(30)],["does not match",Et(30)],["is equal to",Et(30)],["is not equal to",Et(30)],["is really equal to",Et(30)],["is not really equal to",Et(30)],["really equals",Et(30)],["is greater than",Et(30)],["is less than",Et(30)],["is greater than or equal to",Et(30)],["is less than or equal to",Et(30)],["in",Et(30)],["of",xt(30)],["really",Et(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",kt(80)]]),new Map([["=",xt(5)]])),Tt=new Map,Ct=new Map,$t=new Map,Nt=new Set,Ot=new Set,Rt=new Set,jt=new Set;function Lt(t){return Tt.get(t.toLowerCase())}function Mt(t){return $t.get(t)}function It(t,e){if(0!==Ot.size)for(const n of Ot)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Pt(t,e,n){if(0!==Rt.size)for(const r of Rt)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function qt(t,e){if(0!==jt.size)for(const n of jt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function Ht(t,e,n){if(t.globals.set(e,n),0!==Nt.size)for(const r of Nt)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function Bt(t){return t.kind===q.IDENTIFIER&&E.has(t.value.toLowerCase())}function Dt(t){return t.kind===q.IDENTIFIER&&P.has(t.value.toLowerCase())}function Ft(t){return t.kind===q.IDENTIFIER&&I.has(t.value.toLowerCase())}function Ut(t){return t.kind===q.IDENTIFIER&&j.has(t.value.toLowerCase())}function Vt(t){return M.has(t.value.toLowerCase())}function _t(t){return t.kind===q.IDENTIFIER}function zt(t){return t.kind===q.SELECTOR}function Wt(t){return t.kind===q.SELECTOR&&!t.value.startsWith("<")}function Zt(t){return t.kind===q.STRING||t.kind===q.NUMBER||t.kind===q.TEMPLATE}function Jt(t){return t.kind===q.IDENTIFIER}function Kt(t){return t.kind===q.TIME}function Xt(t){return t.kind===q.SYMBOL}function Gt(t){return t.kind===q.COMMENT}function Yt(t){if(t.kind!==q.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(E.has(e)||P.has(e)||I.has(e)||j.has(e))}function Qt(t){return t.kind===q.STRING}function te(t){return t.kind===q.NUMBER}function ee(t){if(t.kind===q.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function ne(t){return t.kind===q.TEMPLATE}function re(t){return t.kind===q.SELECTOR&&t.value.startsWith("<")}function ie(t){return t.kind===q.SELECTOR&&t.value.startsWith("#")}function se(t){return t.kind===q.SELECTOR&&t.value.startsWith(".")}function oe(t){return t.kind===q.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function ae(t){if(t.kind!==q.OPERATOR)return!1;const e=t.value.toLowerCase();return!L.has(e)&&!M.has(e)}function ce(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function le(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ue(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function fe(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function he(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function de(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function pe(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function me(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ye(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ge(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}const ve=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"prepend",keywords:["to"],syntax:"prepend <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"throw",keywords:[],syntax:"throw <error>"}];function be(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const we=[t,r,e,n];function Ee(t,e=[]){if(t.isAtEnd())return!0;for(const e of we)if(t.check(e))return!0;for(const n of e)if(t.check(n))return!0;return!!t.checkIsCommand()}function xe(t,e=[]){if(!Ee(t,e))return t.parseExpression()}function ke(t,e,n){return!!t.check(e)&&(t.advance(),n.push(t.createIdentifier(e)),!0)}function Se(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function Ae(t,e){return!!t.check(e)&&(t.advance(),!0)}function Te(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}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 $e(t,e){const n=[];let r="";const i=t.peek().start||0,s=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=Te(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:i,end:t.getPosition().end,line:s,column:o})}else n.push({type:"string",value:r,start:i,end:t.getPosition().end,line:s,column:o})}const a=[...n];for(;!Ee(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}const e=t.savePosition(),n=t.parsePrimary();n&&a.push(n),t.savePosition()===e&&t.advance()}return Ce.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Ne(t,e){const n=[];if(t.check(b)){const e=t.advance();if(n.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();n.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Oe(i,s){const o=[],a=()=>i.check(n)||s&&i.check(e);for(;!i.isAtEnd()&&!a();){if(Gt(i.peek())){i.advance();continue}if(!i.checkIsCommand()&&!i.isCommand(i.peek().value))break;i.advance();const e=i.parseCommand();e&&o.push(e),(i.check(t)||i.check(r)||i.check(","))&&i.advance()}return o}const Re=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function je(t,e,n){return null!==e&&!Re.has(e.value?.toLowerCase?.()??"")&&(t.checkIsCommand()||t.isCommand(n.value?.toLowerCase()))}function Le(r,i){const s=[];let o=!1;const a=r.savePosition();let c=null;for(let e=0;500>e&&!r.isAtEnd();e++){const e=r.peek();if(e.value===t){o=!0;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;if(void 0!==e.line&&e.line!==i.line&&je(r,c,e))break;Gt(e)||(c=e),r.advance()}r.restorePosition(a);let l=!1;if(!o){const t=r.savePosition(),s=i.line,o=100;let a=!1,c=null;for(;!r.isAtEnd()&&o>r.current-t;){const t=r.peek(),i=t.value?.toLowerCase();if(a&&void 0!==t.line&&t.line!==s)break;if(i===g||"def"===i||i===m)break;if(i===e||i===n){t.line===s&&(l=!0);break}if(je(r,c,t)){if(void 0!==t.line&&t.line!==s){l=!0;break}a=!0}Gt(t)||(c=t),r.advance()}r.restorePosition(t)}const u=o||l;let f;if(u)f=r.parseExpression();else{const e=[],n=20;let s=0,o=!0;for(;!r.isAtEnd()&&!r.check(t)&&(o||!r.checkIsCommand()&&!r.isCommand(r.peek().value))&&n>s;){o=!1;const t=r.savePosition();e.push(r.parseLogicalAnd()),r.savePosition()===t&&r.advance(),s++}if(0===e.length)throw Error("Expected condition after if/unless");f=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:i.line,column:i.column}}if(s.push(f),u){Ae(r,t);const o=Oe(r,!0);if(0===o.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");s.push(he(o,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}));let a=!1;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Le(r,t);s.push(he([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=!0}else{const t=Oe(r,!1);s.push(he(t,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const t=r.parseCommand();s.push(he([t],{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}}return Ce.from(i).withArgs(...s).endingAt(r.getPosition()).build()}function Me(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.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();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const i=Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Ie=new Set(["my","its","your"]);function Pe(t){const e={};if(Ae(t,i)){const n=t.parseExpression();return n&&(e.for=n),e}if(!t.check(o))return e;t.advance();const n=t.peek();if(!n||!_t(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&_t(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},Ae(t,h)){const n=xe(t);n&&(e.from=n)}return e}function qe(t,e){const n=[],r=xe(t,[h]);r&&n.push(r),ke(t,h,n);const i=xe(t);return i&&n.push(i),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function He(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const s=xe(t,[r]);if(s&&"binaryExpression"===s.type&&"and"===s.operator)s.left&&n.push(s.left),n.push(t.createIdentifier("and")),s.right&&n.push(s.right);else{s&&n.push(s),ke(t,r,n);const e=xe(t,[h,m,i]);e&&n.push(e)}if(Se(t,[h,m],n)){const e=xe(t);e&&n.push(e)}return Ce.fromIdentifier(e).withArgs(...n).withModifiers(Pe(t)).endingAt(t.getPosition()).build()}const s=xe(t,[h,m]);if(s&&n.push(s),Se(t,[h,m],n)){const e=xe(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Ce.fromIdentifier(e).withArgs(...n).withModifiers(Pe(t)).endingAt(t.getPosition()).build()}function Be(t,e){if(!t.check("using"))return!1;if(t.advance(),!t.match("view"))throw Error("expected 'view transition' after 'using'");if(!t.match("transition"))throw Error("expected 'transition' after 'using view'");return e.push(t.createIdentifier("using")),e.push(t.createIdentifier("view")),e.push(t.createIdentifier("transition")),!0}function De(t,e){const r=t.parseExpression();if(!r)return t.addError("Put command requires content expression"),null;const i=t.peek();if(!i||!A.includes(i.value))return t.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${i?.value}`),null;let s=t.advance().value;const o=s.toLowerCase();"at start of"===o||"at the start of"===o?s=k:"at end of"===o||"at the end of"===o?s=S:"at"===s&&(t.check(w)||t.check(b)?(Ae(t,b),t.check(w)&&(t.advance(),t.check(p)&&(t.advance(),s=k))):t.check(n)&&(t.advance(),t.check(p)&&(t.advance(),s=S)));const a=t.parseExpression();return a?Ce.fromIdentifier(e).withArgs(r,t.createIdentifier(s),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Fe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Ue(i,s){const o=i.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:"element",start:e.start-1,end:e.end}}(i)??function(t){if(!t.check(v)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(i)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===p){const t=n.left,e=n.right;return ye(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(f)?n:(t.restorePosition(e),null)}(i),a||(a=i.parseExpression())}catch{i.restorePosition(o),a=null}if(!a){const s=function(i){if(i.match(":")){const t=i.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const s=[];for(;!(i.isAtEnd()||i.check(f)||i.check(t)||i.check(r)||i.check(e)||i.check(n));)s.push(i.parsePrimary());if(0===s.length)return{expression:null,tokens:[]};if(s.length>=4){const t=(t,e)=>t[e];if(t(s[0],"value")===b&&t(s[2],"value")===p){const e=s[1],n=s[3];return{expression:ye(ue(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:t(n,"value")||t(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:s[0].start??0,end:n.end??0,line:s[0].line??1,column:s[0].column??1}),tokens:[]}}}return 1===s.length?{expression:s[0],tokens:[]}:{expression:null,tokens:s}}(i);a=s.expression,c=s.tokens}if(!i.check(f)){const t=i.isAtEnd()?"end of input":i.peek().value;throw Error("Expected 'to' in set command, found: "+t)}i.advance();const l=i.parseExpression()??i.parsePrimary();let u;var h;i.check(m)&&(h=i.peekAt(1))&&("selector"===h.kind||h.value.startsWith("<")||Ve.has(h.value))&&(i.advance(),u=xe(i));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(i.createIdentifier(f)),l&&d.push(l);const y=Ce.fromIdentifier(s).withArgs(...d);return u&&y.withModifier("on",u),y.endingAt(i.getPosition()).build()}const Ve=new Set(["me","my","it","its","you","your","yourself"]),_e=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function ze(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function We(t,e){const n=[];for(;!Ee(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ze(t){const e=t.peek();if("/"===e.value)return!0;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return!1}const Je=new Set(["{",")"]);function Ke(t){const e=t.savePosition(),n=t.peek();let r="",i=null;for(;!t.isAtEnd();){const e=t.peek();if(i&&e.start!==i.end)break;if("$"===e.value&&"{"===t.peekAt(1)?.value){t.advance();let n=t.advance(),s=1;for(;!t.isAtEnd()&&s>0;)n=t.advance(),"{"===n.value?s++:"}"===n.value&&s--;r+=t.getInputSlice(e.start,n.end),i=n;continue}if(Je.has(e.value))break;i=t.advance(),r+=i.value}if(!r||"/"===r)return t.restorePosition(e),null;const s={start:n.start,end:i?i.end:n.end,line:n.line,column:n.column};return r.includes("${")?{type:"templateLiteral",value:r,...s}:{type:"literal",value:r,raw:r,...s}}function Xe(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Ge(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const i=t.parsePrimary();i&&e.push({key:r,value:i})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const Ye=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Qe{constructor(t,e,n){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 vt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||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.recovered=!0),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}}const t=this.peek(),e=t&&Lt(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==Lt(t.value))){this.advance();continue}}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")){const e=this.peek(),n=e?Lt(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}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("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];dt(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){dt(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(dt("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,dt(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),dt(`\u2705 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("\u26a0\ufe0f 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("\u2705 PARSER: No more event handlers, at end of input");break}}return dt(`\u2705 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 n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,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}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=Qe.PRATT_TABLE.get(r.value);let s;if(i?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();s=i.prefix.handler(t,this.makePrattContext())}else s=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(s,e);if(t){s=t;continue}}const n=Qe.PRATT_TABLE.get(e.value);if(!n?.infix){if(bt.has(e.value)||wt.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)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(t){dt("arrow body discarded after error:",t instanceof Error?t.message:t+"")}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}`),s}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}`),s}const i=this.advance();if(this.isAtEnd()&&!Qe.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),s;s=n.infix.handler(s,i,this.makePrattContext())}return this.prattCache.set(e,{node:s,endPos:this.current}),s}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(Ye.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:i.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return!1;const e=t.value;return!bt.has(e)&&!wt.has(e)&&("number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(e))}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||bt.has(e.value)||wt.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):C(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):N(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))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)}parseCompoundCommand(s){return function(s,o){switch(o.name.toLowerCase()){case"put":return De(s,o);case"trigger":case"send":return $e(s,o);case"remove":return qe(s,o);case"take":return function(t,e){const n=[],r={},s=xe(t,[h,i]);if(s&&n.push(s),t.check(h)){ke(t,h,n);const e=xe(t,[i]);e&&n.push(e)}if(Ae(t,i)){const e=xe(t);e&&(r.for=e)}return Ce.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(s,o);case"toggle":return He(s,o);case"set":return Ue(s,o);case"halt":return Ne(s,o);case"measure":return Me(s,o);case"js":return function(t,e){const r=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&r.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const i=t.peek().start,s=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"\u2019"!==t&&"\u2018"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,i);for(;!t.isAtEnd()&&!t.check(n)&&t.peek().start<s;)t.advance();t.consume(n,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(i,s).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:r.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,o);case"go":return function(t,e){const n=[];for(;!Ee(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(_e.has(r)){t.advance(),n.push(ze(r,e));continue}if(Ze(t)){const r=Ke(t);if(r){n.push(r);continue}t.advance(),n.push(ze(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(ze(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(ze(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o);case"tell":return function(i,s){const o=i.parseExpression();if(!o)throw Error("tell command requires a target expression");i.check(f)&&i.advance();const a=[];for(;!i.isAtEnd();){if(i.checkIsCommand()){try{i.advance();const t=i.parseCommand();if(!t)break;a.push(t)}catch{break}if(i.match(r)||i.match(t))continue;if(i.check(e))break;if(i.check(n)){i.advance();break}if(i.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Ce.fromIdentifier(s).withArgs(o,...a).endingAt(i.getPosition()).build()}(s,o);case"pick":return function(t,e){const n=Ce.fromIdentifier(e);Ae(t,b);const r=t.peek().value,i=t=>({type:"literal",value:t,start:e.start,end:e.end}),s=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=s();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=s();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=s(),o=n.withArgs(r).withModifier("variant",i("random"));return e&&o.withModifier("count",e),o.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?i("start"):t.parsePrimary();let o=!1;(t.match("to")||t.match(".."))&&(t.match("end")?o=!0:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=s(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return o?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let o;t.matchOperator("|")&&(o=t.advance().value);const a=s(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",e);return o&&c.withModifier("flags",i(o)),c.endingAt(t.getPosition()).build()}return We(t,e)}(s,o);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd("start view transition");return Ce.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(s,o);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const i=e.value.toLowerCase();Fe.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),n.push(t.createIdentifier("of")));const i=t.parseExpression();if(i&&n.push(i),!t.isAtEnd()&&t.check(d)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return Be(t,n),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o);case"process":return function(t,e){if(!t.check("partials"))return null;const n=[];if(ke(t,"partials",n),ke(t,u,n)){const e=xe(t,["using"]);e&&n.push(e)}return Be(t,n),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o)??We(s,o);default:return We(s,o)}}(this.getContext(),s)}parsePutCommand(t){return De(this.getContext(),t)}parseSetCommand(t){return Ue(this.getContext(),t)}parseHaltCommand(t){return Ne(this.getContext(),t)}parseMeasureCommand(t){return Me(this.getContext(),t)}parseTriggerCommand(t){return $e(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(dt("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){dt("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){dt(r?"\u2705 Found COMMAND token:":"\u2705 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("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(dt("\u2705 Parsed command:",r.name),e.push(r),t=!0)}catch(t){dt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&dt("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){dt("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(dt("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)dt("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))dt("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){dt("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}dt("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),dt("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(dt('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw dt('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return dt('\u2705 Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",f=null,p=null,m=null,g=null,v=null,w=null;if(t.check(i)){t.advance(),r=i;const e=t.peek();_t(e)&&(v=e.value,t.advance()),t.check(u)&&(t.advance(),g=t.parseExpression())}else if(t.check(u))t.advance(),r=i,v="it",g=t.parseExpression();else if(t.check(s))t.advance(),r=s,m=t.parseExpression();else if(t.check(o))if(t.advance(),r=o,t.check(y)){t.advance(),r="until-event";const e=t.peek();if(dt("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!_t(e)&&!Ft(e))throw Error('Expected event name after "event"');if(f=e.value,t.advance(),dt("\u2705 Got event name:",f,"Next token:",t.peek().value),dt('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(h)){dt('\u2705 Found "from", advancing...'),t.advance(),dt('\ud83d\udccd After consuming "from", current token:',t.peek().value),Ae(t,b)&&dt('\u2705 Found "the", advancing...');const e=t.peek();dt("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),dt("\u2705 After parsePrimary, eventTarget:",p)}else dt('\u274c No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),r=a):(w=t.parseExpression(),t.check(c)&&(t.advance(),r=c));let E,x=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),x=l)}else if(t.check(l)){t.advance();const e=t.peek();_t(e)?(x=e.value,t.advance()):x=l}let k=null,S=!1;if(r===a){const e=t.parseRepeatBody();if(E=e.commands,"else"===e.terminator)t.advance(),k=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(S=!0,r=e.terminator,t.advance(),m=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();E=e.commands,e.hasElse&&(t.advance(),k=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const A={start:e.start,end:e.end,line:e.line,column:e.column};v&&n.push(de(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(de(f,A)),p&&n.push(p),x&&n.push(de(x,A)),n.push(he(E,{...A,end:A.end||0})),null!==k&&n.push(he(k,{...A,end:A.end||0}));const T=Ce.from(e).withArgs(...n);return S&&T.withModifier("bottomTested",{type:"literal",value:!0,...A}),T.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,i=null;t.check("each")&&t.advance();const s=t.peek();if(!_t(s))throw Error('Expected variable name after "for"');if(r=s.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),i=t.parseExpression(),!i)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();_t(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd("for");n.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 n.push(de(r,c)),n.push(i),o&&n.push(de(o,c)),n.push(he(a,{...c,end:c.end||0})),Ce.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!Ee(t)){const r=t.parseExpression();return n.push(r),Ce.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{if(t.checkTimeExpression()||t.checkLiteral()||t.check("(")){if(r.push({kind:"duration",expr:t.parseExpression()}),t.check("or")){t.advance();continue}break}const e=t.peek();if(!_t(e))throw Error('Expected event name or duration after "for"');const n=e.value;t.advance();const i=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!_t(e))break;i.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({kind:"event",name:n,params:i}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let i=null;t.check(h)&&(t.advance(),Ae(t,b),i=t.parsePrimary());const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(me(r.map(t=>pe("duration"===t.kind?[{key:ue("duration",s),value:t.expr}]:[{key:ue("name",s),value:le(t.name,`"${t.name}"`,s)},{key:ue("args",s),value:me(t.params.map(t=>le(t,`"${t}"`,s)),s)}],s)),s)),i&&n.push(i)}return Ce.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,i=t.previous();if(n.push(ue(r,{start:i.start,end:i.end,line:i.line,column:i.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push(Te(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(pe(r.map(t=>({key:t.name?ue(t.name,i):le("_positional","_positional",i),value:t.value})),i))}}return Ce.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let i=null,s=null;const o=t.peek();if(t.checkAnySelector()||t.checkContextVar()||t.check("<")||_t(o)&&Ie.has(o.value)){const e=t.parsePrimary();("possessiveExpression"===e.type||"memberExpression"===e.type&&!e.computed)&&e.object&&e.property?.name?(s=e.object,i={type:"string",value:e.property.name,start:o.start||0,end:t.getPosition().end,line:o.line,column:o.column}):(s=e,t.check("'s")&&t.advance())}const a=t.peek();if(!i&&(_t(a)||"*"===a.value)){let e="";t.check("*")&&(e="*",t.advance());const n=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);n&&(e+=n,i={type:"string",value:e,start:a.start||0,end:t.getPosition().end,line:a.line,column:a.column})}if(!i)throw Error("Transition command requires a CSS property");if(s&&n.push(s),n.push(i),!t.check(f))throw Error('Expected "to" keyword after property in transition command');t.advance();const c=t.parsePrimary();if(r.to=c,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();r.with=e}return Ce.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=xe(t,[f]);e&&n.push(e)}if(t.check(f)){t.advance();const e=xe(t);e&&n.push(e)}return Ce.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Le(this.getContext(),t)}parseRemoveCommand(t){return qe(this.getContext(),t)}parseToggleCommand(t){return He(this.getContext(),t)}parseRegularCommand(t){return We(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),!1);n.optional=!0,t=n}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):Xt(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("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()&&_t(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),n=this.processEscapeSequences(e);return this.createLiteral(n,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,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=!0,n.raw=t,n}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:"element",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(Yt)||this.matchPredicate(Dt)||this.matchPredicate(Ut)||this.matchPredicate(Bt)||this.matchPredicate(Ft))){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,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"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("\\"===this.peek().value)return this.parseBlockLiteral();if(Xt(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()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),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.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Yt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=!1;for(;this.check("-");)this.advance(),t+="-",n=!0;for(this.checkPredicate(Yt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=!0,this.checkPredicate(Yt)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!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 n;if(this.matchPredicate(Yt))n=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);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,s=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==s||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>o&&"number"==typeof t.start&&(o=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(i=!0),"{"===t.value&&s++,"}"===t.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:l}),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(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,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 n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:s,finallyHandler:o}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==s&&{errorHandler:s},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseErrorAndFinallyBlocks(){let t,e,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(t=this.advance().value),e=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==t&&{errorSymbol:t},...void 0!==e&&{errorHandler:e},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}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,n,r,i){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)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==i.start&&{start:i.start},...void 0!==i.end&&{end:i.end},...void 0!==i.line&&{line:i.line},...void 0!==i.column&&{column:i.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(Qe.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Yt(r)&&!this.isCommand(r.value)||Ut(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let i,s;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"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}}),Qe.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{s=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,t,i,s,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(dt("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return dt("\u26a0\ufe0f Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),s=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=s,dt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,dt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`);var r}parseEventHandler(){dt("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=!0,dt("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),dt("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),dt("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),dt("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(dt("\ud83d\udd27 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(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();i.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),dt("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=n,dt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,dt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else dt(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(s),e&&(s.once=!0),Object.keys(s).length>0&&dt("\ud83d\udd27 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(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(s)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,dt("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(dt("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),dt("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(dt(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(dt(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){dt("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())dt("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){dt("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){dt(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);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 n=this.parseCommand();u.push(n);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("\u2705 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("\u26a0\ufe0f 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 n={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(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let f,h,d;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:f,errorHandler:h,finallyHandler:d}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const p=this.getPosition(),m={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...void 0!==f&&{errorSymbol:f},...void 0!==h&&{errorHandler:h},...void 0!==d&&{finallyHandler:d},...i.length>0&&{args:i},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:p.start,end:p.end,line:p.line,column:p.column};return dt(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),m}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 n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Yt(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let s;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),s=e.value,this.advance())}}const{commands:o,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const f={type:"eventHandler",event:e,commands:o,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==s&&{target:s},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};i.push(f)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={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:n,eventHandlers:i,...void 0!==s?{initBlock:s}:{},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,n=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("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)dt("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){dt('\u2705 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(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const i=ge(n,r,e.value);if(t.push(i),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 ve.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return be(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!Ee(t,["catch","finally",...r.keywords])&&!be(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&be(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&be(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(s[e]=n),!be(t.peek(),r.keywords))break}const o=Ce.from(e).withArgs(...i).endingAt(t.getPosition());return Object.keys(s).length>0&&o.withModifiers(s),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();if(e.push(t),this.match("then","and",","))continue}}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(),n=e.value.toLowerCase();if(t.includes(n))break;if(Bt(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","prepend","toggle","take","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch","process"].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 n={};let r=null;if(!t.isAtEnd()&&Ze(t)&&(r=Ke(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),Ce.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:!0,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Xe(t)?Ge(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||Ae(t,"a")||Ae(t,"an"),n.as=t.parsePrimary();const i=Ce.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:!0,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const i=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let i=!1;t.check(v)&&(i=!0,t.advance());const s=t.parseExpression();if(!s)throw Error("Expected variable or expression after "+n);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);o=e}else o=le(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=s;i&&"identifier"===s.type&&(a={...s,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=fe(r,s,o,c);l.coerceNumeric=!0;const u=[a,ue(f,c),l];return Ce.from(e).withName("set").withArgs(...u).withOriginalCommand(n).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(i.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 n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const s=this.getPosition();return{type:"command",name:e,args:i,isBlocking:!1,start:s.start,end:s.end,line:s.line,column:s.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.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())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=!1,i=!1;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:t,within:e,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}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.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(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 n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Xt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifierLike(`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;O(e)&&dt(`\ud83d\udca1 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 le(t,e,this.getPosition())}createIdentifier(t){return ue(t,this.getPosition())}createBinaryExpression(t,e,n){return fe(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,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,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.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(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return dt("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return dt(`\u2705 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(`\u2705 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!(!ae(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(Wt)}matchSelector(){return this.matchPredicate(Wt)}checkAnySelector(){return this.checkPredicate(zt)}checkLiteral(){return this.checkPredicate(Zt)}checkIdentifierLike(){return this.checkPredicate(_t)}checkIsCommand(){return this.checkPredicate(Bt)}checkCommandTerminator(){return this.checkPredicate(ce)}checkReference(){return this.checkPredicate(Jt)}checkTimeExpression(){return this.checkPredicate(Kt)}checkEvent(){return this.checkPredicate(Ft)}checkContextVar(){return this.checkPredicate(Ut)}checkComment(){return this.checkPredicate(Gt)}checkIdentifier(){return this.checkPredicate(Yt)}checkKeyword(){return this.checkPredicate(Dt)}checkString(){return this.checkPredicate(Qt)}matchString(){return this.matchPredicate(Qt)}checkNumber(){return this.checkPredicate(te)}matchNumber(){return this.matchPredicate(te)}checkBoolean(){return this.checkPredicate(ee)}matchBoolean(){return this.matchPredicate(ee)}checkTemplateLiteral(){return this.checkPredicate(ne)}matchTemplateLiteral(){return this.matchPredicate(ne)}checkQueryReference(){return this.checkPredicate(re)}matchQueryReference(){return this.matchPredicate(re)}checkIdSelector(){return this.checkPredicate(ie)}checkClassSelector(){return this.checkPredicate(se)}checkCssSelector(){return this.checkPredicate(oe)}checkBasicOperator(){return this.checkPredicate(ae)}matchBasicOperator(){return this.matchPredicate(ae)}matchTimeExpression(){return this.matchPredicate(Kt)}matchIdentifierLike(){return this.matchPredicate(_t)}matchComparisonOperator(){return this.matchPredicate(Vt)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Yt,t)}consumeIdentifierLike(t){return this.consumePredicate(_t,t)}consumeEvent(t){return this.consumePredicate(Ft,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]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}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 n=e.start||0,r=e.line||1,i=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,i=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,i=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},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("\u26a0\ufe0f synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const s="["+i+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],s=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===s?.value||s&&r.has(s.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:t,end:this.previous().end,line:e,column:n}}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),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.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=>t.peekAt(e),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 tn(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(U(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==D(e,1))if('"'!==n){if("'"===n||"'"===n){const t=D(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==q.IDENTIFIER&&n.kind!==q.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)W(e);else{const t=e.position;F(e),F(e),V(e,q.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===D(e,1)){const t=e.position;F(e),F(e),V(e,q.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===q.IDENTIFIER&&E.has(t.value.toLowerCase()),i=t&&t.kind===q.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===q.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(et(D(e))||"{"===D(e)||"-"===D(e))){J(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===q.IDENTIFIER&&I.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==q.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(F(e),V(e,q.SYMBOL,"[")):(F(e),V(e,q.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=D(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){tt(e);continue}}st(n)?G(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(V(e,q.UNKNOWN,n),F(e)):Q(e):Y(e)}else F(e),V(e,q.OPERATOR,"]")}else F(e),V(e,q.OPERATOR,"}");else F(e),V(e,q.OPERATOR,"{");else X(e)}else J(e);else it(e)?K(e):G(e);else Z(e)}else W(e);else z(e)}return e.tokens}(t);return new Qe(n,e,t).parse()}Qe.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Qe.PRATT_TABLE=At,Qe.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class en{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 n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(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 nn(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function rn(t){return{ok:!0,value:t}}function sn(t){return{ok:!1,error:t}}function on(t){return!0===t.ok}const an=new Map,cn=new WeakMap;function ln(t){let e=cn.get(t);return e||(e=new Map,cn.set(t,e)),e}function un(t){return t.owner||(t.me instanceof Element?t.me:null)}function fn(t,e){const n=un(t);if(n)return qt(e,t),ln(n).get(e)}function hn(t,e,n){const r=un(t);r&&(ln(r).set(e,n),Pt(e,n,t))}function dn(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||an,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function pn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function mn(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function yn(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 gn(t,e,n){return"element"===n?fn(e,t):"global"===n&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==n&&e.locals&&e.locals.has(t)?(qt(t,e),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"===n&&e.locals&&e.locals.has(t)?(qt(t,e),e.locals.get(t)):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function vn(t,e,n,r){if("element"!==r){if("global"===r)return Ht(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void Ht(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Pt(t,e,n);if(n.globals&&n.globals.has(t))return Ht(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void Ht(n,t,e);n.locals.set(t,e),Pt(t,e,n)}}else hn(n,t,e)}function bn(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:gn(t,e)}function wn(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function En(t){if(pn(t))return[t];if(Array.isArray(t)){const e=t.filter(pn);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(pn);return e.length>0?e:null}return null}const xn=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,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(t),s=r.coerceFrom?.[i];if(s){const r=s(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return!1;if(n.isType(t))return!0;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.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 n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}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,n)=>{e[n+""]=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 kn(t){const e=xn.get("String");return e?e.isType(t):"string"==typeof t}function Sn(t){const e=xn.get("Number");return e?e.isType(t):"number"==typeof t}function An(t){const e=xn.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Tn(t){const e=xn.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function Cn(t){const e=xn.get("Function");return e?e.isType(t):"function"==typeof t}function $n(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function Nn(t){return t instanceof Element}function On(t){return t instanceof HTMLElement}const Rn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function jn(t,e){return Rn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Ln={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=>$n(t)?t.tabIndex:void 0,hidden:t=>$n(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,next:t=>t.nextElementSibling,previous: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 n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function Mn(t,e){if(e.startsWith("*"))return function(t,e){if(!On(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return On(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return jn(t,e.slice(1));const n=Ln[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return jn(t,e);const r=t[e];return Cn(r)?r.bind(t):r}const In={1:"one",2:"two",3:"three",4:"four",5:"five"};function Pn(t,e,n,r){if(t.length!==e){return`${n} requires exactly ${i=e,In[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`}var i;return null}function qn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Hn(t,e,n){return Pn(t,1,e,n)??qn(t,0,e,n)}function Bn(t,e){return Pn(t,2,e,"left, right")}function Dn(){return null}function Fn(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function Un(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const Vn={conversions:{dynamicResolvers:[]}},_n={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":kn(t)?t:Tn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(An(t))return t;if(null==t)return!1;if(kn(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return Sn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(Sn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(Sn(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(!Sn(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=_n.Number(t);return Math.trunc(e)},Float:t=>{const e=_n.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(kn(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!kn(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(Tn(t))return t;if(kn(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>kn(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:_n.String(t)).join(""):t instanceof Element?t.outerHTML:_n.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=zn(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=zn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?_n.Values(t,e):t;if(!Tn(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=_n.Values(t,e);return _n.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=_n.Values(t,e);return JSON.stringify(n)}};function zn(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 Wn={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",jsonstring:"JSONString",formencoded:"FormEncoded"};function Zn(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return _n.Number(t).toFixed(n??0)}if(null==t)return t;let r=_n[e];if(r)return r(t,n);const i=Wn[e.toLowerCase()];if(i&&(r=_n[i],r))return r(t,n);const s=Vn.conversions[e];if("function"==typeof s)return s(t,n);for(const n of Vn.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Jn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Zn(n,r,t)},validate:t=>Pn(t,2,"as","value, type")??qn(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[n,r]=e;if(!kn(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return kn(n);case"number":return Sn(n)&&!isNaN(n);case"boolean":return An(n);case"object":return Tn(n);case"array":return Array.isArray(n);case"function":return Cn(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||Tn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>Pn(t,2,"is","value, type")??qn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Pn(t,1,"async","expression")}},Kn=new Set(["__proto__","constructor","prototype"]);function Xn(t,e){if(t instanceof Element)return Mn(t,e);if(Tn(t)){if(Kn.has(e))return;return t[e]}return t[e]}function Gn(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return!1;e=Array.from(t)}return 0!==e.length&&e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const Yn={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return Gn(n)&&!(r in n)?Array.from(n,t=>Xn(t,r)):Xn(n,r)}},validate:t=>Pn(t,2,"possessive","element, property")??qn(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return Mn(t.me,n);if(Tn(t.me)){if(Kn.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Hn(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return Mn(r,n);if(Tn(r)){if(Kn.has(n))return;return r[n]}return r[n]},validate:t=>Hn(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return Mn(t.you,n);if(Tn(t.you)){if(Kn.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Hn(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return Mn(r,n);if(Tn(r)){if(Kn.has(n))return;return r[n]}return r[n]}},validate:t=>Pn(t,2,"of","property, object")??qn(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||t.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:t=>Un(t,1,2,"attribute","attributeName, optional element")??qn(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[n,r,i]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const s=i||t.me;return!!(s&&s instanceof Element)&&s.getAttribute(n)===r},validate:t=>Un(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??qn(t,0,"attributeWithValue","attribute name")??qn(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[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:t=>Hn(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>Hn(t,"idReference","idValue")}};function Qn(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}function tr(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function er(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function nr(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return lr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return lr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await nr(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?Ht(e,t.slice(1),n):"global"===i.scope?Ht(e,t,n):"element"===i.scope?hn(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await nr(t.left,e);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===i?.type&&"identifier"===i.callee?.type?i.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(i.arguments)){const r=i.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const i=await nr(t.right,e);if(i&&"function"==typeof i.querySelectorAll){const t=Array.from(i.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await nr(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(i.value))}}if("of"===n&&"selector"===i?.type&&"string"==typeof i.value&&/^\*[a-zA-Z][\w-]*$/.test(i.value)){const n=await nr(t.right,e);return tr(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=ur(t.left);if(n){const r=await nr(t.right,e);let i=r;for(const t of n){if(null==i)return;i=Nn(i)?Mn(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const s=await nr(t.left,e);if("and"===n){if(!s)return s;const n=await nr(t.right,e);return tr(e,"and").evaluate(e,s,n)}if("or"===n){if(s)return s;const n=await nr(t.right,e);return tr(e,"or").evaluate(e,s,n)}const o=await nr(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(s):s,l=t.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=yn(n)),"string"==typeof r&&(r=yn(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:er(await tr(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return er(await tr(e,"subtraction").evaluate(e,{left:s,right:o}));case"*":return er(await tr(e,"multiplication").evaluate(e,{left:s,right:o}));case"/":return er(await tr(e,"division").evaluate(e,{left:s,right:o}));case"%":case"mod":return er(await tr(e,"modulo").evaluate(e,{left:s,right:o}));case"^":case"**":return er(await tr(e,"power").evaluate(e,{left:s,right:o}));case">":case"is greater than":return tr(e,"greaterThan").evaluate(e,s,o);case"<":case"is less than":return tr(e,"lessThan").evaluate(e,s,o);case">=":case"is greater than or equal to":return tr(e,"greaterThanOrEqual").evaluate(e,s,o);case"<=":case"is less than or equal to":return tr(e,"lessThanOrEqual").evaluate(e,s,o);case"==":return tr(e,"equals").evaluate(e,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=dr(t,s,o);return void 0!==n?n:tr(e,"equals").evaluate(e,c,l)}case"!=":return tr(e,"notEquals").evaluate(e,c,l);case"is not":case"is not equal":case"is not equal to":{const n=dr(t,s,o);return void 0!==n?!n:tr(e,"notEquals").evaluate(e,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return tr(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really":case"is not really equal to":return tr(e,"strictNotEquals").evaluate(e,c,l);case"as":return tr(e,"as").evaluate(e,s,mr(o));case"contains":case"contain":case"includes":case"include":return tr(e,"contains").evaluate(e,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return tr(e,"doesNotContain").evaluate(e,c,l);case"starts with":return tr(e,"startsWith").evaluate(e,c,l);case"ends with":return tr(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await tr(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await tr(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return tr(e,"matches").evaluate(e,c,hr(t.right,l));case"does not match":case"do not match":return!await tr(e,"matches").evaluate(e,c,hr(t.right,l));case"in":case"is in":case"am in":return fr(s,o);case"is not in":case"am not in":return!fr(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return pr(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!pr(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return pr(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!pr(s,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await nr(t.expression,e),r=mr(t.targetType);return tr(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await nr(t.value,e),r=await nr(t.min,e),i=await nr(t.max,e),s=t=>"string"==typeof t?t.toLowerCase():t,[o,a,c]=t.ignoringCase?[s(n),s(r),s(i)]:[n,r,i],l=await tr(e,"between").evaluate(e,o,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return!0;if(Object.prototype.toString.call(t).slice(8,-1)===e)return!0;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await nr(t.value,e),t.typeName+"",!1!==t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await nr(t.collection,e);if(null==n)return n;const r=async(t,n)=>nr(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=Qn(t),i=[];for(const t of r)await n(e,t)&&i.push(t);return i}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const i=[...Qn(t)],s=await Promise.all(i.map(t=>r(e,t))),o=i.map((t,e)=>e);o.sort((t,e)=>{const n=s[t],r=s[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(t=>i[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=Qn(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return s=await nr(t.right,e),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return Qn(t).map(t=>null==t?"":t+"").join(n)}(n,await nr(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var i,s}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await nr(n,e);switch(t.operator){case"not":case"!":return tr(e,"not").evaluate(e,r);case"no":return tr(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return tr(e,"exists").evaluate(e,r);case"does not exist":return tr(e,"doesNotExist").evaluate(e,r);case"is empty":return tr(e,"isEmpty").evaluate(e,r);case"is not empty":return tr(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await nr(t.object,e);if(t.computed){const r=await nr(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return br(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await nr(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await br(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await nr(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>nr(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return wr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:nr(t,n))):Promise.all(t.map(t=>nr(t,n)))}(t.arguments,r,e);switch(r){case"closest":return tr(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?Er(await nr(n.from,e)):e.me,s=n.within?Er(await nr(n.within,e)):void 0,o=n.inElt?await nr(n.inElt,e):void 0;return tr(e,r).evaluate(e,i[0],t,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return tr(e,r).evaluate(e,...i)}case"first":return tr(e,"first").evaluate(e,...i);case"last":return tr(e,"last").evaluate(e,...i);default:if("function"==typeof n)return n(...i);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>nr(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await nr(t.callee.object,e);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return tr(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(t,e){const n=Tr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>or(t.expr,e)));return Cr(n,r)}(n,e),s=Sr(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await tr(e,"elementWithSelector").evaluate(e,s)}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return vr(t,/\{([^}]*)\}/g,async(t,n)=>(await or(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Sr(t,n):n;return wn(await tr(e,"elementWithSelector").evaluate(e,r),n,t.fromQuery)}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return tr(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return tr(e,"me").evaluate(e);case"your":case"yourself":return tr(e,"you").evaluate(e);case"its":return tr(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??tr(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return tr(e,"document").evaluate(e);case"window":return tr(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await nr(t.object,e),r=t.property.name;return tr(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await nr(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await nr(t.test,e)?nr(t.consequent,e):t.alternate?nr(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await nr(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await nr(t,e)+"",n[i]=await nr(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await nr(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return tr(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await vr(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=gr(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(gr(n,e)??"")+""}catch{return""}}),n=await vr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await or(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await nr(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return yr(n,e);default:{const n=Ct.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class rr extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function ir(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new rr("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new rr("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=Tr(t),r=n.filter(t=>"expr"in t).map(t=>sr(t.expr,e));return Cr(n,r)}(n,e),s=Sr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new rr("selector");i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(o.querySelectorAll(s))}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(sr(n.trim(),e)??"")+"")}(n,e):n,i=Sr(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new rr("selector");return wn(Array.from(s.querySelectorAll(i)),r,t.fromQuery)}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"result"===t?e.result??e.it:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?fn(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new rr("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>ir(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:ir(t,e)+"",n[i]=ir(r.value,e)}return n}(n,e);case"asExpression":return Zn(ir(n.expression,e),mr(n.targetType),e);case"stringPostfix":return`${ir(n.expression,e)}${n.unit}`;case"blockLiteral":return yr(n,e);case"memberExpression":{const t=ir(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new rr("memberExpression");const r=t[n.computed?ir(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new rr(n?.type??"unknown")}}function sr(t,e){const n=tn(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return ir(n.node,e)}async function or(t,e){const n=tn(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await cr()};return nr(n.node,r)}let ar=null;async function cr(){if(!ar){const t=await Promise.resolve().then(function(){return oa});ar=t.createFullExpressionRegistry()}return ar}async function lr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?tr(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?tr(e,"you").evaluate(e):"it"===n||"its"===n?tr(e,"it").evaluate(e):"result"===n?tr(e,"result").evaluate(e):"window"===n?tr(e,"window").evaluate(e):"document"===n?tr(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?(It(n,e),e.globals.get(n)):"element"===t.scope?fn(e,n):e.locals&&e.locals.has(n)?(qt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&It(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(It(n.slice(1),e),e.globals.get(n.slice(1))):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function ur(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=ur(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function fr(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function hr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function dr(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const i=e[r.name];return"boolean"==typeof i?!0===i:void 0}function pr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function mr(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 yr(t,e){const n=t.parameters??[];return(...r)=>{const i=new Map(e.locals??new Map);n.forEach((t,e)=>i.set(t,r[e]));const s={...e,locals:i};try{return ir(t.body,s)}catch(e){if(e instanceof rr)return nr(t.body,s);throw e}}}function gr(t,e){if(e.locals?.has(t))return qt(t,e),e.locals.get(t);if("me"===t&&e.me)return e.me;if("you"===t&&e.you)return e.you;if("it"===t){const t=e.it??e.result;if(t)return t}if("result"===t){const t=e.result??e.it;if(t)return t}return"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function vr(t,e,n){const r=[];let i;for(;null!==(i=e.exec(t));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let s=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:i}=r[t];s=s.substring(0,e)+i+s.substring(e+n)}return s}function br(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?Mn(t,e):Gn(t)&&!(e in t)?tr(n,"possessive").evaluate(n,t,e):t?.[e]}const wr=new Set(["closest","previous","next"]);function Er(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const xr=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),kr=/[:&()[\]/]/g;function Sr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(xr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(kr,"\\$&")}(e)}const Ar=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Tr(t){const e=[];let n,r=0;for(Ar.lastIndex=0;null!==(n=Ar.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function Cr(t,e){let n="";const r=[];let i=0;for(const s of t){if("lit"in s){n+=s.lit;continue}const t=e[i++];Nn(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class $r{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,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&pt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&pt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&pt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&pt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&pt("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&pt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&pt(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&pt(`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,n=0,r=0,i=0;for(const s of this.globalCleanups)switch(s.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Nr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&pt("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.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,n){const r=this.get(t);if(!r)return void pt("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const i=r.subscribe(e,n);return this.subscriptions.set(i.id,i),i}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,n]of this.sources.entries())if(n.supports?.(t)??n.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 Or{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.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,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const s=await r.provide(e);return r.cache&&n&&n.set(i,s),s}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const s=r.provide(e);if(s instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,s),s}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,i){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,i)},has:(t,n)=>!("string"!=typeof n||!e.has(n))||Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,s]of r)try{n[i]=await this.resolve(i,t,e)}catch(t){pt(`[ContextProviderRegistry] Failed to resolve '${i}':`,t),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const Rr={evaluate:(t,e)=>nr(t,e)};class jr{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},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||{},...void 0!==t.registry&&{registry:t.registry},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 Lr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof t?t:t?t.join(" | "):""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(ft(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void ft(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=jr.toTyped(t);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ft(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await nr(r,t))return void ft(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Rr,t)}else s=e;else ft(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=e;if(ft("CommandAdapterV2: Calling execute with parsed input:",s),2===this.impl.execute.length)o=await this.impl.execute(s,i);else{const t=Array.isArray(s)?s:[s];o=await this.impl.execute(i,...t)}return ft("CommandAdapterV2: Command result:",o),Object.assign(t,jr.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Br(t)||ft(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return{isValid:!this.impl.validate||this.impl.validate(t),errors:[],suggestions:[]}}}class Mr{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);pt(`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 n=e.toLowerCase();pt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Lr(t,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const i=t.metadata?.aliases;if(i&&Array.isArray(i))for(const e of i){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),E.add(n)}}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 n=this.getAdapter(t);return n?n.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 Ir=null;function Pr(){return Ir||(Ir=function(t){const e=t?.commands??new Mr,n=t?.eventSources??new Nr,r=t?.context??new Or,i=new Set,s={commands:e,eventSources:n,context:r,use(t){if(i.has(t.name))pt(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const n of t.commands)e.register(n);if(t.eventSources)for(const e of t.eventSources)n.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:n,options:i}of t.contextProviders)r.register(e,n,i);t.setup?.(s),i.add(t.name)}},reset(){i.clear()}};return s}()),Ir}class qr{constructor(t={}){this.contextCache=new WeakMap;const e=Pr();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,pt(`[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),pt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return pt("[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 pt(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return pt(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return pt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pt("[RegistryIntegration] Destroyed")}}function Hr(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 Br(t){return t instanceof Error&&(null!==nn(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function Dr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Fr=new WeakMap;function Ur(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)Ur(n,e);return e}const n=t;"identifier"===n.type&&"string"==typeof n.name&&e.add(n.name);for(const t of Object.keys(n))"start"!==t&&"end"!==t&&"line"!==t&&"column"!==t&&Ur(n[t],e);return e}class Vr{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.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=an,this.hookRegistry=new en,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new $r,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new qr("object"==typeof t.registryIntegration?t.registryIntegration:{}),pt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.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&&pt(`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)}trackListener(t,e,n,r,i){this.cleanupRegistry.registerListener(t,e,n,r,i)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){pt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return pt("\u26a0\ufe0f 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){const n=await this.processCommandWithResult(t,e);if(!on(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Hr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=nn(t);if(n?.isReturn){const t=n.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"def":return this.installFunction(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 n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!on(r))throw Hr(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!on(n))throw Hr(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:i}=t,s=n.toLowerCase();if(ft(`RUNTIME BASE: Processing command '${s}'`),this.registry.has(s)){const t=await this.registry.getAdapter(s);if(!t)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this})}catch(t){throw Br(t)||this.logError(`Error executing command '${s}':`,t),t}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(t){const e=nn(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:n,args:r,modifiers:i}=t,s=n.toLowerCase();if(ft(`RUNTIME BASE (Result): Processing command '${s}'`),!this.registry.has(s)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const o=await this.registry.getAdapter(s);if(!o)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return rn(await o.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return sn(e);throw this.logError(`Error executing command '${s}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const r of t){if(this.hasErrorDiagnostics(r)){const t=r.diagnostics?.[0];pt("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===r.type){const t=await this.processCommandWithResult(r,e);if(!on(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),rn(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!on(t))return t;n=t.value}}return rn(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await nr(t,n);return Dr(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await async function(t,e){try{return rn(await nr(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return sn({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return sn({type:"exit",returnValue:e.returnValue});if(e.isBreak)return sn({type:"break"});if(e.isContinue)return sn({type:"continue"});if(e.isReturn)return sn({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!on(r))return r;const i=r.value;if(Dr(i)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:i.command,args:[{type:"literal",value:i.selector}]},e);try{return rn(await this.executeCommandFromPattern(i.command,i.selector,e))}catch(t){const e=this.toSignal(t);if(e)return sn(e);throw t}}return rn(i)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}installFunction(t,e){const n=this,r=t.params??[],i=t.body??[],s=t.errorHandler,o=t.finallyHandler,a=t.errorSymbol;e.globals.set(t.name,async(...t)=>{const c={...e,locals:new Map(e.locals)};r.forEach((e,n)=>{e&&c.locals.set(e,t[n])});const l=async t=>{const e=await n.executeCommandSequenceWithResult(t,c);if(!on(e))throw nn(e.error);return e.value};if(!s&&!o)return await l(i);try{return await l(i)}catch(t){if(!s||Br(t))throw t;return a&&c.locals.set(a,t),await l(s)}finally{o&&await l(o)}})}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],i=[],s=[],o=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"def"===e.type?i.push(e):"initBlock"===e.type?s.push(e):o.push(e);for(const t of i)this.execute(t,e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Br(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Br(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Br(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Br(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Br(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 n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const i=await this.execute(r.value,e);n[t]=i}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:s}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),pt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),pt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){pt("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(pt(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),pt(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));pt("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:e,owner:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},s=this.enhanceContext(i);if(r.parameters)for(const t of r.parameters)s.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||s.locals.set(t,e);if(r.initBlock){pt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),pt("BEHAVIOR: Init block completed for "+t)}catch(e){if(pt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Br(e)))throw e}}if(pt(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}pt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:s,args:o,selector:a,condition:c,attributeName:l,watchTarget:u,modifiers:f,errorSymbol:h,errorHandler:d,finallyHandler:p}=t,m=r&&r.length>0?r:[n];pt(`BEHAVIOR: executeEventHandler: event='${n}', target='${s}'`);let y=[],g=null;if(s){const t="string"==typeof s?s.toLowerCase():"";if("window"===t||"the window"===t)g=window;else if("document"===t||"the document"===t||"body"===t)g=document;else if("me"===t||"myself"===t)y=e.me?[e.me]:[];else if("string"==typeof s&&e.locals.has(s)){const t=e.locals.get(s);pt(`BEHAVIOR: Target resolution: found local '${s}', isElement: ${this.isElement(t)}`),this.isElement(t)?y=[t]:Array.isArray(t)?y=t.filter(t=>this.isElement(t)):"string"==typeof t&&(y=this.queryElements(t,e))}else pt(`BEHAVIOR: Target resolution: querying for '${s}'`),y=this.queryElements(s,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void pt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,e);if("change"===n&&u)return void this.setupChangeObserver(u,i,e);const v=t.customEventSource;if(v&&this.registryIntegration){pt(`BEHAVIOR: executeEventHandler - Using custom event source '${v}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),s={...e,locals:r,it:t,event:t},o=this.enhanceContext(s);pt(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},o)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(v,{event:n,handler:t,target:s,selector:a},e);pt(`BEHAVIOR: Subscribed to custom event source '${v}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${v}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${v}':`,t)}return}const b=Vr.createEventHandler(this,i,e,a,o,{errorSymbol:h,errorHandler:d,finallyHandler:p},1===m.length?c:void 0);let w,E=null;if(f){let t=b;if(f.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(f.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(f.debounce){const e=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const e=f.throttle;let n=0;w=r=>{const i=Date.now();e>i-n||(n=i,t(r))}}else w=t}else w=b;const x=f?.once?{once:!0}:void 0;if(g){for(const t of m)g.addEventListener(t,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],g,t,w):this.cleanupRegistry.registerGlobal(()=>g.removeEventListener(t,w),"listener",`Global ${t} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const t of y){for(const e of m){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(t.synthetic=!0,w(t),x?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,w,x),this.cleanupRegistry.registerListener(t,t,e,w)}E&&this.cleanupRegistry.registerCustom(t,E,"debounce-timeout")}}static createEventHandler(t,e,n,r,i,s,o){return async a=>{const c=Fr.get(a)??0;if(c>=100)return;if(Fr.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{pt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const l=new Map(n.locals),u={...n,locals:l,it:a,event:a};l.has("target")||u.locals.set("target",a.target);const f=t.enhanceContext(u);if(i&&i.length>0){const t=a,e=t.detail;for(const n of i)f.locals.set(n,t[n]??e?.[n]??null)}if(o){const e=a;for(const t of Ur(o))!f.locals.has(t)&&t in e&&f.locals.set(t,e[t]);let n;try{n=await t.evaluateExpression(o,f)}catch(t){return void pt("Event filter threw; skipping handler body:",t)}if(!n)return}const h=async e=>{for(const n of e)try{await t.execute(n,f)}catch(e){if(Br(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(f,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}},d=s?.errorHandler,p=s?.finallyHandler;if(d||p)try{await h(e)}catch(t){if(!d||Br(t))throw t;s?.errorSymbol&&f.locals.set(s.errorSymbol,t),await h(d)}finally{p&&await h(p)}else await h(e)}}setupMutationObserver(t,e,n,r){pt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const i of t){const t=new MutationObserver(async t=>{for(const s of t)if("attributes"===s.type&&s.attributeName===e){ht(`MUTATION DETECTED: attribute '${e}' changed on`,i);const t={...r,me:i,it:s,locals:new Map(r.locals)},o=s.oldValue,a=i.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Br(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),pt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){pt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(t=>this.isElement(t))),pt(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const t of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){ht("CONTENT CHANGE DETECTED on",t,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",t);const s=i.oldValue,o=t.textContent;null!==s&&r.locals.set("oldValue",s),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Br(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,r),pt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=t;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return pt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}function _r(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}function zr(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}const Wr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Dn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Dn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Dn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Dn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:Dn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>Hn(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>Hn(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>Hn(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>Hn(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):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:Dn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Dn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Dn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:t=>Hn(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||t.me;if(i&&i instanceof HTMLElement)return zr(i,n)},validate:t=>Un(t,1,2,"styleRef","property, optional element")??qn(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 n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&t.me?i=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return zr(i,r)},validate:t=>Pn(t,2,"possessiveStyleRef","possessor, property")??qn(t,0,"possessiveStyleRef","possessor")??qn(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&t.me?i=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return zr(i,n)},validate:t=>Pn(t,2,"ofStyleRef","property, reference")??qn(t,0,"ofStyleRef","property")??qn(t,1,"ofStyleRef","reference")}};function Zr(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Jr="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 Kr;function Xr(){return Kr({validate:t=>({success:!0,data:t})})}function Gr(t,e){if(Jr)return Xr();const n=Kr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Zr("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:!1,error:Zr("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:!1,error:Zr("missing-argument",`Required field "${e}" is missing`,e)};const s=n.validate(t);if(!s.success)return{success:!1,error:Zr("validation-error",s.error.message||`Field "${e}" validation failed`,s.error.path?`${e}.${s.error.path}`:e)};void 0!==s.data&&(i[e]=s.data)}return{success:!0,data:i}}});return n.strict=()=>Gr(t,{strict:!0}),n}Kr=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 Kr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:Zr("runtime-error",`String must be at least ${t} characters long`)}:r}};return Kr(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:Zr("runtime-error",`String must be at most ${t} characters long`)}:r}};return Kr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:!0,validate:n=>void 0===n?{success:!0,data:t}:e(n)};return Kr(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?t(i.data)?i:{success:!1,error:Zr("runtime-error",e||"Refinement validation failed")}:i}};return Kr(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const Yr=t=>function(t={}){return Jr?Xr():Kr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Zr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Zr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Zr("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:Zr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Zr("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),Qr=t=>Gr(t),ti=t=>function(t){return Jr?Xr():Kr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Zr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Zr("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const i=t[r].validate(e[r]);if(!i.success)return{success:!1,error:Zr("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(t),ei=()=>Xr();class ni{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(this.ttl>=Date.now()-e.timestamp)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(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),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[n,r]of this.accessOrder)e>r&&(e=r,t=n);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,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const ri=new class{constructor(){this.domQueryCache=new ni(200,3e3),this.exprResultCache=new ni(500,2e3),this.cssMatchCache=new ni(100,5e3),this.formValueCache=new ni(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=t.matches(e);return this.cssMatchCache.set(n,i),i}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),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}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("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}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(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{ri.cleanup()},1e4);const ii=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 n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=ri.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 si(){ri.cleanup(),ii.getMetrics().memoryUsage>52428800&&ii.reset()}let oi=null;function ai(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 n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}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 n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return ai(n,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 n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function ci(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function li(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function ui(t){try{return ai(t,"_"),!0}catch{return!1}}function fi(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,n);const[r,i]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=ci(t),r=ci(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return hi(t,e);case"!=":return!hi(t,e);default:return!1}}function hi(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 n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?hi(t?1:0,e):"boolean"==typeof e?hi(t,e?1:0):t+""==e+""}function di(t,e=[]){return{isValid:!1,errors:t,suggestions:e}}function pi(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function mi(t,e,n,r,i,s=!0,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:s,...void 0!==o&&{error:o}}),r}function yi(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){oi&&clearInterval(oi),oi=setInterval(si,t)}();const gi=ti([ei(),ei()]),vi=ti([ei(),Yr()]),bi={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return mi(this,t,[e,n],e==n,r)}catch(i){throw mi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Bn(t,"equals"),inputSchema:gi,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"]}},wi={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e===n;return r&&mi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Bn(t,"strictEquals")},Ei={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!=n;return r&&mi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Bn(t,"notEquals")},xi={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!==n;return r&&mi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Bn(t,"strictNotEquals")},ki={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=fi(e,n,"<");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Bn(t,"lessThan")},Si={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=fi(e,n,"<=");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Bn(t,"lessThanOrEqual")},Ai={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=fi(e,n,">");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Bn(t,"greaterThan")},Ti={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=fi(e,n,">=");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Bn(t,"greaterThanOrEqual")},Ci={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return mi(this,t,[e,n],e&&n,r)}catch(i){throw mi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Bn(t,"and"),inputSchema:gi,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"]}},$i={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e||n;return r&&mi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Bn(t,"or")},Ni={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&mi(this,t,[e],r,n?Date.now():0),r},validate:t=>Pn(t,1,"not","operand")},Oi={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||(kn(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!Tn(e)||0!==Object.keys(e).length)),n&&mi(this,t,[e],i,r),i},validate:t=>Pn(t,1,"isEmpty","value")},Ri={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:(kn(e),!1)),n&&mi(this,t,[e],i,r),i},validate:t=>Pn(t,1,"no","value")},ji={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!await Oi.evaluate(t,e);return n&&mi(this,t,[e],i,r),i},validate:t=>Pn(t,1,"isNotEmpty","value")},Li={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=Mi(e);return n&&mi(this,t,[e],i,r),i},validate:t=>Pn(t,1,"exists","value")};function Mi(t){return null!=t&&(Array.isArray(t)?t.length>0:!("undefined"!=typeof NodeList&&t instanceof NodeList)||t.length>0)}const Ii={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!Mi(e);return n&&mi(this,t,[e],i,r),i},validate:t=>Pn(t,1,"doesNotExist","value")},Pi={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let s;if(e&&n){if(yi(e)&&yi(n))return s=e.contains(n),r&&mi(this,t,[e,n],s,i),s;if(kn(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&yi(n))return s=o.contains(n),r&&mi(this,t,[e,n],s,i),s;if(o&&kn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=!!a&&o.contains(a),r&&mi(this,t,[e,n],s,i),s}}if(kn(n)&&n.match(/^[.#][\w-]+$/)&&yi(e)){const o=document.querySelector(n);return s=!!o&&e.contains(o),r&&mi(this,t,[e,n],s,i),s}}if(kn(e)&&kn(n))s=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);s=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else s=!(!Tn(e)||!kn(n))&&n in e;return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"contains","container, value")},qi={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=!await Pi.evaluate(t,e,n);return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"doesNotContain","container, value")},Hi={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=null!=e&&null!=n&&(e+"").startsWith(n+"");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"startsWith","str, prefix")},Bi={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=null!=e&&null!=n&&(e+"").endsWith(n+"");return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"endsWith","str, suffix")},Di={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const i=t.evaluationHistory;let s=n,o=r;if(null!=s&&null!=o&&s>o){const t=s;s=o,o=t}const a=null!=s&&null!=o&&e>=s&&o>=e;return i&&mi(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>Pn(t,3,"between","value, min, max")},Fi={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&kn(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{i=function(t,e){return ri.matches(t,e)}(e,t)}catch(t){i=!1}else i=!1}else if(kn(e)&&kn(n)){const t=e,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){i=t.includes(r)}}else i=!1;return mi(this,t,[e,n],i,r)}catch(i){throw mi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Pn(t,2,"matches","element, selector"),inputSchema:vi,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"]}},Ui={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let s=!1;if(e instanceof Element&&kn(n)){const t=n;t.startsWith(".")?s=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(s=e.hasAttribute(t.slice(1,-1)))}return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"has","element, selector")},Vi={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=!await Ui.evaluate(t,e,n);return r&&mi(this,t,[e,n],s,i),s},validate:t=>Pn(t,2,"doesNotHave","element, selector")},_i={equals:bi,strictEquals:wi,notEquals:Ei,strictNotEquals:xi,lessThan:ki,lessThanOrEqual:Si,greaterThan:Ai,greaterThanOrEqual:Ti,and:Ci,or:$i,not:Ni,no:Ri,isEmpty:Oi,isNotEmpty:ji,exists:Li,doesNotExist:Ii,contains:Pi,doesNotContain:qi,startsWith:Hi,endsWith:Bi,between:Di,matches:Fi,has:Ui,doesNotHave:Vi};class zi{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||Sn(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:!1,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}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":Tn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":kn(t)?"String":Sn(t)?"Number":An(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):kn(t)?t.split(""):null==t?[]:Tn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(Sn(t)&&Number.isFinite(t))return t;if(kn(t)){const e=Number(t);return Number.isFinite(e)?e:null}return An(t)?t?1:0:null}}const Wi=Qr({value:Yr().describe("String literal value")}).strict(),Zi=Qr({value:function(t={}){return Jr?Xr():Kr({validate:e=>{const n=Number(e);return isNaN(n)?{success:!1,error:Zr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:!1,error:Zr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:!1,error:Zr("runtime-error","Number must be at most "+t.max)}:{success:!0,data:n}}})}(Xi||{}).describe("Number literal value")}).strict(),Ji=Qr({value:(Jr?Xr():Kr({validate:t=>"boolean"!=typeof t?{success:!1,error:Zr("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}})).describe("Boolean literal value")}).strict(),Ki=Qr({left:ei().describe("Left operand"),right:ei().describe("Right operand")}).strict();var Xi;const Gi={stringLiteral:new class extends zi{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=Wi,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,!1),e}let i=e.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,t));const s=this.success(i,"string");return this.trackSimple(t,n,!0,i),s}catch(e){return this.trackSimple(t,n,!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 n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}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)?(qt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends zi{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Zi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!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 zi{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Ji,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!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 zi{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Ki,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ai(e.left,"left operand")+ai(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!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 zi{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=Ki,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,!0,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,!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=Ki.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(kn(t))return t;if(Sn(t))return""+t;if(An(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends zi{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Ki,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ai(e.left,"left operand")*ai(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!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"])}}}},Yi={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:kn(n)?n.length>0?n[0]:null:Tn(n)&&"length"in n&&Sn(n.length)&&n.length>0?n[0]:null},validate:t=>Fn(t,1,"first","collection")},Qi={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return kn(n)?n.length>0?n[n.length-1]:null:Tn(n)&&"length"in n&&Sn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Fn(t,1,"last","collection")},ts={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!Sn(n))throw Error("Index must be a number");const i=n,s=void 0!==r?r:t.it;if(null==s)return null;if(Array.isArray(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(s instanceof NodeList||s instanceof HTMLCollection){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(s instanceof Element){const t=s.children,e=0>i?t.length+i:i;return e>=0&&t.length>e?t[e]:null}if(kn(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(Tn(s)&&"length"in s&&Sn(s.length)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}return null},validate:t=>Un(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function es(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?es(r,e):null}function ns(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?ns(r,e):null}function rs(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const i=Array.from(e??[]),s=[];for(const e of i)(e.matches&&e.matches(n)||e===t)&&s.push(e);for(let e=0;s.length-1>e;e++)if(s[e]===t)return s[e+1];if(r){const t=s[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=0;i.length>e;e++){const n=i[e];if(2===n.compareDocumentPosition(t))return n}return r?i[0]:void 0}(t,i,e,!!n.wrapping):function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=i.length-1;e>=0;e--){const n=i[e];if(4===n.compareDocumentPosition(t))return n}return r?i[i.length-1]:void 0}(t,i,e,!!n.wrapping)}function is(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const ss={first:Yi,last:Qi,at:ts,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,i]=e,s=r||t.me;return s&&s instanceof Element?n?i?rs(s,n,i,!0):es(s,n):s.nextElementSibling:null},validate:t=>Fn(t,3,"next","optional selector, optional fromElement, optional modifiers")||(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[n,r,i]=e,s=r||t.me;return s&&s instanceof Element?n?i?rs(s,n,i,!1):ns(s,n):s.previousElementSibling:null},validate:t=>Fn(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(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[n,r,i]=e,s=i||t.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=is(t);for(const t of r)if(is(t)>i)return t;return null}(s,n,o):null},validate:t=>Un(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[n,r,i]=e,s=i||t.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=is(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>is(e))return e}return null}(s,n,o):null},validate:t=>Un(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")}};function os(){return _r(Wr,_i,Gi,Jn,ss)}class as{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 n=dn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function cs(t,e,n,r,i,s){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,f=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(t){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(t||null))};var y=(0,n[d])("accessor"===c?{get:f.get,set:f.set}:f[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))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&i.unshift(a)}else(a=o(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),h=!0}function ls(t,e,n){for(var r=arguments.length>2,i=0;e.length>i;i++)n=r?e[i].call(t,n):e[i].call(t);return r?n:void 0}function us(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function fs(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function hs(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let i=t.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function ds(t,e){for(const n of t)e(n);return t}function ps(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function ms(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function ys(t){if(!t)return[];if("string"==typeof t)return t.trim().split(/[\s,]+/).map(t=>{const e=t.trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));if(Array.isArray(t))return t.map(t=>{const e=(t+"").trim();return e.startsWith(".")?e.substring(1):e}).filter(t=>t.length>0&&vs(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&vs(n)?[n]:[]}function gs(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function vs(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!gs(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function bs(t,e){return t.map(t=>{if(gs(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(ft(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function ws(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function Es(t){return{...t}}function xs(t){return()=>new t}function ks(t,e){return e}function Ss(t,e,n){if(pn(t))return t;if(!t){const t=e.me;if(!t)throw Error(ks(0,"No target element \u2014 provide explicit target or ensure context.me is set"));return Ts(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(ks(0,'Context reference "me" is not available'));return Ts(e.me)}if("it"===n){if(!pn(e.it))throw Error(ks(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(ks(0,'Context reference "you" is not available'));return Ts(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(ks(0,"DOM not available \u2014 cannot resolve element selector"));const i=r.querySelector(n);if(!i)throw Error(ks(0,"Element not found with selector: "+n));if(!pn(i))throw Error(ks(0,"Element found but is not an HTMLElement: "+n));return i}throw Error(ks(0,"Invalid target type: "+typeof t))}function As(t,e){if(Array.isArray(t))return t.filter(pn);if(mn(t))return Array.from(t).filter(pn);if(pn(t))return[t];if(!t){const t=e.me;return t&&pn(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&pn(e.me)?[e.me]:[];if("it"===n)return pn(e.it)?[e.it]:[];if("you"===n)return e.you&&pn(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(pn)}}return[]}function Ts(t){if(pn(t))return t;throw Error("Value is not an HTMLElement")}function Cs(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(ks(0,'No "me" element in context'));if(!pn(e.me))throw Error(ks(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(ks(0,'No "it" value in context'));if(!pn(e.it))throw Error(ks(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(ks(0,'No "you" element in context'));if(!pn(e.you))throw Error(ks(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(ks(0,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const $s=["on","from","to","in","with","at"];async function Ns(t,e,n,r,i={},s){let o=t;if(i.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!$s.includes(e.name.toLowerCase())})),(!o||0===o.length)&&i.fallbackModifierKey&&s){const t=s[i.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!pn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of o){const i=await e.evaluate(t,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(pn(i))a.push(i);else if(mn(i)){const t=Array.from(i).filter(pn);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(pn);a.push(...t)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let t=i;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),s=Array.from(r).filter(pn);a.push(...s)}catch(t){throw Error(`Invalid CSS selector: "${i}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!pn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Os(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 n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function js(t,e,n){t.style.setProperty(e,n)}const Ls=["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 Is(t,e,n){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const n=Ms(t);return"string"==typeof n&&n.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 n=Ms(t);return"string"==typeof n&&n.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:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:Ms(r)),extractedFromNode:!0}:{value:await e.evaluate(t,n),extractedFromNode:!1};var r}class Ps{async resolveTargets(t,e,n,r){return Ns(t,e,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return Is(t,e,n)}parseClassNames(t){return ys(t)}isAttribute(t){return fs(t.trim())}isCSSProperty(t){return Os(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>pn(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 qs=(()=>{let t,e,n=[ws({name:"add"})],r=[],i=Ps;var s=e=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return s.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:s}=function(t){const e=hs(t);return{name:e.name,value:e.value??""}}(i);return{type:"attribute",name:r,value:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const s=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw Error("add command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=bs(t.classes,e);n.length>0&&ps(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,ds(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":!function(t,e){ps(t,Object.entries(e),(t,[e,n])=>{t.style.setProperty(e,n)})}(t.targets,t.styles)}var n,r}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 n=e.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(t=>"string"==typeof t))return!1}return!0}};return us(e,"AddCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=Es({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"],category:"dom",compatibility:"standard"}),ls(e,r),s=e})();const Hs=xs(qs),Bs={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function Ds(t){return t.includes("<")&&t.includes(">")}function Fs(t,e,n){!function(t,e,n){"replace"!==n?pn(e)?function(t,e,n){switch(n){case"beforebegin":t.parentElement?.insertBefore(e,t);break;case"afterbegin":t.insertBefore(e,t.firstChild);break;case"beforeend":t.appendChild(e);break;case"afterend":t.parentElement?.insertBefore(e,t.nextSibling)}}(t,e,n):function(t,e,n){const r=n,i=["beforebegin","afterbegin","beforeend","afterend"];if(!i.includes(r))throw Error(`Invalid insert position '${n}'. Expected one of ${i.join(", ")} (or 'replace').`);Ds(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){pn(e)?(t.innerHTML="",t.appendChild(e)):Ds(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,function(t){const e=Bs[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(Bs).join(", ")}.`);return e}(n))}function Us(t){return!!t.parentNode&&(t.remove(),!0)}let Vs=(()=>{let t,e,n=[ws({name:"remove"})],r=[],i=Ps;var s=e=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return s.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(pn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&pn(r[0]))return{type:"element",targets:r.filter(t=>pn(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:hs(i).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const i=this.parseClassNames(r);if(0===i.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=bs(t.classes,e);n.length>0&&ps(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,ds(t.targets,t=>{t.removeAttribute(n)});break;case"styles":!function(t,e){ps(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Us(e)}var n}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}};return us(e,"RemoveCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=Es({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"],category:"dom",compatibility:"standard"}),ls(e,r),s=e})();const _s=xs(Vs);function zs(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Ws(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=zs(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Zs(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Js(t){return"DIALOG"===t.tagName}function Ks(t){return"DETAILS"===t.tagName}function Xs(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&ms(t,n)}}function Gs(t,e,n,r){const i=Xs(t,e,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function Ys(t,e,n,r){const i=Xs(t,e,n),s=()=>{i(),t.removeEventListener(r,s)};return t.addEventListener(r,s,{once:!0}),()=>{t.removeEventListener(r,s)}}function Qs(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(!1===n?t.removeAttribute(r):t.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++)if(i=i[r[t]],null==i)return;return void(i[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}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 to=/^the\s+(.+?)\s+of\s+(.+)$/i,eo=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 no(t){return"string"==typeof t&&to.test(t)}function ro(t,e){const n=t.match(to);if(!n)return null;try{return{element:Ss(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function io(t,e,n){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let i=await e.evaluate(t.target,n);return Array.isArray(i)&&(i=i[0]),pn(i)?{element:i,property:r}:null}(t,e,n);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,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let i=await e.evaluate(t.object,n);return Array.isArray(i)&&(i=i[0]),pn(i)?{element:i,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,i=r.property;let s=await e.evaluate(t,n);if(Array.isArray(s)&&(s=s[0]),!pn(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function so(t,e){const{element:n,property:r}=t;r.startsWith("*")?js(n,r.substring(1),e+""):Qs(n,r,e)}async function oo(t,e,n){let r,i;if(t?.for){const i=await e.evaluate(t.for,n);r="number"==typeof i?i:"string"==typeof i?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=zs(t);return n?n.milliseconds:e}return e}(i):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function ao(t,e){const n=e?.name,r=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 Ls.includes(e)}(e)}(e);if(pn(t)||Array.isArray(t)&&t.every(t=>pn(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};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 Ls.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const co=xs((()=>{let t,e,n=[ws({name:"toggle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(t){if(!t||"asExpression"!==t.type)return!1;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=!0;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const i=t.args[0],s=i?.name;if("between"===s&&t.args.length>=4){const{duration:r,untilEvent:i}=await oo(t.modifiers,e,n),s=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},o=await s(t.args[1]),a=await s(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await Ns(c,e,n,"toggle",l,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const o=await io(i,e,n);if(o)return{type:"property",target:o};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,s=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,s=2),"*"===r&&t.modifiers?.on){const i=t.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:s,untilEvent:o}=await oo(t.modifiers,e,n),a=Rs(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:s,untilEvent:o}}}}const o=Rs(r);if(o){const{duration:r,untilEvent:i}=await oo(t.modifiers,e,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Ns(t.args.slice(s),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await oo(t.modifiers,e,n),{value:l}=await Is(i,e,n);if(no(l)){const t=ro(l,n);if(t)return{type:"property",target:t}}const{type:u,expression:f}=ao(l,i),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=hs(f);return{type:"attribute",name:r,value:i,targets:await Ns(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=Rs(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await Ns(t.args.slice(1),e,n,"toggle",h,t.modifiers)}}case"element":{let s;if(pn(l))s=[l];else if(Array.isArray(l)&&l.every(t=>pn(t)))s=l;else if(f){const t=document.querySelectorAll(f);s=Array.from(t).filter(t=>pn(t))}else s=await Ns([i],e,n,"toggle",h,t.modifiers);const o=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"===o){const i=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const i=e.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:i,targets:s}}return"details"===o?{type:"details",targets:Zs(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:ys(f),targets:s,duration:a,untilEvent:c}}default:{const r=ys(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Ns(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=bs(t.classes,e);if(0===n.length)return[...t.targets];if(ps(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&Gs(e,"class",n[0],t.duration),t.untilEvent&&Ys(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,ds(t.targets,t=>{ms(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Gs(e,"attribute",t.name,t.duration),t.untilEvent&&Ys(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return ds(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):Mn(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||eo.has(r)||eo.has(r.toLowerCase())){const n=!e;return so(t,n),n}if("number"==typeof e){const n=0===e?1:0;return so(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(so(t,i),i):(t.element[r]=e,so(t,""),"")}so(t,!e)}(t.target),[t.target.element];case"dialog":return ds(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return ds(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return ds(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 n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(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&&Gs(e,"class",t.classA,t.duration),t.untilEvent&&Ys(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return us(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})());class lo{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await Ns(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,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=>pn(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||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 uo=(()=>{let t,e,n=[ws({name:"show"})],r=[],i=lo;var s=e=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return s.metadata}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>pn(t))&&"string"==typeof e.defaultDisplay}};return us(e,"ShowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=Es({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),s=e})();const fo=xs(uo);let ho=(()=>{let t,e,n=[ws({name:"hide"})],r=[],i=lo;var s=e=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return s.metadata}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=>pn(t))}};return us(e,"HideCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=Es({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),s=e})();const po=xs(ho);const mo=xs((()=>{let t,e,n=[ws({name:"put"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let s=-1,o=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){s=e,o=c;break}}let a=null,c=null;if(-1===s){const e=i.find(e=>t.modifiers[e]);if(e)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,s)[0]||null,c=t.args.slice(s+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(o);let f,h,d=null;if(c){const t=r(c),i=await io(c,e,n);if(i)return{value:l,targets:[i.element],position:"into",memberPath:i.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const i=t.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}else d=i}if(d&&r?.name)f=r.name;else if(!d&&!f){const t=await e.evaluate(c,n);"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&&no(t)){const e=ro(t,n);if(e)return{value:l,targets:[e.element],position:"into",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:h=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const r=En(await e.evaluate(c,n));if(r)return{value:l,targets:r,position:u,memberPath:f};h=t}}else{const t=await e.evaluate(c,n),r=En(t);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?d=t:h=t)}}return h?{value:l,targets:[],position:u,memberPath:f,variableName:h}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:f}}async execute(t,e){const{value:n,targets:r,position:i,memberPath:s,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,n),e[o]=n,void Object.assign(e,{it:n});if(s)for(const t of r)this.setProperty(t,s,n);else for(const t of r)Fs(t,this.parseValue(n),i);return r}mapPosition(t){switch(t){case"into":return"into";case"before":return"before";case"after":return"after";case"at start of":return"prepend";case"at end of":return"append";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!pn(e.me))throw Error("put: no target and context.me is null");return[e.me]}return function(t){if("undefined"==typeof document)throw Error("DOM not available");const e=Array.from(document.querySelectorAll(t)).filter(t=>pn(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}(t)}parseValue(t){return pn(t)?t:null==t?"":t+""}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,n){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++){if(!i[r[t]])throw Error(`Property path "${e}" does not exist`);i=i[r[t]]}i[r[r.length-1]]=n}};return us(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})()),yo={"&":"&","<":"<",">":">",'"':""","'":"'"};function go(t){return t.replace(/[&<>"']/g,t=>yo[t])}let vo=(()=>{let t,e,n=[ws({name:"make"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers.an??t.modifiers.a??t.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let s="string"==typeof i&&i.startsWith("<")?i:await e.evaluate(r,n);if(null==s)throw Error("Make command requires class name or DOM element expression");"string"==typeof s&&s.startsWith("<")&&(s=await async function(t,e){if(!t.includes("{"))return t;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(t));){let t=i[0];try{const n=await or(i[1].trim(),e);null!=n&&(t=go(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:t})}let s=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,text:i}=r[t];s=s.slice(0,e)+i+s.slice(e+n)}return s}(s,n));const o=void 0!==t.modifiers.an?"an":"a",a=await async function(t,e,n){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const r=[];for(const i of t.args)r.push(await e.evaluate(i,n));return r}const r=await e.evaluate(t,n);return Array.isArray(r)?r:[r]}(t.modifiers.from,e,n),c=await async function(t,e,n){if(!t)return;if(("symbol"===t.type||"identifier"===t.type)&&"string"==typeof t.name)return t.name;const r=await e.evaluate(t,n);return"string"==typeof r?r:void 0}(t.modifiers.called,e,n);return{article:o,expression:s,constructorArgs:a,variableName:c}}async execute(t,e){const{expression:n,constructorArgs:r=[],variableName:i}=t,s="string"==typeof n&&n.startsWith("<"),o=s&&n.endsWith("/>")?function(t){const e=t.slice(1,-2);let n="div",r=e;const i=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=e.slice(i[0].length));const s=document.createElement(n),o=r.split(/(?=[.#])/);for(const t of o)if(t.startsWith("#")){const e=t.slice(1);e&&(s.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&s.classList.add(e)}return s}(n):s&&/<\/[a-zA-Z]/.test(n)?function(t){const e=document.createElement("template");e.innerHTML=t.trim();const n=e.content.firstElementChild;if(n&&pn(n))return n;const r=document.createElement("div");r.innerHTML=t.trim();const i=r.firstElementChild;return i&&pn(i)?i:r}(n):function(t,e,n){if(pn(t))return t;const r=t+"";let i;if("undefined"!=typeof window&&(i=window[r]),i||"undefined"==typeof global||(i=global[r]),!i&&n.variables?.has(r)&&(i=n.variables.get(r)),!i||"function"!=typeof i)throw Error(`Constructor '${r}' not found or is not a function`);return 0===e.length?new i:new i(...e)}(n,r,e);return Object.assign(e,{it:o}),i&&vn(i,o,e),o}};return us(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})();const bo=xs(vo),wo=xs((()=>{let t,e,n=[ws({name:"empty"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ns(t.args,e,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.innerHTML=""}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})());function Eo(t){if("string"!=typeof t)return;const e=t.toLowerCase().trim();return"non-modal"===e||"nonmodal"===e?"non-modal":"modal"===e?"modal":void 0}function xo(t){return t.hasAttribute("popover")}const ko=xs((()=>{let t,e,n=[ws({name:"open"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=(t.args??[]).filter(t=>{const e=t;if("identifier"!==e?.type)return!0;const n=e.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=Zs(await Ns(r,e,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)),s=await async function(t,e,n,r){if(e?.as){const t=Eo(await n.evaluate(e.as,r));if(t)return t}for(const e of t){const t=e;if("asExpression"!==t?.type)continue;const n=t.targetType,r=Eo(n?.name??n?.value);if(r)return r}for(let e=0;t.length-1>e;e++){const i=t[e];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(t[e+1],r);if("string"==typeof i){const t=i.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}}return"modal"}(t.args??[],t.modifiers??{},e,n);return{targets:i,dialogMode:s}}async execute(t,e){for(const e of t.targets)if(Js(e))e.open||("modal"===t.dialogMode?e.showModal():e.show());else if(Ks(e))e.open=!0;else if(xo(e)){const t=e;if("function"==typeof t.showPopover)try{t.showPopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>pn(t))||"modal"!==e.dialogMode&&"non-modal"!==e.dialogMode)}};return us(e,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})());function So(t){return t.hasAttribute("popover")}const Ao=xs((()=>{let t,e,n=[ws({name:"close"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:Zs(await Ns(t.args,e,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers))}}async execute(t,e){for(const e of t.targets)if(Js(e))e.open&&e.close();else if(Ks(e))e.open=!1;else if(So(e)){const t=e;if("function"==typeof t.hidePopover)try{t.hidePopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})());function To(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e}const Co=xs((()=>{let t,e,n=[ws({name:"select"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ns(t.args,e,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if(0!==t.targets.length)for(const e of t.targets){if(To(e)){e.select();continue}const t=e.ownerDocument??("undefined"!=typeof document?document:null),n=t?.defaultView;if(!t||!n)continue;const r=n.getSelection?.();if(r)try{const n=t.createRange();n.selectNodeContents(e),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})());function $o(t){return"FORM"===t.tagName}const No=xs((()=>{let t,e,n=[ws({name:"reset"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ns(t.args,e,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)$o(e)&&e.reset()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),ls(e,r),i=e})()),Oo=xs((()=>{let t,e,n=[ws({name:"focus"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ns(t.args,e,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.focus()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),ls(e,r),i=e})()),Ro=xs((()=>{let t,e,n=[ws({name:"blur"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Ns(t.args,e,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.blur()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return us(e,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),ls(e,r),i=e})());async function jo(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return pn(i)?i:null}const Lo=xs((()=>{let t,e,n=[ws({name:"set"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],i=r?.name||r?.value,s=r?.scope,o=await async function(t,e,n,r){if(!t)return null;const i=t,s=i.type;if(s){const e=Mt(s);if(e)return{kind:"node-write",node:t,writer:e}}if(r.selectorSource&&"selector"===s&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const o=await async function(t,e,n,r){const i=t;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const t=await jo(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await jo(i.object,e,n);if(t)return{elements:[t],name:i.property.attributeName}}return null}(t,e,n,r.scopeElements);if(o)return{kind:"attribute",elements:o.elements,name:o.name};const a=await io(t,e,n);if(a)return a.property.startsWith("*")?{kind:"style",element:a.element,property:a.property.substring(1)}:{kind:"property",target:a};if(r.bareReference&&("identifier"===s||"variable"===s||"symbol"===s)&&"string"==typeof i.name){const t=i.scope;return{kind:"variable",name:i.name,scope:"element"===t||"global"===t?t:void 0}}return null}(r,e,n,{scopeElements:()=>this.resolveTargets(t.modifiers.on,e,n)});if(o)return function(t,e){switch(t.kind){case"node-write":return{type:"node-write",node:t.node,value:e,writer:t.writer};case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"style":return{type:"style",element:t.element,property:t.property,value:e+""};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};default:throw Error(`set: unrequested write-target rung '${t.kind}'`)}}(o,await this.extractValue(t,e,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,t,e,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await e.evaluate(r,n):i,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(pn(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(no(a)){const r=ro(a,n);if(r){const i=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,t,e,n)}if("string"==typeof a&&Os(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:i+""}}if("string"==typeof a&&fs(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=Cs(r[1],n),s=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:s}}}if(pn(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&pn(a[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(t,e,n),scope:"element"===s||"global"===s?s:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?hn(e,t.name,t.value):"global"===t.scope?vn(t.name,t.value,e,"global"):vn(t.name,t.value,e),"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":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Qs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return js(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"object-literal":for(const e of t.targets)for(const[n,r]of Object.entries(t.properties))Qs(e,n,r);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"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,n,r){const i=t.object,s=t.property;if(i?.name&&s?.name){const t=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const i=Cs(t,r),o=await this.extractValue(e,n,r);return{type:"property",element:i,property:s.name,value:o}}}const o=t.object,a=t.computed;if(o){const i=o;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const t=await n.evaluate(i.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(t.property,r)+"":s?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return Ss(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return As(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const i=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,s,o]=i,a=Ss(o,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:s.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&&Array.isArray(e.elements)&&e.elements.every(pn)&&"value"in e;case"property":return"string"==typeof e.property&&pn(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&pn(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}}};return us(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"data",compatibility:"standard"}),ls(e,r),i=e})());function Mo(t){return t&&"object"==typeof t&&t.type||"unknown"}let Io=(()=>{let t,e,n=[ws({name:"increment"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",i=await async function(t,e,n,r){if(!t.args||0===t.args.length)throw Error(r+" command requires a target");const i=t.args[0];let s,o,a;const c=Mo(i);if("identifier"===c)s=i.name,i.scope&&(o=i.scope);else if("literal"===c)s=i.value;else{const t=Mt(c);if(t){const r=await e.evaluate(i,n),o="number"==typeof r?r:null==r?0:Number(r)||0;s=o,a={node:i,writer:t,currentValue:o}}else{const t=await e.evaluate(i,n);s=Array.isArray(t)&&t.length>0?t[0]:t}}let l=1,u=o;for(let r=1;t.args.length>r;r++){const i=t.args[r];if(i&&"literal"===i.type){const t=i.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(i&&"literal"!==i.type){const t=await e.evaluate(i,n);"number"==typeof t&&(l=t)}}const f=t.modifiers?.by;if(f){const t=f.value;if("literal"===Mo(f)&&"number"==typeof t)l=t;else if("literal"!==Mo(f)){const t=await e.evaluate(f,n);"number"==typeof t&&(l=t)}}return{target:s,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(t,e,n,r);return{...i,operation:r}}async execute(t,e){const{target:n,property:r,scope:i,amount:s=1,operation:o="increment",customWrite:a}=t;if(a){const t=isFinite(s)?s:1,n="increment"===o?a.currentValue+t:a.currentValue-t;return await a.writer(a.node,n,e),Object.assign(e,{it:n}),n}const c=function(t,e,n,r){if("number"==typeof t)return t;if(pn(t)){const n=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?yn(n.getAttribute(e)):yn(n[e]):yn(n.value||n.textContent)}return"string"==typeof t?"element"===n?yn(gn(t,r,"element")):"global"===n?yn(gn(t,r,"global")):t.includes(".")?function(t,e){const n=t.split("."),r=n[1],i=bn(n[0],e);return i?yn(i[r]):0}(t,r):yn("me"===t&&r.me?r.me.value||0:"it"===t?r.it||0:"you"===t&&r.you?r.you.value||0:gn(t,r)):yn(t)}(n,r,i,e);let l;if(isNaN(c))l=NaN;else{const t=isFinite(s)?s:1;l="increment"===o?c+t:c-t}return function(t,e,n,r,i){if(pn(t)){const n=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?n.setAttribute(e,r+""):n[e]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof t){if("element"===n)return void vn(t,r,i,"element");if("global"===n)return void vn(t,r,i,"global");if(t.includes("."))return void function(t,e,n){const r=t.split("."),i=r[1],s=bn(r[0],n);s&&(s[i]=e)}(t,r,i);if("me"===t&&i.me)return void(i.me.value=r);if("it"===t)return void Object.assign(i,{it:r});if("you"===t&&i.you)return void(i.you.value=r);vn(t,r,i)}}(n,r,i,l,e),Object.assign(e,{it:l}),l}};return us(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"data",compatibility:"standard"}),ls(e,r),i=e})();const Po=xs(Io),qo=xs(Io);function Ho(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e}const Bo=xs((()=>{let t,e,n=[ws({name:"clear"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.args?.[0],i=r?.type,s=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof s))try{const t=await e.evaluate(r,n);if(!pn(t)&&!Array.isArray(t))return{type:"variable",name:s}}catch{return{type:"variable",name:s}}return{type:"form-fields",targets:await Ns(t.args,e,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if("variable"===t.type)return e.locals.set(t.name,null),void Object.assign(e,{it:null});for(const e of t.targets)Ho(e)&&("SELECT"===e.tagName?e.selectedIndex=-1:e.value="")}validate(t){if("object"!=typeof t||null===t)return!1;if("variable"===t.type)return"string"==typeof t.name;if("form-fields"===t.type){const e=t.targets;return Array.isArray(e)&&e.every(t=>pn(t))}return!1}};return us(e,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"],category:"data",compatibility:"standard"}),ls(e,r),i=e})());function Do(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 Fo=(()=>{let t,e,n=[ws({name:"trigger"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",i=r;if(!t.args?.length)throw Error(i+" command requires an event name");const s=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===s(o)||"callExpression"===s(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===s(o)||"keyword"===s(o))a=o.name;else{const t=await e.evaluate(o,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return!1;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const s=t.args.slice(r+1),o=s.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?s:s.slice(0,o);l=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const i=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)i.push(n.me);else if("you"===t&&n.you)i.push(n.you);else if("it"===t&&n.it)i.push(n.it);else if(pn(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(pn));else if(Array.isArray(t))i.push(...t.filter(pn));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);i.push(...Array.from(e).filter(pn));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);i.push(t)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const i of t){const t=await e.evaluate(i,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=Do(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:!0,cancelable:!0,composed:!1},i=t.findIndex(t=>"with"===(t.name||t.value));if(-1===i)return r;for(const s of t.slice(i+1)){const t=await e.evaluate(s,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=!0:"nobubbles"===e?r.bubbles=!1:"cancelable"===e?r.cancelable=!0:"nocancelable"===e?r.cancelable=!1:"composed"===e&&(r.composed=!0)}}return r}};return us(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"event",compatibility:"standard"}),ls(e,r),i=e})();const Uo=xs(Fo),Vo=xs(Fo);function _o(t,e,n,r){return t?new Promise(n=>{const i=()=>{s({event:null,timedOut:!1,cancelled:!0})},s=function(n,s){let a=!1;return n=>{a||(a=!0,t.removeEventListener(e,o),r&&r.removeEventListener("abort",i),s(n))}}(0,n),o=t=>{s({event:t,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(t.addEventListener(e,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function zo(t){return new Promise(e=>setTimeout(e,t))}const Wo=xs((()=>{let t,e,n=[ws({name:"wait"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await zo(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await _o(r,t.eventName)).event;if(Object.assign(e,{it:i}),t.destructure)for(const n of t.destructure)n in i&&e.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const t of i.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:Ws(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const i=await n.evaluate(t,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const s=i.match(/^(\w+)\(([^)]+)\)$/),o=s?s[1]:i,a=s?s[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}i||(i=r.me??void 0);const s=[];for(const e of t){const t=e;if("objectLiteral"!==t.type||!t.properties)continue;let o,a="",c=[];for(const e of t.properties){const t=e.key?.name||e.key?.value;"name"===t&&e.value?a=e.value.value||"":"args"===t&&e.value?.elements?c=e.value.elements.map(t=>t.value||t.name||""):"duration"===t&&e.value&&(o=e.value)}if(o){const t=await n.evaluate(o,r);s.push({type:"time",milliseconds:Ws(t)})}else a&&s.push({type:"event",eventName:a,target:i,destructure:c.length>0?c:void 0})}return 1===s.length?s[0]:{type:"race",conditions:s}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const i=await e.evaluate(t.modifiers.or,n),s=Array.isArray(i)?i:[i];for(const t of s)try{r.push({type:"time",milliseconds:Ws(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,i=t.map(t=>"time"===t.type?zo(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):_o(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(i)}finally{n.abort()}}};return us(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"async",compatibility:"standard"}),ls(e,r),i=e})()),Zo=new Map;let Jo=[/^4\d{2}$/,/^5\d{2}$/],Ko=(()=>{let t,e,n=[ws({name:"fetch"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(t.args[0],e,n),i=this.parseResponseType(t.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(t.modifiers.with,e,n),throwOnError:!t.modifiers.doNotThrow&&"response"!==i}}async execute(t,e){const n=Date.now(),{url:r,responseType:i,options:s}=t,o=new AbortController;let a;e.me&&(a=()=>o.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...s,signal:o.signal},l=Zo.get(i);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;s.timeout&&(u=setTimeout(()=>o.abort(),s.timeout));try{let s=await fetch(r,c);if(e.me){const t={response:s};this.dispatchEvent(e.me,"fetch:afterResponse",t),s=t.response}if(t.throwOnError&&function(t){const e=t+"";return Jo.some(t=>t.test(e))}(s.status)){const t=Error(`Fetch failed for ${r}: HTTP ${s.status} ${s.statusText}`.trim());throw t.response=s,t.isFetchStatusError=!0,t}const o=await this.handleResponse(s,i,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:o});const a={status:s.status,statusText:s.statusText,headers:s.headers,data:o,url:s.url,duration:Date.now()-n};return Object.assign(e,{it:o}),a}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 "+r);if(t instanceof Error&&!0===t.isFetchStatusError)throw t;throw Error(`Fetch failed for ${r}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,n){const r=await e.evaluate(t,n);if("string"!=typeof r||!r){const e=t;if(null==r&&"identifier"===e?.type&&e.name)throw Error(`fetch: URL expression "${e.name}" evaluated to ${r+""} \u2014 check the variable is set, or quote it if you meant a literal URL (fetch 'https://example.com/path')`);throw Error("fetch: URL must be a non-empty string")}return r}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(Zo.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,n){if(!t)return{};const r=await e.evaluate(t,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const i={};return"method"in r&&(i.method=(r.method+"").toUpperCase()),"headers"in r&&(i.headers=this.parseHeaders(r.headers)),"body"in r&&(i.body=this.parseBody(r.body)),"credentials"in r&&(i.credentials=r.credentials),"mode"in r&&(i.mode=r.mode),"cache"in r&&(i.cache=r.cache),i}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[n,r]of Object.entries(t))e.set(n,r+"");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,n){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 r=Zo.get(e);return r?r.handler(t,n):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),n=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>n.appendChild(t.cloneNode(!0))),1===n.childNodes.length&&pn(n.firstChild)?n.firstChild:n}dispatchEvent(t,e,n){t.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!0}))}};return us(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"async",compatibility:"standard"}),ls(e,r),i=e})();const Xo=xs(Ko),Go=xs((()=>{let t,e,n=[ws({name:"go"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{args:[]}}async execute(t,e){const{args:n}=t;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,e),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}isBareUrl(t){return!!t.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(t)}findBareUrl(t){for(const e of t)if("to"!==e&&"the"!==e)return"string"==typeof e&&this.isBareUrl(e)?e:null;return null}async navigateToBareUrl(t,e){if(e.includes("new")&&e.includes("window")){if("undefined"!=typeof window&&window.open){const e=window.open(t,"_blank");e?.focus&&e.focus()}}else t.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=t):"undefined"!=typeof window&&(window.location.assign?.(t)??(window.location.href=t));return t}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const n=t.findIndex(t=>"url"===t),r=t[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",s=t.includes("new")&&t.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(s){if("undefined"!=typeof window&&window.open){const t=window.open(i,"_blank");t?.focus&&t.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const n=this.parseScrollPosition(t),r=this.parseScrollTarget(t),i=this.parseScrollOffset(t),s=!t.includes("instantly"),o=this.resolveScrollTarget(r,e);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const t=s?"smooth":"instant",e=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){o.scrollIntoView?.({behavior:t,block:e,inline:r});const{x:s,y:a}=this.calculateScrollPosition(o,n,i);window.scrollTo?.({left:s,top:a,behavior:t})}else o.scrollIntoView?.({behavior:t,block:e,inline:r})}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"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,s=!1;for(const o of t)"string"==typeof o&&(n.includes(o)?(e.vertical=o,i=!0):r.includes(o)&&(e.horizontal=o,s=!0));return s&&!i&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let n=t[e+1];return"the"===n&&t.length>e+2&&(n=t[e+2]),n}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!n.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 n=t[e];if("string"==typeof n){const t=n.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===n||"-"===n)&&t.length>e+1){const r=t[e+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const n="string"==typeof t?t:t+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&pn(e.me))return e.me;if("it"===n&&pn(e.it))return e.it;if("you"===n&&pn(e.you))return e.you;const r=gn(n,e);if(pn(r))return r;if("undefined"!=typeof document)try{const t=document.querySelector(n);if(t)return t}catch{try{const t=document.getElementsByTagName(n);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,n){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const r=t.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,s=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=s;switch(e.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-o/2;break;case"right":c=r.right+i-o}switch(e.vertical){case"top":l=r.top+s+n;break;case"middle":l=r.top+s+r.height/2-a/2+n;break;case"bottom":l=r.bottom+s-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}};return us(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"navigation",compatibility:"standard"}),ls(e,r),i=e})()),Yo=xs((()=>{let t,e,n=[ws({name:"log"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}};return us(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({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"],category:"utility",compatibility:"standard"}),ls(e,r),i=e})()),Qo=xs((()=>{let t,e,n=[ws({name:"breakpoint"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{}}async execute(t,e){}validate(t){return"object"==typeof t&&null!==t}};return us(e,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;cs(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=Es({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),ls(e,r),i=e})()),ta=function(t,e){const n=new Mr(null);for(const e of t)n.register(e);return new Vr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Hs(),_s(),co(),fo(),po(),mo(),bo(),wo(),ko(),Ao(),Co(),No(),Oo(),Ro(),Lo(),Po(),qo(),Bo(),Vo(),Uo(),Wo(),Xo(),Go(),Yo(),Qo()],{expressionRegistry:os()}),ea={parse:t=>tn(t),execute:async(t,e)=>{const n=function(t){if(!t)return dn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=dn(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),r=tn(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await ta.execute(r.node,n)}},na=function(t){return new as(t)}(ea),ra={runtime:ea,parse:t=>ea.parse(t),execute:async(t,e)=>ea.execute(t,e),createContext:dn,attributeProcessor:na,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","empty","open","close","select","reset","focus","blur","set","increment","decrement","clear","send","trigger","wait","fetch","go","log","breakpoint"],eval:async(t,e)=>ea.execute(t,e),init:()=>{na.init()}};"undefined"!=typeof window&&(window.hyperfixi=ra,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{na.init()}):na.init());class ia{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ai(t,"left operand");return{success:!0,value:li(r+ai(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return di([pi("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return di([pi("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),di([pi("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return ui(n)?ui(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[pi("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[pi("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const sa={addition:new ia,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ai(t,"left operand");return{success:!0,value:li(r-ai(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ia).validate(t)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ai(t,"left operand");return{success:!0,value:li(r*ai(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ia).validate(t)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=!0){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(ai(t,"left operand"),ai(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ia).validate(t)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(ai(t,"left operand"),ai(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new ia).validate(t)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ai(t,"left operand"),i=ai(n,"right operand");return{success:!0,value:li(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:!1,errors:[pi("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ia).validate(t)}}};var oa=Object.freeze({__proto__:null,conversion:Jn,conversionExpressions:Jn,createCommonRegistry:os,createCoreRegistry:function(){return _r(Wr,_i,Gi)},createExpressionRegistry:_r,createFullExpressionRegistry:function(){return _r(Wr,_i,Jn,ss,Yn,Gi,sa)},createFullRegistry:function(){return _r(Wr,_i,Gi,Jn,ss,Yn)},logical:_i,logicalExpressions:_i,positional:ss,positionalExpressions:ss,properties:Yn,propertiesExpressions:Yn,references:Wr,referencesExpressions:Wr,special:Gi,specialExpressions:Gi});return ra}();
|
|
1
|
+
var hyperfixi=function(){"use strict";const t="then",e="else",n="end",r="and",i="for",s="while",o="until",a="forever",c="times",l="index",u="in",f="to",h="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",w="start",E=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","prepend","process","pseudo-command","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait","for"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","go","tell","pick","start","swap","morph","push","replace","process"]),k=(new Set(["if","unless","repeat","wait","for","while"]),"at start of"),S="at end of",A=["into","before","after","at",k,S,"at the start of","at the end of"],T=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"]),C=t=>E.has(t.toLowerCase()),$=t=>x.has(t.toLowerCase()),N=t=>T.has(t.toLowerCase()),O=t=>R.has(t.toLowerCase()),R=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"]),j=new Set(["me","it","you","result","my","its","your"]),L=new Set(["and","or","not","no"]),M=new Set(["==","!=","===","!==","<",">","<=",">=","is","is not","am","is a","is an","is not a","is not an","precedes","does not precede","follows","does not follow","contains","starts with","ends with","does not start with","does not end with","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","is between","is not between","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","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),I=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"]),P=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 q;!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"}(q||(q={}));const H=new Set(["+","-","*","/","mod"]),B=new Set(["ms","s","seconds","minutes","hours","days"]);function D(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function F(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 U(t){const e=t.input,n=e.length;for(;n>t.position;){const n=e[t.position];if(" "!==n&&"\t"!==n&&"\r"!==n&&"\n"!==n)break;F(t)}}function V(t,e,n,r,i){const s=r??t.position-n.length,o=t.position;let a=t.column-n.length;if(void 0!==r){a=1;let e=-1;for(let n=0;r>n;n++)"\n"!==t.input[n]&&"\r"!==t.input[n]||(e=n);a=r-e}const c={kind:e,value:n,start:s,end:o,line:_(t,s),column:a};t.tokens.push(c)}function _(t,e){let n=1;for(let r=0;e>r&&t.input.length>r;r++){const e=t.input[r];"\n"===e?n++:"\r"===e&&(n++,t.input.length>r+1&&"\n"===t.input[r+1]&&r++)}return n}function z(t){const e=t.position;let n="";for(F(t),F(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=F(t);V(t,q.COMMENT,"--"+n,e)}function W(t){const e=t.position,n=F(t);let r=n;for(;t.input.length>t.position;){const e=F(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=F(t))}V(t,q.STRING,r,e)}function Z(t){const e=t.position;F(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){F(t);break}if("\\"===e){if(F(t),t.input.length>t.position){const e=F(t);switch(e){case"n":n+="\n";break;case"t":n+="\t";break;case"r":n+="\r";break;case"\\":n+="\\";break;case"`":n+="`";break;default:n+=e}}}else n+=F(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);V(t,q.TEMPLATE,n,e)}function J(t){const e=t.position;let n=F(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=F(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=F(t),"}"===e)break}V(t,q.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)F(t),t.input.length>t.position&&(n+=F(t));else{if(!nt(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=F(t)}}V(t,q.SELECTOR,n,e)}}function K(t){const e=t.position;if(rt(t))return void function(t,e){const n=t.input;let r="",i=0,s="";for(;n.length>t.position;){const e=n[t.position];if(s)r+=F(t),e===s&&(s="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=F(t);if(n.length>t.position&&(r+=F(t)),i--,0>=i)break;continue}let e=!1,s="";for(;n.length>t.position;){const i=n[t.position];if(s)r+=F(t),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=F(t);break}r+=F(t)}else s=i,r+=F(t)}if(e||i++,0>=i)break;continue}r+=F(t)}else s=e,r+=F(t)}V(t,q.SELECTOR,r,e)}(t,e);let n="";for(n+=F(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=F(t),"/"===e&&">"===r){n+=F(t);break}}V(t,q.SELECTOR,n,e)}function X(t){const e=t.position;let n=F(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!nt(e)&&"_"!==e&&"-"!==e)break;n+=F(t)}V(t,q.SYMBOL,n,e)}function G(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===D(t,1))return n="'s",F(t),F(t),void V(t,q.OPERATOR,n,e);const i=t.input.substring(t.position,t.position+2),s=t.input.substring(t.position,t.position+3);["===","!=="].includes(s)?(n=s,F(t),F(t),F(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,F(t),F(t)):n=F(t),V(t,q.OPERATOR,n,e)}function Y(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=F(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}if(r>t.position){const e=n[t.position];if("e"===e||"E"===e){const e=r>t.position+1?n[t.position+1]:"",s=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">s||s>"9"))for(i+=F(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=F(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=F(t)}}}const s=t.position;let o="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=F(t)}B.has(o)?V(t,q.TIME,i+o,e):(t.position=s,V(t,q.NUMBER,i,e))}function Q(t){const e=t.position,n=t.input,r=n.length;let i="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e&&"-"!==e)break;i+=F(t)}const s=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return!1;const s=t.tokens[t.tokens.length-1];if(s&&(s.kind===q.IDENTIFIER||s.kind===q.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return!1}U(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+=F(t)}if(o){const e=o.toLowerCase(),i=`${r} ${e}`,s=function(t,e,n,r){const i=e.toLowerCase(),s=n.toLowerCase();if("at"===i){const e=t.position;if("the"===s){U(t);let n="";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;n+=F(t)}const i=n.toLowerCase();if("start"===i||"end"===i){U(t);let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z")&&("0">n||n>"9")&&"_"!==n&&"-"!==n)break;e+=F(t)}if("of"===e.toLowerCase())return V(t,q.IDENTIFIER,`at the ${i} of`,r),!0}return t.position=e,!1}if("start"===s||"end"===s){U(t);let n="";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;n+=F(t)}return"of"===n.toLowerCase()?(V(t,q.IDENTIFIER,`at ${s} of`,r),!0):(t.position=e,!1)}}return!1}(t,r,e,n);if(s)return!0;const a=function(t,e,n){const r=t.position;let i=`${e} ${n}`,s=t.position;const o=[e,n];for(;8>o.length&&(U(t),t.input.length>t.position);){let e="";for(;t.input.length>t.position;){const n=t.input[t.position];if(("a">n||n>"z")&&("A">n||n>"Z"))break;e+=F(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");M.has(n)&&(i=n,s=t.position)}return M.has(i)&&i!==`${e} ${n}`?(t.position=s,i):(t.position=r,null)}(t,r,e);if(a)return V(t,q.OPERATOR,a,n),!0;if(M.has(i))return V(t,q.OPERATOR,i,n),!0}return M.has(r)?(t.position=i,V(t,q.OPERATOR,e,n),!0):(t.position=i,!1)}(t,i,e);if(s)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||L.has(e)||H.has(t)||H.has(e)||M.has(e)?q.OPERATOR:q.IDENTIFIER}(i);V(t,o,i,e)}function tt(t){const e=t.position,n=t.input,r=n.length;F(t);let i="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;i+=F(t)}V(t,q.IDENTIFIER,i,e)}function et(t){return/[a-zA-Z]/.test(t)}function nt(t){return/[a-zA-Z0-9]/.test(t)}function rt(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return!1;let r=t.position+1,i="";for(;e.length>r&&/[a-zA-Z0-9-]/.test(e[r]);)i+=e[r],r++;return i.length>0&&-1!==e.indexOf("</"+i+">",r)}function it(t){if(rt(t))return!0;let e=t.position+1,n=!1;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(nt(r)||"."===r||"#"===r||"["===r||"]"===r||":"===r||"-"===r||"_"===r||" "===r||"="===r||'"'===r||"'"===r||"("===r||")"===r||"*"===r||"^"===r||"$"===r||"~"===r||"|"===r||">"===r||"+"===r||","===r||"{"===r||"}"===r)n=!0,e++;else{if(" "!==r&&"\t"!==r)return!1;e++}if(e-t.position>50)return!1}return!1}function st(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const ot=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}(),at=ot,ct=ot,lt=ot,ut=ot,ft=(...t)=>{at&&console.log("\ud83d\udd27",...t)},ht=(...t)=>{ct&&console.log("\ud83c\udfaf",...t)},dt=(...t)=>{lt&&console.log("\ud83d\udcdd",...t)},pt=(...t)=>{ut&&console.log("\ud83d\ude80",...t)};let mt=!1,yt=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(mt=!0,yt=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 vt{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(vt.SKIP_SEMANTIC_COMMANDS.has(e))return!0;const n=t.toLowerCase();return!!/\bjs\b/.test(n)||!!/\btell\b/.test(n)||!!/\*[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 r=this.analyzer.analyze(t,this.language),i=performance.now()-e;this.debugEnabled&&console.log("[SemanticIntegration] Analysis result:",{input:t,language:this.language,confidence:r.confidence,command:r.command?.name,threshold:this.confidenceThreshold});const s=r.confidence>=this.confidenceThreshold&&!!r.command,o=!s&&r.confidence>0;if(mt){const e={};if(r.command?.roles)for(const[t,n]of r.command.roles)e[t]=n.value;const a={input:t.substring(0,100),language:this.language,confidence:r.confidence,threshold:this.confidenceThreshold,semanticSuccess:s,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:i};!function(t){if(!mt)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),i=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?"...":""}`,i,"color: #888"),console.log(`Confidence: ${n}% (threshold: ${r}%)`),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(),yt){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:!0});yt.dispatchEvent(e)}}(a),n=a,gt.totalParses++,n.semanticSuccess?gt.semanticSuccesses++:n.fallbackTriggered?gt.semanticFallbacks++:gt.traditionalParses++,gt.confidenceHistory.push(n.confidence),gt.confidenceHistory.length>100&>.confidenceHistory.shift(),gt.averageConfidence=gt.confidenceHistory.reduce((t,e)=>t+e,0)/gt.confidenceHistory.length}return s?{success:!0,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:!1,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:!1,confidence:0,errors:[t instanceof Error?t.message:t+""]}}var n}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 n=this.analyzer.buildCommandNode?.(e);if(!n)throw Error(`Semantic analyzer cannot build an AST node for '${e.name}' (no buildCommandNode wired \u2014 see createSemanticAdapter's buildAST dep)`);return n}buildRepeatCommandNode(t){const e=[],n={},r=t.roles.get("loopType");r&&e.push({type:"identifier",name:r.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("patient");"for"==(r?r.value+"":"")&&i&&e.push({type:"identifier",name:"expression"===i.type&&i.raw||i.value+"",start:0,end:0,line:1,column:0});const s=t.roles.get("event");s&&e.push({type:"string",value:s.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&&(n.condition=this.semanticValueToExpression(c)),{type:"command",name:"repeat",args:e,modifiers:Object.keys(n).length>0?n:void 0,isBlocking:!1,start:0,end:0,line:1,column:0}}buildSetCommandNode(t){const e=[],n=t.roles.get("destination");if(n)if("property-path"===n.type){const t=n;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(n));e.push({type:"identifier",name:"to",start:0,end:0,line:1,column:0});const r=t.roles.get("patient");return r&&e.push(this.semanticValueToExpression(r)),{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=[],n=t.roles.get("condition");return n&&e.push(this.semanticValueToExpression(n)),{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 n=()=>{for(;t.length>e&&/\s/.test(t[e]);)e++},r=()=>{n();const r=e;for(;t.length>e&&/[a-zA-Z0-9_$]/.test(t[e]);)e++;return t.slice(r,e)},i=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(s()),n();","===t[e];)e++,n(),r.push(s()),n();return")"===t[e]&&e++,r},s=()=>{n();const s=r();if(!s)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:s,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const s=t[e];if("."===s){e++;const t=r();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("("!==s)break;o={type:"callExpression",callee:o,arguments:i(),start:0,end:0,line:1,column:0}}}return o};return s()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}vt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const bt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),wt=new Set([")","]","}",","]);function Et(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const i=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function xt(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const i=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:i,start:e.start,end:i.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function kt(t,e){return{prefix:{bp:t,handler:e??((e,n)=>{const r=n.parseExpr(t);return{type:"unaryExpression",operator:e.value,operand:r,argument:r,prefix:!0,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function St(t){return(e,n,r)=>{const i=r.advance();if(!i||!i.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let s=!0;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=!1),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:s,negated:t,start:e.start,end:i.end}}}const At=function(...t){const e=new Map;for(const n of t)for(const[t,r]of n){const n=e.get(t);e.set(t,n?{prefix:r.prefix??n.prefix,infix:r.infix??n.infix}:{...r})}return e}(new Map([["or",Et(10)],["||",Et(10)],["and",Et(20)],["&&",Et(20)],["==",Et(30)],["!=",Et(30)],["<",Et(30)],[">",Et(30)],["<=",Et(30)],[">=",Et(30)],["is",Et(30)],["matches",Et(30)],["contains",Et(30)],["starts with",Et(30)],["ends with",Et(30)],["does not start with",Et(30)],["does not end with",Et(30)],["is between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!1,start:t.start,end:s.end}})],["is not between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!0,start:t.start,end:s.end}})],["am between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!1,start:t.start,end:s.end}})],["am not between",Et(30,(t,e,n)=>{const r=n.parseExpr(31),i=n.peek();if(!i||"and"!==i.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(i?.value??"<end>"));n.advance();const s=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:s,negated:!0,start:t.start,end:s.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=!0,t)}}],["where",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:t,right:r,start:t.start,end:r.end}})],["sorted by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);let i="asc";const s=n.peek();if(s&&"string"==typeof s.value){const t=s.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),i="asc"):"desc"!==t&&"descending"!==t||(n.advance(),i="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:i,start:t.start,end:r.end}})],["mapped to",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:t,right:r,start:t.start,end:r.end}})],["split by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:t,right:r,start:t.start,end:r.end}})],["joined by",Et(28,(t,e,n)=>{const r=n.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:t,right:r,start:t.start,end:r.end}})],["+",{...Et(40),...kt(80)}],["-",{...Et(40),...kt(80)}],["*",Et(50)],["/",Et(50)],["%",Et(50)],["mod",Et(50)],["^",xt(60)],["**",xt(60)],["as",Et(70,(t,e,n)=>{const r=()=>{const t=n.peek();!t||"a"!==t.value&&"an"!==t.value||n.advance();const e=n.parseExpr(71),r=n.peek();if(r&&":"===r.value&&e&&"identifier"===e.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(e.name=`${e.name}:${t.value}`,e.end=t.end)}return e};let i=r(),s={type:"asExpression",expression:t,targetType:i,start:t.start,end:i.end??e.end,line:t.line??e.line,column:t.column??e.column};for(;n.peek()&&"|"===n.peek().value;){n.advance();const t=r();s={type:"asExpression",expression:s,targetType:t,start:s.start,end:t.end??s.end,line:s.line,column:s.column}}return s})],["not",kt(80)],["!",kt(80)],["no",kt(27)]]),new Map([["===",Et(30)],["!==",Et(30)],["is not",Et(30)],["am",Et(30)],["is in",Et(30)],["is not in",Et(30)],["precedes",Et(30)],["does not precede",Et(30)],["follows",Et(30)],["does not follow",Et(30)],["is a",Et(30,St(!1))],["is an",Et(30,St(!1))],["is not a",Et(30,St(!0))],["is not an",Et(30,St(!0))],["has",Et(30)],["have",Et(30)],["match",Et(30)],["include",Et(30)],["includes",Et(30)],["equals",Et(30)],["does not contain",Et(30)],["does not include",Et(30)],["am in",Et(30)],["am not in",Et(30)],["is really",Et(30)],["is not really",Et(30)],["is equal",Et(30)],["is not equal",Et(30)],["contain",Et(30)],["do not contain",Et(30)],["does not contains",Et(30)],["do not match",Et(30)],["does not match",Et(30)],["is equal to",Et(30)],["is not equal to",Et(30)],["is really equal to",Et(30)],["is not really equal to",Et(30)],["really equals",Et(30)],["is greater than",Et(30)],["is less than",Et(30)],["is greater than or equal to",Et(30)],["is less than or equal to",Et(30)],["in",Et(30)],["of",xt(30)],["really",Et(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",kt(80)]]),new Map([["=",xt(5)]])),Tt=new Map,Ct=new Map,$t=new Map,Nt=new Set,Ot=new Set,Rt=new Set,jt=new Set;function Lt(t){return Tt.get(t.toLowerCase())}function Mt(t){return $t.get(t)}function It(t,e){if(0!==Ot.size)for(const n of Ot)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Pt(t,e,n){if(0!==Rt.size)for(const r of Rt)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function qt(t,e){if(0!==jt.size)for(const n of jt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function Ht(t,e,n){if(t.globals.set(e,n),0!==Nt.size)for(const r of Nt)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function Bt(t){return t.kind===q.IDENTIFIER&&E.has(t.value.toLowerCase())}function Dt(t){return t.kind===q.IDENTIFIER&&P.has(t.value.toLowerCase())}function Ft(t){return t.kind===q.IDENTIFIER&&I.has(t.value.toLowerCase())}function Ut(t){return t.kind===q.IDENTIFIER&&j.has(t.value.toLowerCase())}function Vt(t){return M.has(t.value.toLowerCase())}function _t(t){return t.kind===q.IDENTIFIER}function zt(t){return t.kind===q.SELECTOR}function Wt(t){return t.kind===q.SELECTOR&&!t.value.startsWith("<")}function Zt(t){return t.kind===q.STRING||t.kind===q.NUMBER||t.kind===q.TEMPLATE}function Jt(t){return t.kind===q.IDENTIFIER}function Kt(t){return t.kind===q.TIME}function Xt(t){return t.kind===q.SYMBOL}function Gt(t){return t.kind===q.COMMENT}function Yt(t){if(t.kind!==q.IDENTIFIER)return!1;const e=t.value.toLowerCase();return!(E.has(e)||P.has(e)||I.has(e)||j.has(e))}function Qt(t){return t.kind===q.STRING}function te(t){return t.kind===q.NUMBER}function ee(t){if(t.kind===q.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return!1}function ne(t){return t.kind===q.TEMPLATE}function re(t){return t.kind===q.SELECTOR&&t.value.startsWith("<")}function ie(t){return t.kind===q.SELECTOR&&t.value.startsWith("#")}function se(t){return t.kind===q.SELECTOR&&t.value.startsWith(".")}function oe(t){return t.kind===q.SELECTOR&&!t.value.startsWith("#")&&!t.value.startsWith(".")}function ae(t){if(t.kind!==q.OPERATOR)return!1;const e=t.value.toLowerCase();return!L.has(e)&&!M.has(e)}function ce(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function le(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ue(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function fe(t,e,n,r){return{type:"binaryExpression",operator:t,left:e,right:n,start:r.start,end:r.end,line:r.line,column:r.column}}function he(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function de(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function pe(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function me(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ye(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function ge(t,e,n){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:e,severity:"error",code:"parse-error",line:t.line,column:t.column,...n&&{source:n}}],start:t.start,end:t.end,line:t.line,column:t.column}}const ve=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"prepend",keywords:["to"],syntax:"prepend <value> [to <target>]"},{command:"make",keywords:["a","an","from","called"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},{command:"throw",keywords:[],syntax:"throw <error>"}];function be(t,e){return!!t&&e.some(e=>t.value===e||t.value.toLowerCase()===e)}const we=[t,r,e,n];function Ee(t,e=[]){if(t.isAtEnd())return!0;for(const e of we)if(t.check(e))return!0;for(const n of e)if(t.check(n))return!0;return!!t.checkIsCommand()}function xe(t,e=[]){if(!Ee(t,e))return t.parseExpression()}function ke(t,e,n){return!!t.check(e)&&(t.advance(),n.push(t.createIdentifier(e)),!0)}function Se(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function Ae(t,e){return!!t.check(e)&&(t.advance(),!0)}function Te(t){const e=t.savePosition();let n;if(t.checkIdentifierLike()){const r=t.peek().value;t.advance(),t.check(":")?(t.advance(),n=r):t.restorePosition(e)}const r=t.parseExpression();return void 0!==n?{name:n,value:r}:{value:r}}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 $e(t,e){const n=[];let r="";const i=t.peek().start||0,s=t.peek().line||1,o=t.peek().column||1;if(t.checkIdentifierLike()){for(r=t.advance().value;t.check(":")&&!t.isAtEnd();)t.advance(),r+=":",t.checkIdentifierLike()&&(r+=t.advance().value);if(t.check("(")){t.advance();const e=[];for(;!t.isAtEnd()&&!t.check(")");){const{name:n,value:r}=Te(t);if(e.push(void 0!==n?{type:"objectLiteral",properties:[{key:{type:"identifier",name:n},value:r}],start:r.start,end:r.end,line:r.line,column:r.column}:r),t.check(","))t.advance();else if(!t.check(")"))break}t.check(")")&&t.advance(),n.push({type:"functionCall",name:r,args:e,start:i,end:t.getPosition().end,line:s,column:o})}else n.push({type:"string",value:r,start:i,end:t.getPosition().end,line:s,column:o})}const a=[...n];for(;!Ee(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}const e=t.savePosition(),n=t.parsePrimary();n&&a.push(n),t.savePosition()===e&&t.advance()}return Ce.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Ne(t,e){const n=[];if(t.check(b)){const e=t.advance();if(n.push({type:"identifier",name:b,start:e.start,end:e.end,line:e.line,column:e.column}),t.check(y)){const e=t.advance();n.push({type:"identifier",name:y,start:e.start,end:e.end,line:e.line,column:e.column})}}return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Oe(i,s){const o=[],a=()=>i.check(n)||s&&i.check(e);for(;!i.isAtEnd()&&!a();){if(Gt(i.peek())){i.advance();continue}if(!i.checkIsCommand()&&!i.isCommand(i.peek().value))break;i.advance();const e=i.parseCommand();e&&o.push(e),(i.check(t)||i.check(r)||i.check(","))&&i.advance()}return o}const Re=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function je(t,e,n){return null!==e&&!Re.has(e.value?.toLowerCase?.()??"")&&(t.checkIsCommand()||t.isCommand(n.value?.toLowerCase()))}function Le(r,i){const s=[];let o=!1;const a=r.savePosition();let c=null;for(let e=0;500>e&&!r.isAtEnd();e++){const e=r.peek();if(e.value===t){o=!0;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;if(void 0!==e.line&&e.line!==i.line&&je(r,c,e))break;Gt(e)||(c=e),r.advance()}r.restorePosition(a);let l=!1;if(!o){const t=r.savePosition(),s=i.line,o=100;let a=!1,c=null;for(;!r.isAtEnd()&&o>r.current-t;){const t=r.peek(),i=t.value?.toLowerCase();if(a&&void 0!==t.line&&t.line!==s)break;if(i===g||"def"===i||i===m)break;if(i===e||i===n){t.line===s&&(l=!0);break}if(je(r,c,t)){if(void 0!==t.line&&t.line!==s){l=!0;break}a=!0}Gt(t)||(c=t),r.advance()}r.restorePosition(t)}const u=o||l;let f;if(u)f=r.parseExpression();else{const e=[],n=20;let s=0,o=!0;for(;!r.isAtEnd()&&!r.check(t)&&(o||!r.checkIsCommand()&&!r.isCommand(r.peek().value))&&n>s;){o=!1;const t=r.savePosition();e.push(r.parseLogicalAnd()),r.savePosition()===t&&r.advance(),s++}if(0===e.length)throw Error("Expected condition after if/unless");f=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:i.line,column:i.column}}if(s.push(f),u){Ae(r,t);const o=Oe(r,!0);if(0===o.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");s.push(he(o,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}));let a=!1;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Le(r,t);s.push(he([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=!0}else{const t=Oe(r,!1);s.push(he(t,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}a||r.consume(n,"Expected 'end' after if block")}else{if(!r.checkIsCommand()&&!r.isCommand(r.peek().value))throw Error("Expected command after if condition in single-line form");{r.advance();const t=r.parseCommand();s.push(he([t],{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}}return Ce.from(i).withArgs(...s).endingAt(r.getPosition()).build()}function Me(t,e){const n=[],r={};if(t.checkAnySelector()||t.checkContextVar()||t.match("<")){const e=t.parsePrimary();if(n.push(e),t.match("*")){if(t.checkIdentifierLike()){const e=t.advance();n.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();n.push(e)}}else if(t.checkIdentifierLike()){const e=t.parsePrimary();n.push(e)}if(t.match("and")&&t.match("set")&&t.checkIdentifierLike()){const e=t.advance();r.set={type:"identifier",name:e.value,start:e.start,end:e.end,line:e.line,column:e.column}}const i=Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Ie=new Set(["my","its","your"]);function Pe(t){const e={};if(Ae(t,i)){const n=t.parseExpression();return n&&(e.for=n),e}if(!t.check(o))return e;t.advance();const n=t.peek();if(!n||!_t(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&_t(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},Ae(t,h)){const n=xe(t);n&&(e.from=n)}return e}function qe(t,e){const n=[],r=xe(t,[h]);r&&n.push(r),ke(t,h,n);const i=xe(t);return i&&n.push(i),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function He(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const s=xe(t,[r]);if(s&&"binaryExpression"===s.type&&"and"===s.operator)s.left&&n.push(s.left),n.push(t.createIdentifier("and")),s.right&&n.push(s.right);else{s&&n.push(s),ke(t,r,n);const e=xe(t,[h,m,i]);e&&n.push(e)}if(Se(t,[h,m],n)){const e=xe(t);e&&n.push(e)}return Ce.fromIdentifier(e).withArgs(...n).withModifiers(Pe(t)).endingAt(t.getPosition()).build()}const s=xe(t,[h,m]);if(s&&n.push(s),Se(t,[h,m],n)){const e=xe(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),Ce.fromIdentifier(e).withArgs(...n).withModifiers(Pe(t)).endingAt(t.getPosition()).build()}function Be(t,e){if(!t.check("using"))return!1;if(t.advance(),!t.match("view"))throw Error("expected 'view transition' after 'using'");if(!t.match("transition"))throw Error("expected 'transition' after 'using view'");return e.push(t.createIdentifier("using")),e.push(t.createIdentifier("view")),e.push(t.createIdentifier("transition")),!0}function De(t,e){const r=t.parseExpression();if(!r)return t.addError("Put command requires content expression"),null;const i=t.peek();if(!i||!A.includes(i.value))return t.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${i?.value}`),null;let s=t.advance().value;const o=s.toLowerCase();"at start of"===o||"at the start of"===o?s=k:"at end of"===o||"at the end of"===o?s=S:"at"===s&&(t.check(w)||t.check(b)?(Ae(t,b),t.check(w)&&(t.advance(),t.check(p)&&(t.advance(),s=k))):t.check(n)&&(t.advance(),t.check(p)&&(t.advance(),s=S)));const a=t.parseExpression();return a?Ce.fromIdentifier(e).withArgs(r,t.createIdentifier(s),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Fe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Ue(i,s){const o=i.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:"element",start:e.start-1,end:e.end}}(i)??function(t){if(!t.check(v)&&!t.check("local"))return null;const e=t.advance(),n=t.advance();return{type:"identifier",name:n.value,scope:e.value,start:e.start,end:n.end}}(i)??function(t){if(!t.check(b))return null;const e=t.savePosition();t.advance();const n=t.parseExpression();if(!n)return t.restorePosition(e),null;if("binaryExpression"===n.type&&n.operator===p){const t=n.left,e=n.right;return ye(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(f)?n:(t.restorePosition(e),null)}(i),a||(a=i.parseExpression())}catch{i.restorePosition(o),a=null}if(!a){const s=function(i){if(i.match(":")){const t=i.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const s=[];for(;!(i.isAtEnd()||i.check(f)||i.check(t)||i.check(r)||i.check(e)||i.check(n));)s.push(i.parsePrimary());if(0===s.length)return{expression:null,tokens:[]};if(s.length>=4){const t=(t,e)=>t[e];if(t(s[0],"value")===b&&t(s[2],"value")===p){const e=s[1],n=s[3];return{expression:ye(ue(t(e,"value")||t(e,"name")||"",{start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:t(n,"value")||t(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:s[0].start??0,end:n.end??0,line:s[0].line??1,column:s[0].column??1}),tokens:[]}}}return 1===s.length?{expression:s[0],tokens:[]}:{expression:null,tokens:s}}(i);a=s.expression,c=s.tokens}if(!i.check(f)){const t=i.isAtEnd()?"end of input":i.peek().value;throw Error("Expected 'to' in set command, found: "+t)}i.advance();const l=i.parseExpression()??i.parsePrimary();let u;var h;i.check(m)&&(h=i.peekAt(1))&&("selector"===h.kind||h.value.startsWith("<")||Ve.has(h.value))&&(i.advance(),u=xe(i));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(i.createIdentifier(f)),l&&d.push(l);const y=Ce.fromIdentifier(s).withArgs(...d);return u&&y.withModifier("on",u),y.endingAt(i.getPosition()).build()}const Ve=new Set(["me","my","it","its","you","your","yourself"]),_e=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function ze(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function We(t,e){const n=[];for(;!Ee(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ze(t){const e=t.peek();if("/"===e.value)return!0;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return!1}const Je=new Set(["{",")"]);function Ke(t){const e=t.savePosition(),n=t.peek();let r="",i=null;for(;!t.isAtEnd();){const e=t.peek();if(i&&e.start!==i.end)break;if("$"===e.value&&"{"===t.peekAt(1)?.value){t.advance();let n=t.advance(),s=1;for(;!t.isAtEnd()&&s>0;)n=t.advance(),"{"===n.value?s++:"}"===n.value&&s--;r+=t.getInputSlice(e.start,n.end),i=n;continue}if(Je.has(e.value))break;i=t.advance(),r+=i.value}if(!r||"/"===r)return t.restorePosition(e),null;const s={start:n.start,end:i?i.end:n.end,line:n.line,column:n.column};return r.includes("${")?{type:"templateLiteral",value:r,...s}:{type:"literal",value:r,raw:r,...s}}function Xe(t){if(t.check("{"))return!1;if(!t.checkIdentifierLike())return!1;const e=t.peekAt(1);return null!==e&&":"===e.value}function Ge(t){const e=[],n=t.getPosition();do{if(!t.checkIdentifierLike())break;const n=t.advance(),r={type:"identifier",name:n.value,start:n.start,end:n.end,line:n.line,column:n.column};t.consume(":","Expected ':' after property name in fetch named arguments");const i=t.parsePrimary();i&&e.push({key:r,value:i})}while(t.match(",")&&!t.isAtEnd());const r=t.getPosition();return{type:"objectLiteral",properties:e,start:n.start,end:r.end,line:n.line,column:n.column}}const Ye=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Qe{constructor(t,e,n){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 vt({analyzer:e.semanticAnalyzer,language:e.language,confidenceThreshold:e.semanticConfidenceThreshold??.5})),this.originalInput=n||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.recovered=!0),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}}const t=this.peek(),e=t&&Lt(t.value)?t.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==e){const t=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const t=this.peekAt(1);if(null!==t&&("init"===t.value||"on"===t.value||"def"===t.value||void 0!==Lt(t.value))){this.advance();continue}}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")){const e=this.peek(),n=e?Lt(e.value):void 0;if(n){const e=this.advance(),r=n(this.getContext(),e);r&&t.push(r);continue}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("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];dt(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){dt(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(dt("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,dt(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),dt(`\u2705 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("\u26a0\ufe0f 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("\u2705 PARSER: No more event handlers, at end of input");break}}return dt(`\u2705 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 n=this.parseExpression();if(this.error)return{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const t=this.peek();return n&&["number","string","identifier"].includes(t.kind)?this.addError(`Unexpected token: ${t.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+t.value),{success:!1,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:n,tokens:this.tokens,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}`,n=this.prattCache.get(e);if(n)return this.current=n.endPos,n.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const r=this.peek(),i=Qe.PRATT_TABLE.get(r.value);let s;if(i?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();s=i.prefix.handler(t,this.makePrattContext())}else s=this.parseCall();for(;!this.isAtEnd();){const e=this.peek();if(60>=t){const t=this.tryParseStringPostfix(s,e);if(t){s=t;continue}}const n=Qe.PRATT_TABLE.get(e.value);if(!n?.infix){if(bt.has(e.value)||wt.has(e.value))break;break}const[r]=n.infix.bp;if(t>r)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(t){dt("arrow body discarded after error:",t instanceof Error?t.message:t+"")}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}`),s}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}`),s}const i=this.advance();if(this.isAtEnd()&&!Qe.POSTFIX_UNARY_OPERATORS.has(i.value))return this.addError(`Expected expression after '${i.value}' operator`),s;s=n.infix.handler(s,i,this.makePrattContext())}return this.prattCache.set(e,{node:s,endPos:this.current}),s}tryParseStringPostfix(t,e){const n=e.value;let r=null;if(Ye.has(n)?r=n:"%"===n&&(this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(r="%")),null==r)return null;const i=this.advance();return{type:"stringPostfix",expression:t,unit:r,start:t.start,end:i.end,line:t.line,column:t.column}}canStartOperand(t){if(!t)return!1;const e=t.value;return!bt.has(e)&&!wt.has(e)&&("number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(e))}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||bt.has(e.value)||wt.has(e.value)},atEnd:()=>t.current>=t.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let t=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==t.type){if("literal"===t.type&&(this.checkNumber()||this.checkIdentifier())){const e=this.peek();return this.addError(`Missing operator between '${t.raw||t.value}' and '${e.value}'`),t}break}if(this.isCommand(t.name))if(this.isCompoundCommand(t.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const e=this.createCommandFromIdentifier(t);e&&(t=e)}}else if("wait"===t.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const e=this.createCommandFromIdentifier(t);e&&(t=e)}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}else{if(!this.checkSelector())break;{const e=this.parseCall();t=this.createBinaryExpression(" ",t,e)}}}return t}isCommand(t){return this.keywordResolver?this.keywordResolver.isCommand(t):C(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):N(t)}createCommandFromIdentifier(t){const e=[],n=this.resolveKeyword(t.name.toLowerCase());if(this.isCompoundCommand(n))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)}parseCompoundCommand(s){return function(s,o){switch(o.name.toLowerCase()){case"put":return De(s,o);case"trigger":case"send":return $e(s,o);case"remove":return qe(s,o);case"take":return function(t,e){const n=[],r={},s=xe(t,[h,i]);if(s&&n.push(s),t.check(h)){ke(t,h,n);const e=xe(t,[i]);e&&n.push(e)}if(Ae(t,i)){const e=xe(t);e&&(r.for=e)}return Ce.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(s,o);case"toggle":return He(s,o);case"set":return Ue(s,o);case"halt":return Ne(s,o);case"measure":return Me(s,o);case"js":return function(t,e){const r=[];if(t.match("(")){for(;!t.check(")")&&!t.isAtEnd();)t.checkIdentifierLike()&&r.push(t.advance().value),t.match(",");t.consume(")","Expected ) after js parameters")}const i=t.peek().start,s=function(t,e){const n=t.getInputSlice(e);if(!n)return e;let r=0;for(;n.length>r;){const t=n[r];if("'"!==t&&"\u2019"!==t&&"\u2018"!==t)if('"'!==t)if("`"!==t)if("/"===t&&n.length>r+1&&"/"===n[r+1])for(r+=2;n.length>r&&"\n"!==n[r];)r++;else if("/"===t&&n.length>r+1&&"*"===n[r+1]){for(r+=2;n.length>r&&("*"!==n[r]||r+1>=n.length||"/"!==n[r+1]);)r++;r+=2}else{if(!("e"!==t&&"E"!==t||r+3>n.length||"end"!==n.slice(r,r+3).toLowerCase()||0!==r&&/[a-zA-Z0-9_]/.test(n[r-1])||n.length>r+3&&/[a-zA-Z0-9_]/.test(n[r+3])))return e+r;r++}else{for(r++;n.length>r&&"`"!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&'"'!==n[r];)"\\"===n[r]&&r++,r++;r++}else{for(r++;n.length>r&&n[r]!==t;)"\\"===n[r]&&r++,r++;r++}}return e+n.length}(t,i);for(;!t.isAtEnd()&&!t.check(n)&&t.peek().start<s;)t.advance();t.consume(n,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(i,s).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:r.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,o);case"go":return function(t,e){const n=[];for(;!Ee(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(_e.has(r)){t.advance(),n.push(ze(r,e));continue}if(Ze(t)){const r=Ke(t);if(r){n.push(r);continue}t.advance(),n.push(ze(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(ze(e.value,e));continue}if("number"===e.kind){t.advance();const r=t.peek();if(t.isAtEnd()||"px"!==r.value||r.start!==e.end)n.push({type:"literal",value:Number(e.value),raw:e.value,start:e.start,end:e.end,line:e.line,column:e.column});else{const r=t.advance();n.push(ze(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o);case"tell":return function(i,s){const o=i.parseExpression();if(!o)throw Error("tell command requires a target expression");i.check(f)&&i.advance();const a=[];for(;!i.isAtEnd();){if(i.checkIsCommand()){try{i.advance();const t=i.parseCommand();if(!t)break;a.push(t)}catch{break}if(i.match(r)||i.match(t))continue;if(i.check(e))break;if(i.check(n)){i.advance();break}if(i.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return Ce.fromIdentifier(s).withArgs(o,...a).endingAt(i.getPosition()).build()}(s,o);case"pick":return function(t,e){const n=Ce.fromIdentifier(e);Ae(t,b);const r=t.peek().value,i=t=>({type:"literal",value:t,start:e.start,end:e.end}),s=()=>{if(!t.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return t.parseExpression()};if("first"===r){t.advance();const e=t.parsePrimary(),r=s();return n.withArgs(r).withModifier("variant",i("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=s();return n.withArgs(r).withModifier("variant",i("last")).withModifier("count",e).endingAt(t.getPosition()).build()}if("random"===r){let e;t.advance(),t.check("of")||t.check("from")||(e=t.parsePrimary());const r=s(),o=n.withArgs(r).withModifier("variant",i("random"));return e&&o.withModifier("count",e),o.endingAt(t.getPosition()).build()}if("item"===r||"items"===r||"character"===r||"characters"===r){let e,r;t.advance(),t.match("at","from"),e=t.match("start")?i("start"):t.parsePrimary();let o=!1;(t.match("to")||t.match(".."))&&(t.match("end")?o=!0:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=s(),l=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return o?l.withModifier("rangeEnd",i("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let o;t.matchOperator("|")&&(o=t.advance().value);const a=s(),c=n.withArgs(a).withModifier("variant",i("match"===r?"match":"matches")).withModifier("regex",e);return o&&c.withModifier("flags",i(o)),c.endingAt(t.getPosition()).build()}return We(t,e)}(s,o);case"start":return function(t,e){if(!t.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!t.match("transition"))throw Error("start view: expected 'transition'");const n={};if(t.match("using")){const e=t.parsePrimary();n.transitionName=e}const r=t.parseCommandListUntilEnd("start view transition");return Ce.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(s,o);case"swap":case"morph":return function(t,e){const n=[];let r=null;if(!t.isAtEnd()){const e=t.peek();if(e&&e.value){const i=e.value.toLowerCase();Fe.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),n.push(t.createIdentifier("of")));const i=t.parseExpression();if(i&&n.push(i),!t.isAtEnd()&&t.check(d)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return Be(t,n),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o);case"process":return function(t,e){if(!t.check("partials"))return null;const n=[];if(ke(t,"partials",n),ke(t,u,n)){const e=xe(t,["using"]);e&&n.push(e)}return Be(t,n),Ce.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o)??We(s,o);default:return We(s,o)}}(this.getContext(),s)}parsePutCommand(t){return De(this.getContext(),t)}parseSetCommand(t){return Ue(this.getContext(),t)}parseHaltCommand(t){return Ne(this.getContext(),t)}parseMeasureCommand(t){return Me(this.getContext(),t)}parseTriggerCommand(t){return $e(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(dt("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){dt("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=!1;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){dt(r?"\u2705 Found COMMAND token:":"\u2705 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("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(dt("\u2705 Parsed command:",r.name),e.push(r),t=!0)}catch(t){dt("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&dt("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){dt("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(dt("\ud83d\udccd After parsing command, current token:",this.peek().value);!(this.isAtEnd()||n()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)dt("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))dt("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){dt("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}dt("\u2705 Next token is a command, continuing without separator")}}let r="end";for(const e of t)if(this.check(e)){r=e;break}return this.check("end")||t.some(t=>this.check(t))||(r=""),dt("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(dt('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw dt('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return dt('\u2705 Found "end", consuming it'),this.advance(),e}parseCommandListUntilEndOrElse(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else"]),n="else"===e;if(!n){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:t,hasElse:n}}parseRepeatBody(){const{commands:t,terminator:e}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===e)this.advance();else if(""===e)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:t,terminator:e}}parseRepeatCommand(t){return function(t,e){const n=[];let r="forever",f=null,p=null,m=null,g=null,v=null,w=null;if(t.check(i)){t.advance(),r=i;const e=t.peek();_t(e)&&(v=e.value,t.advance()),t.check(u)&&(t.advance(),g=t.parseExpression())}else if(t.check(u))t.advance(),r=i,v="it",g=t.parseExpression();else if(t.check(s))t.advance(),r=s,m=t.parseExpression();else if(t.check(o))if(t.advance(),r=o,t.check(y)){t.advance(),r="until-event";const e=t.peek();if(dt("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!_t(e)&&!Ft(e))throw Error('Expected event name after "event"');if(f=e.value,t.advance(),dt("\u2705 Got event name:",f,"Next token:",t.peek().value),dt('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(h)){dt('\u2705 Found "from", advancing...'),t.advance(),dt('\ud83d\udccd After consuming "from", current token:',t.peek().value),Ae(t,b)&&dt('\u2705 Found "the", advancing...');const e=t.peek();dt("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),dt("\u2705 After parsePrimary, eventTarget:",p)}else dt('\u274c No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),r=a):(w=t.parseExpression(),t.check(c)&&(t.advance(),r=c));let E,x=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),x=l)}else if(t.check(l)){t.advance();const e=t.peek();_t(e)?(x=e.value,t.advance()):x=l}let k=null,S=!1;if(r===a){const e=t.parseRepeatBody();if(E=e.commands,"else"===e.terminator)t.advance(),k=t.parseCommandListUntilEnd();else if("until"===e.terminator||"while"===e.terminator){if(S=!0,r=e.terminator,t.advance(),m=t.parseExpression(),!t.check("end"))throw Error('Expected "end" to close repeat block');t.advance()}}else{const e=t.parseCommandListUntilEndOrElse();E=e.commands,e.hasElse&&(t.advance(),k=t.parseCommandListUntilEnd())}n.push({type:"identifier",name:r,start:e.start,end:e.end,line:e.line,column:e.column});const A={start:e.start,end:e.end,line:e.line,column:e.column};v&&n.push(de(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(de(f,A)),p&&n.push(p),x&&n.push(de(x,A)),n.push(he(E,{...A,end:A.end||0})),null!==k&&n.push(he(k,{...A,end:A.end||0}));const T=Ce.from(e).withArgs(...n);return S&&T.withModifier("bottomTested",{type:"literal",value:!0,...A}),T.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,i=null;t.check("each")&&t.advance();const s=t.peek();if(!_t(s))throw Error('Expected variable name after "for"');if(r=s.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),i=t.parseExpression(),!i)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();_t(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd("for");n.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 n.push(de(r,c)),n.push(i),o&&n.push(de(o,c)),n.push(he(a,{...c,end:c.end||0})),Ce.from({...e,value:"repeat"}).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseWaitCommand(t){return function(t,e){const n=[];if(t.checkTimeExpression()||t.checkLiteral()||t.checkContextVar()||t.check("(")||t.checkIdentifierLike()&&!t.check("for")&&!Ee(t)){const r=t.parseExpression();return n.push(r),Ce.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{if(t.checkTimeExpression()||t.checkLiteral()||t.check("(")){if(r.push({kind:"duration",expr:t.parseExpression()}),t.check("or")){t.advance();continue}break}const e=t.peek();if(!_t(e))throw Error('Expected event name or duration after "for"');const n=e.value;t.advance();const i=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!_t(e))break;i.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({kind:"event",name:n,params:i}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let i=null;t.check(h)&&(t.advance(),Ae(t,b),i=t.parsePrimary());const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(me(r.map(t=>pe("duration"===t.kind?[{key:ue("duration",s),value:t.expr}]:[{key:ue("name",s),value:le(t.name,`"${t.name}"`,s)},{key:ue("args",s),value:me(t.params.map(t=>le(t,`"${t}"`,s)),s)}],s)),s)),i&&n.push(i)}return Ce.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}(this.getContext(),t)}parseInstallCommand(t){return function(t,e){const n=[];if(!t.checkIdentifierLike())throw Error('Expected behavior name after "install"');const r=t.advance().value,i=t.previous();if(n.push(ue(r,{start:i.start,end:i.end,line:i.line,column:i.column})),t.check("(")){t.advance();const r=[];for(;!t.isAtEnd()&&!t.check(")");)if(r.push(Te(t)),t.check(","))t.advance();else if(!t.check(")"))break;if(!t.check(")"))throw Error('Expected ")" after behavior parameters');if(t.advance(),r.length>0){const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(pe(r.map(t=>({key:t.name?ue(t.name,i):le("_positional","_positional",i),value:t.value})),i))}}return Ce.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let i=null,s=null;const o=t.peek();if(t.checkAnySelector()||t.checkContextVar()||t.check("<")||_t(o)&&Ie.has(o.value)){const e=t.parsePrimary();("possessiveExpression"===e.type||"memberExpression"===e.type&&!e.computed)&&e.object&&e.property?.name?(s=e.object,i={type:"string",value:e.property.name,start:o.start||0,end:t.getPosition().end,line:o.line,column:o.column}):(s=e,t.check("'s")&&t.advance())}const a=t.peek();if(!i&&(_t(a)||"*"===a.value)){let e="";t.check("*")&&(e="*",t.advance());const n=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);n&&(e+=n,i={type:"string",value:e,start:a.start||0,end:t.getPosition().end,line:a.line,column:a.column})}if(!i)throw Error("Transition command requires a CSS property");if(s&&n.push(s),n.push(i),!t.check(f))throw Error('Expected "to" keyword after property in transition command');t.advance();const c=t.parsePrimary();if(r.to=c,t.check("over")){t.advance();const e=t.parsePrimary();r.over=e}if(t.check(d)){t.advance();const e=t.parsePrimary();r.with=e}return Ce.from(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseAddCommand(t){return function(t,e){const n=[];if(t.match("{"))n.push(t.parseCSSObjectLiteral());else{const e=xe(t,[f]);e&&n.push(e)}if(t.check(f)){t.advance();const e=xe(t);e&&n.push(e)}return Ce.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Le(this.getContext(),t)}parseRemoveCommand(t){return qe(this.getContext(),t)}parseToggleCommand(t){return He(this.getContext(),t)}parseRegularCommand(t){return We(this.getContext(),t)}parseCall(){let t=this.parsePrimary();for(;;)if(this.match("("))t=this.finishCall(t);else if(this.match(".")){const e=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),!1);n.optional=!0,t=n}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):Xt(this.peek())&&this.peek().value.startsWith("@")?e=this.advance().value:this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")?(this.advance(),e=this.advance().value,this.consume("]","Expected ']' after attribute reference")):e=this.consumeIdentifierLike("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()&&_t(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),n=this.processEscapeSequences(e);return this.createLiteral(n,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,e=t.slice(1,-2).trim(),n=this.createSelector(e);return n.fromQuery=!0,n.raw=t,n}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:"element",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(Yt)||this.matchPredicate(Dt)||this.matchPredicate(Ut)||this.matchPredicate(Bt)||this.matchPredicate(Ft))){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,n=this.createSelector("."+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}if(this.check("#")){const e=this.current;if(this.advance(),this.checkIdentifier()){const e=this.advance().value,n=this.createSelector("#"+e);return this.createCallExpression(this.createIdentifier(t.value),[n])}this.current=e}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(t.value):this.parseNavigationFunction(t.value)}const e=this.check(".")||this.check("?.");return"my"!==t.value||e?"its"!==t.value||e?"your"!==t.value||e?"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("\\"===this.peek().value)return this.parseBlockLiteral();if(Xt(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()}parseBlockLiteral(){const t=this.peek().start;this.advance();const e=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}e.push(this.advance().value),this.match(",")}return this.check("-")&&">"===this.tokens[this.current+1]?.value?(this.advance(),this.advance(),{type:"blockLiteral",parameters:e,body:this.parseExpression(),start:t,end:this.previous().end,line:this.previous().line,column:this.previous().column}):(this.addError("Expected '->' in block literal"),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.check("["))this.advance(),e=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,t)}else{if(!this.check("-")&&!this.checkPredicate(Yt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=!1;for(;this.check("-");)this.advance(),t+="-",n=!0;for(this.checkPredicate(Yt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=!0,this.checkPredicate(Yt)&&(t+=this.advance().value);if(""===t||"-"===t)return this.addError("Expected property name in object literal"),this.createErrorNode();e=n?this.createLiteral(t,t):this.createIdentifier(t)}}this.consume(":","Expected ':' after property name in object literal");const n=this.parseExpression();if(t.push({key:e,value:n}),!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 n;if(this.matchPredicate(Yt))n=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);n=this.createLiteral(e,t)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const r=[];let i=!1,s=0,o=-1,a=-1;for(;!this.isAtEnd()&&(0!==s||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),0>o&&"number"==typeof t.start&&(o=t.start),"number"==typeof t.end&&(a=t.end),"$"===t.value&&this.check("{")&&(i=!0),"{"===t.value&&s++,"}"===t.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),l=i?{type:"templateLiteral",value:c,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(c,c);if(e.push({key:n,value:l}),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(),n=e.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const r=[];if(!this.check(")"))do{r.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:n,start:e.start,end:e.end,line:e.line,column:e.column},arguments:r,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 n=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&n.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&n.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const r=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:i,errorHandler:s,finallyHandler:o}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==i&&{errorSymbol:i},...void 0!==s&&{errorHandler:s},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseErrorAndFinallyBlocks(){let t,e,n;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(t=this.advance().value),e=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),n=this.parseCommandBlock(["end"])),{...void 0!==t&&{errorSymbol:t},...void 0!==e&&{errorHandler:e},...void 0!==n&&{finallyHandler:n}}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let n=e.value;return this.check(":")&&(this.advance(),n=`${n}:${this.advance().value}`),n}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,n,r,i){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)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:!1,...void 0!==i.start&&{start:i.start},...void 0!==i.end&&{end:i.end},...void 0!==i.line&&{line:i.line},...void 0!==i.column&&{column:i.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(Qe.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Yt(r)&&!this.isCommand(r.value)||Ut(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!1};let i,s;this.isCommand(n)&&this.addWarning({type:"command-shadow",message:`Method '${n}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${n}Fn', 'my${n.charAt(0).toUpperCase()+n.slice(1)}')`,`Use 'call' command instead: call ${n}(...)`,"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}}),Qe.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(i=this.advance().value.toLowerCase());try{s=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(n,t,i,s,e),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(dt("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return dt("\u26a0\ufe0f Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseTemporalKeywordModifiers(t){if(!this.check("debounced")&&!this.check("throttled"))return;const e=this.advance().value.toLowerCase(),n="debounced"===e?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const i=this.advance(),s=(r=i.value).endsWith("ms")?parseInt(r,10):r.endsWith("seconds")||r.endsWith("s")?1e3*parseFloat(r):r.endsWith("minutes")?6e4*parseFloat(r):r.endsWith("hours")?36e5*parseFloat(r):r.endsWith("days")?864e5*parseFloat(r):parseInt(r,10);t[n]=s,dt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,dt(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${r}'`)}else this.addError(`Expected time expression after '${e} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${e}'`);var r}parseEventHandler(){dt("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const t=this.tokens[this.current+1],n=t?.value?.toLowerCase();n&&"of"!==n&&"in"!==n&&"from"!==n&&(this.advance(),e=!0,dt("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),dt("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),dt("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),dt("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(dt("\ud83d\udd27 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(`\ud83d\udd27 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const i=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();i.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),dt("\ud83d\udd27 parseEventHandler: Parsed event parameters: "+i.join(", "))}const s={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)s.once=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=!0,dt("\ud83d\udd27 parseEventHandler: Parsed modifier '.stop'");else if("debounce"===t||"throttle"===t){if(!this.check("("))throw Error(`Expected '(' after '.${t}'`);{this.advance();const e=this.advance(),n=parseInt(e.value,10);if(isNaN(n))throw Error(`Expected number for ${t} delay, got: ${e.value}`);"debounce"===t?(s.debounce=n,dt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,dt(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else dt(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,l;if(this.parseTemporalKeywordModifiers(s),e&&(s.once=!0),Object.keys(s).length>0&&dt("\ud83d\udd27 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(`\ud83d\udd27 parseEventHandler: Parsed 'from' target: ${a} (kind: ${t.kind})`),this.parseTemporalKeywordModifiers(s)}if(this.match("of")){const t=this.advance();c=t.value.startsWith("@")?t.value.substring(1):t.value,dt("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(dt("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),l=this.parseExpression(),dt("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const u=[];for(dt(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(dt(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){dt("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())dt("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){dt("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){dt(`\u2705 parseEventHandler: Stopping command parsing, found '${this.peek().value}'`);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 n=this.parseCommand();u.push(n);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("\u2705 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("\u26a0\ufe0f 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 n={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(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}let f,h,d;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:f,errorHandler:h,finallyHandler:d}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const p=this.getPosition(),m={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:u,...void 0!==f&&{errorSymbol:f},...void 0!==h&&{errorHandler:h},...void 0!==d&&{finallyHandler:d},...i.length>0&&{args:i},...o&&{condition:o},...a&&{target:a},...c&&{attributeName:c},...l&&{watchTarget:l},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:p.start,end:p.end,line:p.line,column:p.column};return dt(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${l?"yes":"none"}`),m}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 n=[];if(this.match("(")){if(!this.check(")"))do{const t=this.consumeIdentifierLike("Expected parameter name");n.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const r=new Set(n),i=[];let s;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Yt(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let s;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),s=e.value,this.advance())}}const{commands:o,terminator:a}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const f={type:"eventHandler",event:e,commands:o,...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:l},...void 0!==u&&{finallyHandler:u},...void 0!==s&&{target:s},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};i.push(f)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}s={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:n,eventHandlers:i,...void 0!==s?{initBlock:s}:{},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,n=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("\u26a0\ufe0f parseCommandSequence: Command parsing added non-critical error, restoring error state. Error was:",this.error.message),this.error=e)),t.push(n);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)dt("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){dt('\u2705 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(),n=this.getPosition(),r="Expected command, got: "+e.value;this.addError(r);const i=ge(n,r,e.value);if(t.push(i),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 ve.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return be(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!Ee(t,["catch","finally",...r.keywords])&&!be(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&be(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&be(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(s[e]=n),!be(t.peek(),r.keywords))break}const o=Ce.from(e).withArgs(...i).endingAt(t.getPosition());return Object.keys(s).length>0&&o.withModifiers(s),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();if(e.push(t),this.match("then","and",","))continue}}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(),n=e.value.toLowerCase();if(t.includes(n))break;if(Bt(e))break;this.advance()}}parseCommand(){const t=this.parseCommandCore();if(t&&"command"===t.type&&!t.body&&(this.check("when")||this.check("where"))){const e=this.peek().value.toLowerCase();this.advance();const n=this.parseExpression();n&&(t.modifiers={...t.modifiers??{},[e]:n})}return t}parseCommandCore(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","append","prepend","toggle","take","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell","fetch","process"].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 n={};let r=null;if(!t.isAtEnd()&&Ze(t)&&(r=Ke(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),Ce.from(e).endingAt(t.getPosition()).build();!t.isAtEnd()&&t.check("{")&&(n.with=t.parsePrimary());for(let e=0;3>e&&!t.isAtEnd();e++)if(!t.check("as")||n.as){if(!t.check("with")||n.with){if(t.check("do")&&!n.doNotThrow){const e=t.peekAt(1),r=t.peekAt(2);if("not"===e?.value&&"throw"===r?.value){const e=t.advance();t.advance();const r=t.advance();n.doNotThrow={type:"literal",value:!0,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Xe(t)?Ge(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||Ae(t,"a")||Ae(t,"an"),n.as=t.parsePrimary();const i=Ce.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&i.withModifiers(n),i.build()}(this.getContext(),t);const n=this.parseMultiWordCommand(t,e);if(n)return n;const r=e.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(t);if("for"===r)return this.parseForCommand(t);if("if"===r||"unless"===r)return this.parseIfCommand(t);if("wait"===r)return this.parseWaitCommand(t);if("install"===r)return this.parseInstallCommand(t);if("transition"===r)return this.parseTransitionCommand(t);if("add"===r)return this.parseAddCommand(t);if(this.isCompoundCommand(r))return this.parseCompoundCommand({type:"identifier",name:r,start:t.start||0,end:t.end||0,line:t.line,column:t.column})||function(t,e){return{type:"command",name:t,args:[],partial:!0,start:e.start,end:e.end,line:e.line,column:e.column}}(r,this.getPosition());const i=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let i=!1;t.check(v)&&(i=!0,t.advance());const s=t.parseExpression();if(!s)throw Error("Expected variable or expression after "+n);let o;if(t.check("by")){t.advance();const e=t.parseExpression();if(!e)throw Error(`Expected amount after 'by' in ${n} command`);o=e}else o=le(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=s;i&&"identifier"===s.type&&(a={...s,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=fe(r,s,o,c);l.coerceNumeric=!0;const u=[a,ue(f,c),l];return Ce.from(e).withName("set").withArgs(...u).withOriginalCommand(n).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(i.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 n=i[i.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const s=this.getPosition();return{type:"command",name:e,args:i,isBlocking:!1,start:s.start,end:s.end,line:s.line,column:s.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let n;this.match("else")&&(n=this.parseConditionalBranch());const r=this.getPosition();return{type:"conditionalExpression",test:t,consequent:e,alternate:n,start:r.start,end:r.end,line:r.line,column:r.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())}const n=this.createCallExpression(this.createIdentifier(t),e);if("next"===t||"previous"===t){const t=this.parseRelativePositionalModifiers();t&&(n.relativePositional=t)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let t,e,n,r=!1,i=!1;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=!0,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=!0),{from:t,within:e,inElt:n,inSearch:r,wrapping:i}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}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.parseCall(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if(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 n="*"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(this.createIdentifier(t),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Xt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),!1)}const e=this.consumeIdentifierLike(`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;O(e)&&dt(`\ud83d\udca1 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 le(t,e,this.getPosition())}createIdentifier(t){return ue(t,this.getPosition())}createBinaryExpression(t,e,n){return fe(t,e,n,this.getPosition())}createUnaryExpression(t,e,n){return function(t,e,n,r){return{type:"unaryExpression",operator:t,argument:e,prefix:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,this.getPosition())}createCallExpression(t,e){return function(t,e,n){return{type:"callExpression",callee:t,arguments:e,start:n.start,end:n.end,line:n.line,column:n.column}}(t,e,this.getPosition())}createMemberExpression(t,e,n){return function(t,e,n,r){return{type:"memberExpression",object:t,property:e,computed:n,start:r.start,end:r.end,line:r.line,column:r.column}}(t,e,n,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,n){return{type:"possessiveExpression",object:t,property:e,start:n.start,end:n.end,line:n.line,column:n.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(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return dt("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return dt(`\u2705 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(`\u2705 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!(!ae(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(Wt)}matchSelector(){return this.matchPredicate(Wt)}checkAnySelector(){return this.checkPredicate(zt)}checkLiteral(){return this.checkPredicate(Zt)}checkIdentifierLike(){return this.checkPredicate(_t)}checkIsCommand(){return this.checkPredicate(Bt)}checkCommandTerminator(){return this.checkPredicate(ce)}checkReference(){return this.checkPredicate(Jt)}checkTimeExpression(){return this.checkPredicate(Kt)}checkEvent(){return this.checkPredicate(Ft)}checkContextVar(){return this.checkPredicate(Ut)}checkComment(){return this.checkPredicate(Gt)}checkIdentifier(){return this.checkPredicate(Yt)}checkKeyword(){return this.checkPredicate(Dt)}checkString(){return this.checkPredicate(Qt)}matchString(){return this.matchPredicate(Qt)}checkNumber(){return this.checkPredicate(te)}matchNumber(){return this.matchPredicate(te)}checkBoolean(){return this.checkPredicate(ee)}matchBoolean(){return this.matchPredicate(ee)}checkTemplateLiteral(){return this.checkPredicate(ne)}matchTemplateLiteral(){return this.matchPredicate(ne)}checkQueryReference(){return this.checkPredicate(re)}matchQueryReference(){return this.matchPredicate(re)}checkIdSelector(){return this.checkPredicate(ie)}checkClassSelector(){return this.checkPredicate(se)}checkCssSelector(){return this.checkPredicate(oe)}checkBasicOperator(){return this.checkPredicate(ae)}matchBasicOperator(){return this.matchPredicate(ae)}matchTimeExpression(){return this.matchPredicate(Kt)}matchIdentifierLike(){return this.matchPredicate(_t)}matchComparisonOperator(){return this.matchPredicate(Vt)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Yt,t)}consumeIdentifierLike(t){return this.consumePredicate(_t,t)}consumeEvent(t){return this.consumePredicate(Ft,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]}peekAt(t){const e=this.current+t;return e>=0&&this.tokens.length>e?this.tokens[e]:null}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 n=e.start||0,r=e.line||1,i=e.column||1;if(t.includes("property name after '.'")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1}if(t.includes("parenthes")){const t=this.current>0?this.previous():e;n=t.end||t.start||0,r=t.line||1,i=t.column||1,0===n&&this.current>0&&(n=this.current)}if(t.includes("Expected expression after")){const t=this.current>0?this.previous():e;n=t.start||0,r=t.line||1,i=t.column||1,0===n&&(n=Math.max(1,this.current-1))}if(t.includes("Missing operand")){let t=e;for(let e=this.current-1;e>=0;e--){const n=this.tokens[e];if(n&&("+"===n.value||"-"===n.value)){t=n;break}}n=t.start||0,r=t.line||1,i=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,i),position:Math.max(0,n)},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("\u26a0\ufe0f synchronize: Skipping token:",t.value),this.advance()}}parseAttributeOrArrayLiteral(){const t=this.previous().start,e=this.previous().line,n=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const r=[];for(;!this.check("]")&&!this.isAtEnd();){const t=this.advance();r.push(t.value)}this.consume("]","Expected ']' after attribute literal");const i=r.join("");if(!i.includes("="))return{type:"attributeAccess",attributeName:i.replace(/^@/,""),start:t,end:this.previous().end,line:e,column:n};const s="["+i+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),i=this.tokens[this.current],s=this.tokens[this.current+1];if("identifier"===i?.kind&&("]"===s?.value||s&&r.has(s.value)&&"string"===this.tokens[this.current+2]?.kind)){let t="["+this.advance().value;if(this.check("]"))this.advance(),t+="]";else{const e=this.advance().value,n=this.advance().value;t+=e+'"'+(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n)+'"',this.consume("]","Expected ']' after attribute selector"),t+="]"}return this.createSelector(t)}const o=[];if(!this.check("]"))do{if(this.check("]"))break;o.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:o,start:t,end:this.previous().end,line:e,column:n}}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),parseExpression:this.parseExpression.bind(this),parsePrimary:this.parsePrimary.bind(this),parseLogicalAnd:this.parseLogicalAnd.bind(this),parseCSSObjectLiteral:this.parseCSSObjectLiteral.bind(this),parseCommand:this.parseCommand.bind(this),parseCommandSequence:this.parseCommandSequence.bind(this),parseCommandListUntilEnd:this.parseCommandListUntilEnd.bind(this),parseCommandListUntilEndOrElse:this.parseCommandListUntilEndOrElse.bind(this),parseRepeatBody:this.parseRepeatBody.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=>t.peekAt(e),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 tn(t,e){const n=function(t){const e={input:"",position:0,line:1,column:1,tokens:[]};e.input=t;const n=t.length;for(;n>e.position&&(U(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==D(e,1))if('"'!==n){if("'"===n||"'"===n){const t=D(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==q.IDENTIFIER&&n.kind!==q.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)W(e);else{const t=e.position;F(e),F(e),V(e,q.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===D(e,1)){const t=e.position;F(e),F(e),V(e,q.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),r=t&&t.kind===q.IDENTIFIER&&E.has(t.value.toLowerCase()),i=t&&t.kind===q.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===q.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(et(D(e))||"{"===D(e)||"-"===D(e))){J(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===q.IDENTIFIER&&I.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==q.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(F(e),V(e,q.SYMBOL,"[")):(F(e),V(e,q.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=D(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){tt(e);continue}}st(n)?G(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(V(e,q.UNKNOWN,n),F(e)):Q(e):Y(e)}else F(e),V(e,q.OPERATOR,"]")}else F(e),V(e,q.OPERATOR,"}");else F(e),V(e,q.OPERATOR,"{");else X(e)}else J(e);else it(e)?K(e):G(e);else Z(e)}else W(e);else z(e)}return e.tokens}(t);return new Qe(n,e,t).parse()}Qe.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Qe.PRATT_TABLE=At,Qe.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class en{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 n of this.afterExecuteHooks)await n(t,e)}async runOnError(t,e){let n=e;for(const e of this.onErrorHooks){const r=await e(t,n);r instanceof Error&&(n=r)}return n}shouldIntercept(t,e){for(const n of this.interceptCommandHooks)if(n(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 nn(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function rn(t){return{ok:!0,value:t}}function sn(t){return{ok:!1,error:t}}function on(t){return!0===t.ok}const an=new Map,cn=new WeakMap;function ln(t){let e=cn.get(t);return e||(e=new Map,cn.set(t,e)),e}function un(t){return t.owner||(t.me instanceof Element?t.me:null)}function fn(t,e){const n=un(t);if(n)return qt(e,t),ln(n).get(e)}function hn(t,e,n){const r=un(t);r&&(ln(r).set(e,n),Pt(e,n,t))}function dn(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||an,flags:{halted:!1,breaking:!1,continuing:!1,returning:!1,async:!1}}}function pn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function mn(t){if(null===t||"object"!=typeof t)return!1;const e=t.nodeType;return 1===e||3===e||11===e}function yn(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function gn(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 vn(t,e,n){return"element"===n?fn(e,t):"global"===n&&e.globals&&e.globals.has(t)?e.globals.get(t):"global"!==n&&e.locals&&e.locals.has(t)?(qt(t,e),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"===n&&e.locals&&e.locals.has(t)?(qt(t,e),e.locals.get(t)):"undefined"!=typeof window&&t in window?window[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}function bn(t,e,n,r){if("element"!==r){if("global"===r)return Ht(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void Ht(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Pt(t,e,n);if(n.globals&&n.globals.has(t))return Ht(n,t,e),void("undefined"!=typeof window&&t in window&&(window[t]=e));if(n.variables&&n.variables.has(t))n.variables.set(t,e);else{if("undefined"!=typeof window&&t in window)return window[t]=e,void Ht(n,t,e);n.locals.set(t,e),Pt(t,e,n)}}else hn(n,t,e)}function wn(t,e){return"me"===t?e.me:"it"===t?e.it:"you"===t?e.you:vn(t,e)}function En(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function xn(t){if(pn(t))return[t];if(Array.isArray(t)){const e=t.filter(pn);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(pn);return e.length>0?e:null}return null}const kn=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,n]of this.types)if(n.isType(t))return e;return"Unknown"}getHyperScriptType(t){const e=this.inferType(t),n=this.types.get(e);return n?.hyperscriptType??"unknown"}coerce(t,e,n){const r=this.types.get(e);if(!r){if(this.config.strictMode)throw Error("Unknown target type: "+e);return null}if(r.isType(t))return t;if(this.config.cacheCoercions){const n=`${this.inferType(t)}:${e}:${JSON.stringify(t)}`;if(this.coercionCache.has(n))return this.coercionCache.get(n)}const i=this.inferType(t),s=r.coerceFrom?.[i];if(s){const r=s(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${i}:${e}:${JSON.stringify(t)}`;this.coercionCache.set(n,r)}return r}return r.defaultValue}canCoerce(t,e){const n=this.types.get(e);if(!n)return!1;if(n.isType(t))return!0;const r=this.inferType(t);return void 0!==n.coerceFrom?.[r]}getCoercionInfo(t,e){const n=this.types.get(e);return n&&(t===e||n.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 n=t;if(n.startsWith("#")||n.startsWith(".")||n.match(/^[\w-]+$/))try{return document.querySelector(n)}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,n)=>{e[n+""]=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 Sn(t){const e=kn.get("String");return e?e.isType(t):"string"==typeof t}function An(t){const e=kn.get("Number");return e?e.isType(t):"number"==typeof t}function Tn(t){const e=kn.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Cn(t){const e=kn.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function $n(t){const e=kn.get("Function");return e?e.isType(t):"function"==typeof t}function Nn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function On(t){return t instanceof Element}function Rn(t){return t instanceof HTMLElement}const jn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Ln(t,e){return jn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Mn={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=>Nn(t)?t.tabIndex:void 0,hidden:t=>Nn(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,next:t=>t.nextElementSibling,previous: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 n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function In(t,e){if(e.startsWith("*"))return function(t,e){if(!Rn(t))return;if(e.startsWith("computed-"))return getComputedStyle(t).getPropertyValue(e.slice(9))||"";const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}(t,e.slice(1));if(e.startsWith("computed-")){const n=e.slice(9);return Rn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return Ln(t,e.slice(1));const n=Mn[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Ln(t,e);const r=t[e];return $n(r)?r.bind(t):r}const Pn={1:"one",2:"two",3:"three",4:"four",5:"five"};function qn(t,e,n,r){if(t.length!==e){return`${n} requires exactly ${i=e,Pn[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`}var i;return null}function Hn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Bn(t,e,n){return qn(t,1,e,n)??Hn(t,0,e,n)}function Dn(t,e){return qn(t,2,e,"left, right")}function Fn(){return null}function Un(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function Vn(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const _n={conversions:{dynamicResolvers:[]}},zn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":Sn(t)?t:Cn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(Tn(t))return t;if(null==t)return!1;if(Sn(t)){const e=t.toLowerCase().trim();return"false"!==e&&"0"!==e&&""!==e}return An(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(An(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(An(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(!An(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=zn.Number(t);return Math.trunc(e)},Float:t=>{const e=zn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(Sn(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return new Date(e,n-1,r)}return new Date(t)},JSON:t=>{if(!Sn(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(Cn(t))return t;if(Sn(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{const e=document.createDocumentFragment(),n=Array.isArray(t)||t instanceof NodeList?Array.from(t):[t];for(const t of n)if(t instanceof Node)e.append(t);else{const n=document.createElement("template");n.innerHTML=null==t?"":t+"",e.append(n.content)}return e},HTML:t=>Sn(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:zn.String(t)).join(""):t instanceof Element?t.outerHTML:zn.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return function(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=Wn(n);void 0!==t&&(void 0!==e[n.name]?(Array.isArray(e[n.name])||(e[n.name]=[e[n.name]]),e[n.name].push(t)):e[n.name]=t)}}),e}(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=Wn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?zn.Values(t,e):t;if(!Cn(n))return"";const r=new URLSearchParams;for(const[t,e]of Object.entries(n))if(null!=e)if(Array.isArray(e))for(const n of e)r.append(t,n+"");else r.append(t,e+"");return""+r},Set:t=>new Set(t),Map:t=>new Map(Object.entries(t??{})),Keys:t=>t instanceof Map?Array.from(t.keys()):Object.keys(t??{}),Entries:t=>t instanceof Map?Array.from(t.entries()):Object.entries(t??{}),Reversed:t=>Array.from(t).reverse(),Unique:t=>[...new Set(t)],Flat:t=>Array.from(t).flat(),"Values:Form":(t,e)=>{const n=zn.Values(t,e);return zn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=zn.Values(t,e);return JSON.stringify(n)}};function Wn(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 Zn={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",jsonstring:"JSONString",formencoded:"FormEncoded"};function Jn(t,e,n){if("string"!=typeof e)throw Error("Conversion type must be a string");if(e.startsWith("Fixed")){const{precision:n}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):0}:{}}(e);return zn.Number(t).toFixed(n??0)}if(null==t)return t;let r=zn[e];if(r)return r(t,n);const i=Zn[e.toLowerCase()];if(i&&(r=zn[i],r))return r(t,n);const s=_n.conversions[e];if("function"==typeof s)return s(t,n);for(const n of _n.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Kn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Jn(n,r,t)},validate:t=>qn(t,2,"as","value, type")??Hn(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[n,r]=e;if(!Sn(r))throw Error("Type check requires a string type");switch(r.toLowerCase()){case"null":return null===n;case"undefined":return void 0===n;case"string":return Sn(n);case"number":return An(n)&&!isNaN(n);case"boolean":return Tn(n);case"object":return Cn(n);case"array":return Array.isArray(n);case"function":return $n(n);case"date":return n instanceof Date;case"element":return n instanceof Element;case"node":return n instanceof Node;case"nodelist":return n instanceof NodeList;case"empty":return null==n||""===n||Array.isArray(n)&&0===n.length||Cn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>qn(t,2,"is","value, type")??Hn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>qn(t,1,"async","expression")}},Xn=new Set(["__proto__","constructor","prototype"]);function Gn(t,e){if(t instanceof Element)return In(t,e);if(Cn(t)){if(Xn.has(e))return;return t[e]}return t[e]}function Yn(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return!1;e=Array.from(t)}return 0!==e.length&&e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const Qn={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(t,...e){const[n,r]=e;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");return Yn(n)&&!(r in n)?Array.from(n,t=>Gn(t,r)):Gn(n,r)}},validate:t=>qn(t,2,"possessive","element, property")??Hn(t,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(t,...e){const[n]=e;if(t.me){if("string"!=typeof n)throw Error("Property name must be a string");if(t.me instanceof Element)return In(t.me,n);if(Cn(t.me)){if(Xn.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Bn(t,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(t,...e){const[n]=e;if(null==t.it)return;if("string"!=typeof n)throw Error("Property name must be a string");const r=t.it;if(r instanceof Element)return In(r,n);if(Cn(r)){if(Xn.has(n))return;return r[n]}return r[n]},validate:t=>Bn(t,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(t,...e){const[n]=e;if(t.you){if("string"!=typeof n)throw Error("Property name must be a string");if(t.you instanceof Element)return In(t.you,n);if(Cn(t.you)){if(Xn.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Bn(t,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(t,...e){const[n,r]=e;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");if(r instanceof Element)return In(r,n);if(Cn(r)){if(Xn.has(n))return;return r[n]}return r[n]}},validate:t=>qn(t,2,"of","property, object")??Hn(t,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");const i=r||t.me;return i&&i instanceof Element?i.getAttribute(n):null},validate:t=>Vn(t,1,2,"attribute","attributeName, optional element")??Hn(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[n,r,i]=e;if("string"!=typeof n)throw Error("Attribute name must be a string");if("string"!=typeof r)throw Error("Expected value must be a string");const s=i||t.me;return!!(s&&s instanceof Element)&&s.getAttribute(n)===r},validate:t=>Vn(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Hn(t,0,"attributeWithValue","attribute name")??Hn(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[n]=e;if("string"!=typeof n)throw Error("Class name must be a string");const r=n.startsWith(".")?n.slice(1):n,i=document.getElementsByClassName(r);return Array.from(i)},validate:t=>Bn(t,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("ID value must be a string");const r=n.startsWith("#")?n.slice(1):n;return document.getElementById(r)},validate:t=>Bn(t,"idReference","idValue")}};function tr(t){return Array.isArray(t)?t:null==t?[]:"string"==typeof t?[t]:t instanceof NodeList||t instanceof HTMLCollection||"number"==typeof t.length?Array.from(t):[t]}function er(t,e){const n=t.registry?.get(e);if(!n)throw Error(`Expression '${e}' not in ExecutionContext.registry. The bundle's ExpressionRegistry must include this expression's category. Use createExpressionRegistry() with the relevant category objects (referencesExpressions, logicalExpressions, conversionExpressions, positionalExpressions, propertiesExpressions, specialExpressions, mathematicalExpressions).`);return n}function nr(t){if(t&&"object"==typeof t&&"success"in t){if(t.success)return"value"in t?t.value:void 0;const e=t.errors||[];throw Error(e.length>0?e[0].message:"Expression evaluation failed")}return t}async function rr(t,e){if(!t)throw Error("Cannot evaluate null or undefined AST node");if("literal"===t.type)return t.value;if("identifier"===t.type)return ur(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return ur(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await rr(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?Ht(e,t.slice(1),n):"global"===i.scope?Ht(e,t,n):"element"===i.scope?hn(e,t,n):(e.locals||(e.locals=new Map),e.locals.set(t,n)),n}throw Error(`Assignment target must be a variable identifier (got '${i?.type??"undefined"}')`)}if("has"===n||"have"===n){const n=await rr(t.left,e);return!!(n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("."))&&n.classList.contains(r.value.slice(1))}if("in"===n||"is in"===n){const n="callExpression"===i?.type&&"identifier"===i.callee?.type?i.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(i.arguments)){const r=i.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const i=await rr(t.right,e);if(i&&"function"==typeof i.querySelectorAll){const t=Array.from(i.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===i?.type&&i.fromQuery&&"string"==typeof i.value){const n=await rr(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(i.value))}}if("of"===n&&"selector"===i?.type&&"string"==typeof i.value&&/^\*[a-zA-Z][\w-]*$/.test(i.value)){const n=await rr(t.right,e);return er(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=fr(t.left);if(n){const r=await rr(t.right,e);let i=r;for(const t of n){if(null==i)return;i=On(i)?In(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const s=await rr(t.left,e);if("and"===n){if(!s)return s;const n=await rr(t.right,e);return er(e,"and").evaluate(e,s,n)}if("or"===n){if(s)return s;const n=await rr(t.right,e);return er(e,"or").evaluate(e,s,n)}const o=await rr(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(s):s,l=t.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=gn(n)),"string"==typeof r&&(r=gn(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:nr(await er(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return nr(await er(e,"subtraction").evaluate(e,{left:s,right:o}));case"*":return nr(await er(e,"multiplication").evaluate(e,{left:s,right:o}));case"/":return nr(await er(e,"division").evaluate(e,{left:s,right:o}));case"%":case"mod":return nr(await er(e,"modulo").evaluate(e,{left:s,right:o}));case"^":case"**":return nr(await er(e,"power").evaluate(e,{left:s,right:o}));case">":case"is greater than":return er(e,"greaterThan").evaluate(e,s,o);case"<":case"is less than":return er(e,"lessThan").evaluate(e,s,o);case">=":case"is greater than or equal to":return er(e,"greaterThanOrEqual").evaluate(e,s,o);case"<=":case"is less than or equal to":return er(e,"lessThanOrEqual").evaluate(e,s,o);case"==":return er(e,"equals").evaluate(e,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=pr(t,s,o);return void 0!==n?n:er(e,"equals").evaluate(e,c,l)}case"!=":return er(e,"notEquals").evaluate(e,c,l);case"is not":case"is not equal":case"is not equal to":{const n=pr(t,s,o);return void 0!==n?!n:er(e,"notEquals").evaluate(e,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return er(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really":case"is not really equal to":return er(e,"strictNotEquals").evaluate(e,c,l);case"as":return er(e,"as").evaluate(e,s,yr(o));case"contains":case"contain":case"includes":case"include":return er(e,"contains").evaluate(e,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return er(e,"doesNotContain").evaluate(e,c,l);case"starts with":return er(e,"startsWith").evaluate(e,c,l);case"ends with":return er(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await er(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await er(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return er(e,"matches").evaluate(e,c,dr(t.right,l));case"does not match":case"do not match":return!await er(e,"matches").evaluate(e,c,dr(t.right,l));case"in":case"is in":case"am in":return hr(s,o);case"is not in":case"am not in":return!hr(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return mr(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!mr(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return mr(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!mr(s,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await rr(t.expression,e),r=yr(t.targetType);return er(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await rr(t.value,e),r=await rr(t.min,e),i=await rr(t.max,e),s=t=>"string"==typeof t?t.toLowerCase():t,[o,a,c]=t.ignoringCase?[s(n),s(r),s(i)]:[n,r,i],l=await er(e,"between").evaluate(e,o,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return!0;if(Object.prototype.toString.call(t).slice(8,-1)===e)return!0;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await rr(t.value,e),t.typeName+"",!1!==t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await rr(t.collection,e);if(null==n)return n;const r=async(t,n)=>rr(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=tr(t),i=[];for(const t of r)await n(e,t)&&i.push(t);return i}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const i=[...tr(t)],s=await Promise.all(i.map(t=>r(e,t))),o=i.map((t,e)=>e);o.sort((t,e)=>{const n=s[t],r=s[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(t=>i[t]);return"desc"===n?a.reverse():a}(n,t.right,t.order??"asc",r);case"mapped to":return async function(t,e,n){const r=tr(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return s=await rr(t.right,e),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return tr(t).map(t=>null==t?"":t+"").join(n)}(n,await rr(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var i,s}(n,e);case"unaryExpression":return async function(t,e){const n=t.operand??t.argument;if(!n)throw Error(`Unary expression has no operand (operator: ${t.operator})`);const r=await rr(n,e);switch(t.operator){case"not":case"!":return er(e,"not").evaluate(e,r);case"no":return er(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return er(e,"exists").evaluate(e,r);case"does not exist":return er(e,"doesNotExist").evaluate(e,r);case"is empty":return er(e,"isEmpty").evaluate(e,r);case"is not empty":return er(e,"isNotEmpty").evaluate(e,r);default:throw Error("Unknown unary operator: "+t.operator)}}(n,e);case"memberExpression":return async function(t,e){const n=await rr(t.object,e);if(t.computed){const r=await rr(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return wr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await rr(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await wr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await rr(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>rr(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return Er.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:rr(t,n))):Promise.all(t.map(t=>rr(t,n)))}(t.arguments,r,e);switch(r){case"closest":return er(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?xr(await rr(n.from,e)):e.me,s=n.within?xr(await rr(n.within,e)):void 0,o=n.inElt?await rr(n.inElt,e):void 0;return er(e,r).evaluate(e,i[0],t,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return er(e,r).evaluate(e,...i)}case"first":return er(e,"first").evaluate(e,...i);case"last":return er(e,"last").evaluate(e,...i);default:if("function"==typeof n)return n(...i);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>rr(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await rr(t.callee.object,e);return n.apply(i,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){let n=t.value;if("string"==typeof n&&!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))return er(e,"styleRef").evaluate(e,n.slice(1));if("string"==typeof n&&t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=await async function(t,e){const n=Cr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>ar(t.expr,e)));return $r(n,r)}(n,e),s=Ar(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await er(e,"elementWithSelector").evaluate(e,s)}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}"string"==typeof n&&!t.fromQuery&&n.includes("{")&&(n=await function(t,e){return br(t,/\{([^}]*)\}/g,async(t,n)=>(await ar(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?Ar(t,n):n;return En(await er(e,"elementWithSelector").evaluate(e,r),n,t.fromQuery)}(n,e);case"contextReference":return async function(t,e){switch(t.contextType){case"me":case"you":case"it":return er(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return er(e,"me").evaluate(e);case"your":case"yourself":return er(e,"you").evaluate(e);case"its":return er(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??er(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return er(e,"document").evaluate(e);case"window":return er(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await rr(t.object,e),r=t.property.name;return er(e,"possessive").evaluate(e,n,r)}(n,e);case"eventHandler":return async function(t,e){return{event:t.event,selector:t.selector,commands:t.commands,handler:async n=>{const r={...e,event:n,target:n.target,currentTarget:n.currentTarget};for(const e of t.commands)await rr(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await rr(t.test,e)?rr(t.consequent,e):t.alternate?rr(t.alternate,e):void 0}(n,e);case"string":return n.value;case"arrayLiteral":return async function(t,e){const n=[];for(const r of t.elements)n.push(await rr(r,e));return n}(n,e);case"objectLiteral":return async function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await rr(t,e)+"",n[i]=await rr(r.value,e)}return n}(n,e);case"attributeAccess":return async function(t,e){const n=t.attributeName;return e.me&&e.me instanceof Element?e.me.getAttribute(n):"@"+n}(n,e);case"propertyOfExpression":return async function(t,e){const n=t.property;if("identifier"!==n?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const r=n.name,i=await rr(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return er(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await br(n,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(t,n)=>{try{if(/^\d+$/.test(n))return n;if(n.includes(".")){const t=n.split(".");let r=vr(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(vr(n,e)??"")+""}catch{return""}}),n=await br(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await ar(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await rr(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return gr(n,e);default:{const n=Ct.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class ir extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function sr(t,e){const n=t;switch(n?.type){case"literal":case"string":return n.value;case"selector":return function(t,e){const n=t.value;if("string"!=typeof n)throw new ir("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new ir("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=Cr(t),r=n.filter(t=>"expr"in t).map(t=>or(t.expr,e));return $r(n,r)}(n,e),s=Ar(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new ir("selector");i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return Array.from(o.querySelectorAll(s))}finally{i.forEach(t=>t.removeAttribute("data-hs-query-id"))}}const r=!t.fromQuery&&n.includes("{")?function(t,e){return t.replace(/\{([^}]*)\}/g,(t,n)=>(or(n.trim(),e)??"")+"")}(n,e):n,i=Ar(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new ir("selector");return En(Array.from(s.querySelectorAll(i)),r,t.fromQuery)}(n,e);case"identifier":return function(t,e,n){return"me"===t||"my"===t||"I"===t?e.me:"you"===t||"your"===t||"yourself"===t?e.you:"it"===t||"its"===t?e.it??e.result:"result"===t?e.result??e.it:"window"===t?"undefined"!=typeof window?window:globalThis:"document"===t?"undefined"!=typeof document?document:void 0:"element"===n?fn(e,t):e.locals?.has(t)?e.locals.get(t):e.globals?.has(t)?e.globals.get(t):t.startsWith("$")&&e.globals?.has(t.slice(1))?e.globals.get(t.slice(1)):void 0!==e[t]?e[t]:"undefined"!=typeof globalThis&&t in globalThis?globalThis[t]:void 0}(n.name,e,n.scope);case"contextReference":return function(t,e){switch(t){case"me":return e.me;case"you":return e.you;case"it":return e.it??e.result;case"event":return e.event;case"target":return e.target??e.event?.target??e.me;default:throw new ir("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>sr(t,e));case"objectLiteral":return function(t,e){const n={};for(const r of t.properties){const t=r.key;let i;i="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:sr(t,e)+"",n[i]=sr(r.value,e)}return n}(n,e);case"asExpression":return Jn(sr(n.expression,e),yr(n.targetType),e);case"stringPostfix":return`${sr(n.expression,e)}${n.unit}`;case"blockLiteral":return gr(n,e);case"memberExpression":{const t=sr(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new ir("memberExpression");const r=t[n.computed?sr(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new ir(n?.type??"unknown")}}function or(t,e){const n=tn(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return sr(n.node,e)}async function ar(t,e){const n=tn(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}const r=e.registry?e:{...e,registry:await lr()};return rr(n.node,r)}let cr=null;async function lr(){if(!cr){const t=await Promise.resolve().then(function(){return ua});cr=t.createFullExpressionRegistry()}return cr}async function ur(t,e){const n=t.name;return n.startsWith("$")?It(n.slice(1),e):"global"===t.scope&&It(n,e),"me"===n||"my"===n||"I"===n?er(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?er(e,"you").evaluate(e):"it"===n||"its"===n?er(e,"it").evaluate(e):"result"===n?er(e,"result").evaluate(e):"window"===n?er(e,"window").evaluate(e):"document"===n?er(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?e.globals.get(n):"element"===t.scope?fn(e,n):e.locals&&e.locals.has(n)?(qt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?e.globals.get(n):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?e.globals.get(n.slice(1)):void 0!==e[n]?e[n]:"undefined"!=typeof globalThis&&n in globalThis?globalThis[n]:void 0}function fr(t){const e=t;if(!e)return null;if("identifier"===e.type&&"string"==typeof e.name)return[e.name];if("memberExpression"===e.type&&!e.computed){const t=fr(e.object);if(!t)return null;const n=e.property,r="identifier"===n?.type&&"string"==typeof n.name?n.name:"string"==typeof n?.value?n.value:null;return null==r?null:[...t,r]}return null}function hr(t,e){return Array.isArray(e)?e.includes(t):"string"==typeof e?e.includes(t+""):t instanceof Node&&e instanceof Node?t===e||e.contains(t):null!=e&&"object"==typeof e&&t in e}function dr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function pr(t,e,n){if(void 0!==n)return;const r=t.right;if(!r||"identifier"!==r.type||"string"!=typeof r.name)return;if(null==e||"object"!=typeof e)return;const i=e[r.name];return"boolean"==typeof i?!0===i:void 0}function mr(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function yr(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 gr(t,e){const n=t.parameters??[];return(...r)=>{const i=new Map(e.locals??new Map);n.forEach((t,e)=>i.set(t,r[e]));const s={...e,locals:i};try{return sr(t.body,s)}catch(e){if(e instanceof ir)return rr(t.body,s);throw e}}}function vr(t,e){if(e.locals?.has(t))return qt(t,e),e.locals.get(t);if("me"===t&&e.me)return e.me;if("you"===t&&e.you)return e.you;if("it"===t){const t=e.it??e.result;if(t)return t}if("result"===t){const t=e.result??e.it;if(t)return t}return"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function br(t,e,n){const r=[];let i;for(;null!==(i=e.exec(t));)r.push({index:i.index,length:i[0].length,replacement:await n(i[0],...i.slice(1))});let s=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:i}=r[t];s=s.substring(0,e)+i+s.substring(e+n)}return s}function wr(t,e,n){if("string"==typeof e&&e.startsWith("@")){const n=e.substring(1);return t&&"function"==typeof t.getAttribute?t.getAttribute(n):void 0}return t instanceof Element&&"string"==typeof e?In(t,e):Yn(t)&&!(e in t)?er(n,"possessive").evaluate(n,t,e):t?.[e]}const Er=new Set(["closest","previous","next"]);function xr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const kr=RegExp("(\\.[a-zA-Z0-9_-]+):(?!(hover|active|focus|visited|link|focus-within|focus-visible|first-child|last-child|only-child|nth-child|nth-last-child|nth-of-type|nth-last-of-type|first-of-type|last-of-type|only-of-type|empty|root|target|lang|dir|not|has|is|where|matches|before|after|first-letter|first-line|selection|placeholder|marker|backdrop|enabled|disabled|checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range|read-only|read-write|default|defined|fullscreen|modal|picture-in-picture|autofill)(?![a-zA-Z0-9_-]))","g"),Sr=/[:&()[\]/]/g;function Ar(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(kr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(Sr,"\\$&")}(e)}const Tr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function Cr(t){const e=[];let n,r=0;for(Tr.lastIndex=0;null!==(n=Tr.exec(t));)n.index>r&&e.push({lit:t.slice(r,n.index)}),e.push({expr:n[1]??n[2]}),r=n.index+n[0].length;return t.length>r&&e.push({lit:t.slice(r)}),e}function $r(t,e){let n="";const r=[];let i=0;for(const s of t){if("lit"in s){n+=s.lit;continue}const t=e[i++];On(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class Nr{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,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&pt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&pt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&pt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&pt("CleanupRegistry: Cleared timeout")},description:"Timeout"})}registerCustom(t,e,n){this.addCleanup(t,{type:"custom",cleanup:e,description:n||"Custom cleanup"})}registerGlobal(t,e="custom",n){this.globalCleanups.push({type:e,cleanup:t,description:n||"Global cleanup"}),this.debugMode&&pt("CleanupRegistry: Registered global cleanup: "+(n||e))}addCleanup(t,e){const n=this.elementCleanups.get(t);n?n.push(e):(this.elementCleanups.set(t,[e]),this.elementCount++),this.typeCounts[e.type]++,this.debugMode&&pt(`CleanupRegistry: Registered ${e.type} for element`,t)}cleanupElement(t){const e=this.elementCleanups.get(t);if(!e||0===e.length)return 0;let n=0;for(const t of e){try{t.cleanup(),n++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&pt(`CleanupRegistry: Cleaned up ${n} resources for element`),n}cleanupElementTree(t){let e=this.cleanupElement(t);const n=t.querySelectorAll("*");for(const t of n)e+=this.cleanupElement(t);return e}cleanupGlobal(){let t=0;for(const e of this.globalCleanups)try{e.cleanup(),t++}catch(t){this.debugMode&&pt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&pt(`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,n=0,r=0,i=0;for(const s of this.globalCleanups)switch(s.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":i++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+t,observers:this.typeCounts.observer+e,intervals:this.typeCounts.interval+n,timeouts:this.typeCounts.timeout+r,custom:this.typeCounts.custom+i,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}class Or{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&pt("[EventSourceRegistry] Overwriting existing event source: "+t),this.sources.set(n,e)}unregister(t){const e=t.toLowerCase(),n=this.sources.get(e);if(n){for(const[t,n]of this.subscriptions.entries())n.source===e&&(n.unsubscribe(),this.subscriptions.delete(t));return n.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,n){const r=this.get(t);if(!r)return void pt("[EventSourceRegistry] Unknown event source: "+t);r.initialize?.();const i=r.subscribe(e,n);return this.subscriptions.set(i.id,i),i}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,n]of this.sources.entries())if(n.supports?.(t)??n.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 Rr{constructor(){this.providers=new Map,this.globalProviders=new Map}register(t,e,n){const r=t.toLowerCase();this.providers.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.dependencies}:e)}registerGlobal(t,e,n){const r=t.toLowerCase();this.globalProviders.set(r,"function"==typeof e?{name:r,provide:e,cache:n?.cache??!0,description:n?.description,dependencies:n?.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,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const s=await r.provide(e);return r.cache&&n&&n.set(i,s),s}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const i="__provider_"+r.name;if(r.cache&&n?.has(i))return n.get(i);const s=r.provide(e);if(s instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(i,s),s}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,i){if("string"==typeof r&&e.get(r))try{return e.resolveSync(r,t,n)}catch{return e.resolve(r,t,n)}return Reflect.get(t,r,i)},has:(t,n)=>!("string"!=typeof n||!e.has(n))||Reflect.has(t,n)})}async resolveAll(t){const e=new Map,n={},r=[...this.globalProviders.entries(),...this.providers.entries()];for(const[i,s]of r)try{n[i]=await this.resolve(i,t,e)}catch(t){pt(`[ContextProviderRegistry] Failed to resolve '${i}':`,t),n[i]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const jr={evaluate:(t,e)=>rr(t,e)};class Lr{static toTyped(t){return{me:t.me,...void 0!==t.owner&&{owner:t.owner},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||{},...void 0!==t.registry&&{registry:t.registry},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 Mr{constructor(t,e,n){this.impl=t,this.hookRegistry=n??null}setHookRegistry(t){this.hookRegistry=t}createHookContext(t,e,n={}){return{commandName:this.name,element:t.me instanceof Element?t.me:null,args:e,modifiers:n,event:t.event??void 0,executionContext:t}}get name(){const t=this.impl.name;if(t)return t;const e=this.impl.metadata?.name;return"string"==typeof e?e:""}get metadata(){const t=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof t?t:t?t.join(" | "):""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(ft(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void ft(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Lr.toTyped(t);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ft(`CommandAdapterV2: '${this.name}' has parseInput(), calling it`),n&&"object"==typeof n&&("args"in n||"modifiers"in n)){const e=n.modifiers,r=e?.when||e?.where;if(r&&!await rr(r,t))return void ft(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},jr,t)}else s=e;else ft(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=e;if(ft("CommandAdapterV2: Calling execute with parsed input:",s),2===this.impl.execute.length)o=await this.impl.execute(s,i);else{const t=Array.isArray(s)?s:[s];o=await this.impl.execute(i,...t)}return ft("CommandAdapterV2: Command result:",o),Object.assign(t,Lr.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Dr(t)||ft(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return{isValid:!this.impl.validate||this.impl.validate(t),errors:[],suggestions:[]}}}class Ir{constructor(t,e){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=e}setHookRegistry(t){this.hookRegistry=t;for(const e of this.adapters.values())e.setHookRegistry(t);pt(`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 n=e.toLowerCase();pt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Mr(t,void 0,this.hookRegistry);this.adapters.set(n,r),E.add(n);const i=t.metadata?.aliases;if(i&&Array.isArray(i))for(const e of i){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),E.add(n)}}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 n=this.getAdapter(t);return n?n.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 Pr=null;function qr(){return Pr||(Pr=function(t){const e=t?.commands??new Ir,n=t?.eventSources??new Or,r=t?.context??new Rr,i=new Set,s={commands:e,eventSources:n,context:r,use(t){if(i.has(t.name))pt(`[LokaScriptRegistry] Plugin '${t.name}' is already installed`);else{if(t.commands)for(const n of t.commands)e.register(n);if(t.eventSources)for(const e of t.eventSources)n.register(e.name,e);if(t.contextProviders)for(const{name:e,provide:n,options:i}of t.contextProviders)r.register(e,n,i);t.setup?.(s),i.add(t.name)}},reset(){i.clear()}};return s}()),Pr}class Hr{constructor(t={}){this.contextCache=new WeakMap;const e=qr();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,pt(`[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),pt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return pt("[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 pt(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return pt(`[RegistryIntegration] Found event source '${n}' supporting '${t}'`),e}}hasEventSource(t){return void 0!==this.getEventSource(t)}subscribeToEventSource(t,e,n){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const r=this.eventSourceRegistry.subscribe(t,e,n);if(!r)throw Error(`Failed to subscribe to event source '${t}'`);return pt(`[RegistryIntegration] Subscribed to '${t}' event '${e.event}' (id: ${r.id})`),r}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}getContextProviderNames(){return this.contextRegistry.getProviderNames()}destroy(){this.eventSourceRegistry.destroy(),this.contextCache=new WeakMap,pt("[RegistryIntegration] Destroyed")}}function Br(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 Dr(t){return t instanceof Error&&(null!==nn(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message)}function Fr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Ur=new WeakMap;function Vr(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)Vr(n,e);return e}const n=t;"identifier"===n.type&&"string"==typeof n.name&&e.add(n.name);for(const t of Object.keys(n))"start"!==t&&"end"!==t&&"line"!==t&&"column"!==t&&Vr(n[t],e);return e}class _r{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.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=an,this.hookRegistry=new en,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Nr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==t.registryIntegration&&(this.registryIntegration=new Hr("object"==typeof t.registryIntegration?t.registryIntegration:{}),pt("RuntimeBase: Registry integration enabled")),this.behaviorAPI={has:t=>this.behaviorRegistry.has(t),get:t=>this.behaviorRegistry.get(t),set:(t,e)=>this.behaviorRegistry.set(t,e),resolve:null,install:async(t,e,n)=>await this.installBehaviorOnElement(t,e,n)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(t=>{const e=[];for(const n of t)for(const t of n.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&&pt(`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)}trackListener(t,e,n,r,i){this.cleanupRegistry.registerListener(t,e,n,r,i)}cleanupTree(t){return this.cleanupRegistry.cleanupElementTree(t)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...t){this.options.enableErrorReporting&&console.error(...t)}logWarn(...t){this.options.enableErrorReporting&&console.warn(...t)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear(),pt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){pt(`RUNTIME BASE: execute() called with node type: '${t.type}'`),e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI),e.locals.has("_runtimeExecute")||e.locals.set("_runtimeExecute",(t,n)=>this.execute(t,n||e));try{if(this.hasErrorDiagnostics(t)){const e=t.diagnostics?.[0];return pt("\u26a0\ufe0f 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){const n=await this.processCommandWithResult(t,e);if(!on(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Br(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=nn(t);if(n?.isReturn){const t=n.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw t}case"eventHandler":return await this.executeEventHandler(t,e);case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return await this.executeEventHandler(n,e)}case"behavior":return await this.executeBehaviorDefinition(t,e);case"def":return this.installFunction(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 n=t,r=await this.executeCommandSequenceWithResult(n.commands||[],e);if(!on(r))throw Br(r.error);return r.value}return await this.executeCommandSequence(t,e);case"objectLiteral":return await this.executeObjectLiteral(t,e);default:if(this.options.enableResultPattern){const n=await this.evaluateExpressionWithResult(t,e);if(!on(n))throw Br(n.error);return n.value}return await this.evaluateExpression(t,e)}}catch(t){throw t}}async processCommand(t,e){const{name:n,args:r,modifiers:i}=t,s=n.toLowerCase();if(ft(`RUNTIME BASE: Processing command '${s}'`),this.registry.has(s)){const t=await this.registry.getAdapter(s);if(!t)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this})}catch(t){throw Dr(t)||this.logError(`Error executing command '${s}':`,t),t}}const o=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(o),Error(o)}toSignal(t){const e=nn(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:n,args:r,modifiers:i}=t,s=n.toLowerCase();if(ft(`RUNTIME BASE (Result): Processing command '${s}'`),!this.registry.has(s)){const t=`Unknown command: ${n}. Ensure it is registered in the Runtime options.`;throw this.logWarn(t),Error(t)}const o=await this.registry.getAdapter(s);if(!o)throw Error(`Command '${s}' is registered but failed to load adapter.`);try{return rn(await o.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return sn(e);throw this.logError(`Error executing command '${s}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const r of t){if(this.hasErrorDiagnostics(r)){const t=r.diagnostics?.[0];pt("\u26a0\ufe0f RUNTIME: Skipping error node: "+(t?.message||"unknown error")),this.runtimeWarnings.push(t?.message||"Skipped error node");continue}if("command"===r.type){const t=await this.processCommandWithResult(r,e);if(!on(t)){const n=t.error;switch(n.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==n.returnValue&&Object.assign(e,{it:n.returnValue,result:n.returnValue}),rn(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!on(t))return t;n=t.value}}return rn(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await rr(t,n);return Fr(r)?await this.executeCommandFromPattern(r.command,r.selector,e):r}async evaluateExpressionWithResult(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await async function(t,e){try{return rn(await rr(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return sn({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return sn({type:"exit",returnValue:e.returnValue});if(e.isBreak)return sn({type:"break"});if(e.isContinue)return sn({type:"continue"});if(e.isReturn)return sn({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!on(r))return r;const i=r.value;if(Fr(i)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:i.command,args:[{type:"literal",value:i.selector}]},e);try{return rn(await this.executeCommandFromPattern(i.command,i.selector,e))}catch(t){const e=this.toSignal(t);if(e)return sn(e);throw t}}return rn(i)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}installFunction(t,e){const n=this,r=t.params??[],i=t.body??[],s=t.errorHandler,o=t.finallyHandler,a=t.errorSymbol;e.globals.set(t.name,async(...t)=>{const c={...e,locals:new Map(e.locals)};r.forEach((e,n)=>{e&&c.locals.set(e,t[n])});const l=async t=>{const e=await n.executeCommandSequenceWithResult(t,c);if(!on(e))throw nn(e.error);return e.value};if(!s&&!o)return await l(i);try{return await l(i)}catch(t){if(!s||Dr(t))throw t;return a&&c.locals.set(a,t),await l(s)}finally{o&&await l(o)}})}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],i=[],s=[],o=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"def"===e.type?i.push(e):"initBlock"===e.type?s.push(e):o.push(e);for(const t of i)this.execute(t,e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Dr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Dr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Dr(t)&&(t.isHalt||t.isExit))break;throw t}return n}async executeBlock(t,e){if(t.commands&&Array.isArray(t.commands))for(const n of t.commands)try{await this.execute(n,e)}catch(t){if(Dr(t)&&t.isHalt)break;throw t}}async executeCommandSequence(t,e){if(!t.commands||!Array.isArray(t.commands))return;let n;for(const r of t.commands)try{n=await this.execute(r,e)}catch(t){if(Dr(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 n}async executeObjectLiteral(t,e){const n={};if(!t.properties)return n;for(const r of t.properties){let t;t="identifier"===r.key.type?r.key.name:"literal"===r.key.type?r.key.value+"":await this.execute(r.key,e)+"";const i=await this.execute(r.value,e);n[t]=i}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:i=[],initBlock:s}=t,o=t.imperativeInstaller;"function"==typeof o?(this.behaviorRegistry.set(n,{name:n,parameters:r,type:"imperative",install:o}),pt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),pt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){pt("BEHAVIOR: installBehaviorOnElement called: "+t);let r=this.behaviorRegistry.get(t);if(!r&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(t)&&(r=this.behaviorRegistry.get(t)),!r))throw Error(`Behavior "${t}" not found`);if("imperative"===r.type)return void("function"==typeof r.install&&(pt(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),pt(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));pt("BEHAVIOR: Found behavior, eventHandlers count: "+(r.eventHandlers?.length||0));const i={me:e,owner:e,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry,halted:!1,returned:!1,broke:!1,continued:!1,async:!1},s=this.enhanceContext(i);if(r.parameters)for(const t of r.parameters)s.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||s.locals.set(t,e);if(r.initBlock){pt("BEHAVIOR: Running init block for "+t);const e=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(r.initBlock,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" init block timed out after ${e}ms`)),e))]),pt("BEHAVIOR: Init block completed for "+t)}catch(e){if(pt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Dr(e)))throw e}}if(pt(`BEHAVIOR: About to attach ${r.eventHandlers?.length||0} handlers for ${t}`),r.eventHandlers){const e=this.options.commandTimeout??1e4;for(const n of r.eventHandlers)await Promise.race([this.executeEventHandler(n,s),new Promise((n,r)=>setTimeout(()=>r(Error(`Behavior "${t}" handler attachment timed out after ${e}ms`)),e))])}pt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:s,args:o,selector:a,condition:c,attributeName:l,watchTarget:u,modifiers:f,errorSymbol:h,errorHandler:d,finallyHandler:p}=t,m=r&&r.length>0?r:[n];pt(`BEHAVIOR: executeEventHandler: event='${n}', target='${s}'`);let y=[],g=null;if(s){const t="string"==typeof s?s.toLowerCase():"";if("window"===t||"the window"===t)g=window;else if("document"===t||"the document"===t||"body"===t)g=document;else if("me"===t||"myself"===t)y=e.me?[e.me]:[];else if("string"==typeof s&&e.locals.has(s)){const t=e.locals.get(s);pt(`BEHAVIOR: Target resolution: found local '${s}', isElement: ${this.isElement(t)}`),this.isElement(t)?y=[t]:Array.isArray(t)?y=t.filter(t=>this.isElement(t)):"string"==typeof t&&(y=this.queryElements(t,e))}else pt(`BEHAVIOR: Target resolution: querying for '${s}'`),y=this.queryElements(s,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void pt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&l)return void this.setupMutationObserver(y,l,i,e);if("change"===n&&u)return void this.setupChangeObserver(u,i,e);const v=t.customEventSource;if(v&&this.registryIntegration){pt(`BEHAVIOR: executeEventHandler - Using custom event source '${v}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),s={...e,locals:r,it:t,event:t},o=this.enhanceContext(s);pt(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:i},o)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(v,{event:n,handler:t,target:s,selector:a},e);pt(`BEHAVIOR: Subscribed to custom event source '${v}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${v}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${v}':`,t)}return}const b=_r.createEventHandler(this,i,e,a,o,{errorSymbol:h,errorHandler:d,finallyHandler:p},1===m.length?c:void 0);let w,E=null;if(f){let t=b;if(f.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(f.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(f.debounce){const e=f.debounce;let n;w=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},E=()=>{n&&(clearTimeout(n),n=void 0)}}else if(f.throttle){const e=f.throttle;let n=0;w=r=>{const i=Date.now();e>i-n||(n=i,t(r))}}else w=t}else w=b;const x=f?.once?{once:!0}:void 0;if(g){for(const t of m)g.addEventListener(t,w,x),y.length>0?this.cleanupRegistry.registerListener(y[0],g,t,w):this.cleanupRegistry.registerGlobal(()=>g.removeEventListener(t,w),"listener",`Global ${t} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const t of y){for(const e of m){if("resize"===e&&"undefined"!=typeof ResizeObserver){const e=new ResizeObserver(t=>{for(const n of t){const t=new CustomEvent("resize",{detail:n,bubbles:!1,cancelable:!1});if(t.synthetic=!0,w(t),x?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,w,x),this.cleanupRegistry.registerListener(t,t,e,w)}E&&this.cleanupRegistry.registerCustom(t,E,"debounce-timeout")}}static createEventHandler(t,e,n,r,i,s,o){return async a=>{const c=Ur.get(a)??0;if(c>=100)return;if(Ur.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{pt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const l=new Map(n.locals),u={...n,locals:l,it:a,event:a};l.has("target")||u.locals.set("target",a.target);const f=t.enhanceContext(u);if(i&&i.length>0){const t=a,e=t.detail;for(const n of i)f.locals.set(n,t[n]??e?.[n]??null)}if(o){const e=a;for(const t of Vr(o))!f.locals.has(t)&&t in e&&f.locals.set(t,e[t]);let n;try{n=await t.evaluateExpression(o,f)}catch(t){return void pt("Event filter threw; skipping handler body:",t)}if(!n)return}const h=async e=>{for(const n of e)try{await t.execute(n,f)}catch(e){if(Dr(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(f,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}},d=s?.errorHandler,p=s?.finallyHandler;if(d||p)try{await h(e)}catch(t){if(!d||Dr(t))throw t;s?.errorSymbol&&f.locals.set(s.errorSymbol,t),await h(d)}finally{p&&await h(p)}else await h(e)}}setupMutationObserver(t,e,n,r){pt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const i of t){const t=new MutationObserver(async t=>{for(const s of t)if("attributes"===s.type&&s.attributeName===e){ht(`MUTATION DETECTED: attribute '${e}' changed on`,i);const t={...r,me:i,it:s,locals:new Map(r.locals)},o=s.oldValue,a=i.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Dr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),pt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){pt("RUNTIME BASE: Setting up MutationObserver for content changes on watch target");const r=await this.execute(t,n);let i=[];this.isElement(r)?i=[r]:Array.isArray(r)&&(i=r.filter(t=>this.isElement(t))),pt(`RUNTIME BASE: Watching ${i.length} target elements for content changes`);for(const t of i){const r=new MutationObserver(async r=>{for(const i of r)if("childList"===i.type||"characterData"===i.type){ht("CONTENT CHANGE DETECTED on",t,"mutation type:",i.type);const r={...n,me:n.me,it:i,locals:new Map(n.locals)};r.locals.set("target",t);const s=i.oldValue,o=t.textContent;null!==s&&r.locals.set("oldValue",s),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Dr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(t,r),pt("RUNTIME BASE: MutationObserver attached to",t,"for content changes")}}queryElements(t,e){const n=e.me,r=(n instanceof Element?n.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!r)return[];let i=t;i.startsWith("<")&&i.endsWith("/>")&&(i=i.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(i))}catch{return pt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement||!(!t||"object"!=typeof t)&&(!!t.style&&!!t.classList)}}function zr(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}function Wr(t,e){if(e.startsWith("computed-")){const n=e.substring(9);return getComputedStyle(t).getPropertyValue(n)||""}const n=e.replace(/-([a-z])/g,(t,e)=>e.toUpperCase());return t.style[n]}const Zr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Fn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Fn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Fn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Fn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:Fn},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const[n]=e;if("string"!=typeof n)throw Error("querySelector requires a string selector");return document.querySelector(n)},validate:t=>Bn(t,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("querySelectorAll requires a string selector");const r=document.querySelectorAll(n);return Array.from(r)},validate:t=>Bn(t,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementById requires a string ID");return document.getElementById(n)},validate:t=>Bn(t,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("getElementsByClassName requires a string class name");const r=document.getElementsByClassName(n);return Array.from(r)},validate:t=>Bn(t,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(t,...e){let n=e[0];if(n&&"object"==typeof n&&"type"in n){const t=n;"identifier"===t.type&&t.name?n=t.name:"literal"===t.type&&"string"==typeof t.value&&(n=t.value)}if("string"!=typeof n)throw Error("closest requires a string selector");return t.me?t.me.closest(n):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:Fn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Fn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Fn},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(t,...e){const n=e[0];if("string"!=typeof n)throw Error("Selector must be a string");const r=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error("DOM not available - cannot resolve element selector");const i=r.querySelectorAll(n);return Array.from(i)},validate:t=>Bn(t,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n)throw Error("StyleRef requires a string property name");const i=r||t.me;if(i&&i instanceof HTMLElement)return Wr(i,n)},validate:t=>Vn(t,1,2,"styleRef","property, optional element")??Hn(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 n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Possessive styleRef requires possessor and property strings");let i=null;if("my"===n&&t.me?i=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Wr(i,r)},validate:t=>qn(t,2,"possessiveStyleRef","possessor, property")??Hn(t,0,"possessiveStyleRef","possessor")??Hn(t,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(t,...e){const n=e[0],r=e[1];if("string"!=typeof n||"string"!=typeof r)throw Error("Of styleRef requires property and reference strings");let i=null;if("me"===r&&t.me?i=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(i=t.it instanceof HTMLElement?t.it:null),i)return Wr(i,n)},validate:t=>qn(t,2,"ofStyleRef","property, reference")??Hn(t,0,"ofStyleRef","property")??Hn(t,1,"ofStyleRef","reference")}};function Jr(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Kr="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Xr;function Gr(){return Xr({validate:t=>({success:!0,data:t})})}function Yr(t,e){if(Kr)return Gr();const n=Xr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:!1,error:Jr("type-mismatch","Expected object, received "+typeof n)};const r=n,i={};if(e?.strict){const e=Object.keys(t),n=Object.keys(r).filter(t=>!e.includes(t));if(n.length>0)return{success:!1,error:Jr("runtime-error","Unexpected properties: "+n.join(", "))}}for(const[e,n]of Object.entries(t)){const t=r[e];if(!(e in r)&&!n.t)return{success:!1,error:Jr("missing-argument",`Required field "${e}" is missing`,e)};const s=n.validate(t);if(!s.success)return{success:!1,error:Jr("validation-error",s.error.message||`Field "${e}" validation failed`,s.error.path?`${e}.${s.error.path}`:e)};void 0!==s.data&&(i[e]=s.data)}return{success:!0,data:i}}});return n.strict=()=>Yr(t,{strict:!0}),n}Xr=function(t){return t.describe||(t.describe=function(t){return this.description=t,this}),t.safeParse||(t.safeParse=function(t){const e=this.validate(t);return e.success?{success:!0,data:e.data}:{success:!1,error:{errors:e.error?[e.error]:[]}}}),t.parse||(t.parse=function(t){const e=this.validate(t);if(e.success&&void 0!==e.data)return e.data;throw Error(e.error?.message||"Validation failed")}),t.optional||(t.optional=function(){const t=this.validate.bind(this),e={...this,t:!0,validate:e=>null==e?{success:!0,data:void 0}:t(e)};return Xr(e)}),t.min||(t.min=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&t>r.data.length?{success:!1,error:Jr("runtime-error",`String must be at least ${t} characters long`)}:r}};return Xr(n)}),t.max||(t.max=function(t){const e=this.validate.bind(this),n={...this,validate:n=>{const r=e(n);return r.success&&"string"==typeof r.data&&r.data.length>t?{success:!1,error:Jr("runtime-error",`String must be at most ${t} characters long`)}:r}};return Xr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:!0,validate:n=>void 0===n?{success:!0,data:t}:e(n)};return Xr(n)}),t.rest||(t.rest=function(t){return this}),t.refine||(t.refine=function(t,e){const n=this.validate.bind(this),r={...this,validate:r=>{const i=n(r);return i.success?t(i.data)?i:{success:!1,error:Jr("runtime-error",e||"Refinement validation failed")}:i}};return Xr(r)}),new Proxy(t,{get:(t,e,n)=>e in t||"string"!=typeof e||e.startsWith("_")||"constructor"===e||"validate"===e||"then"===e?Reflect.get(t,e,n):function(...t){return n}})};const Qr=t=>function(t={}){return Kr?Gr():Xr({validate:e=>t.optional&&null==e?{success:!0,data:void 0}:"string"!=typeof e?{success:!1,error:Jr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:!1,error:Jr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:!1,error:Jr("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:Jr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:!1,error:Jr("missing-argument","String does not match required pattern")}:{success:!0,data:e},...t.description&&{description:t.description}})}(t||{}),ti=t=>Yr(t),ei=t=>function(t){return Kr?Gr():Xr({validate:e=>{if(!Array.isArray(e))return{success:!1,error:Jr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:!1,error:Jr("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const i=t[r].validate(e[r]);if(!i.success)return{success:!1,error:Jr("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:!0,data:n}}})}(t),ni=()=>Gr();class ri{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(this.ttl>=Date.now()-e.timestamp)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(),this.cache.set(t,{result:e,timestamp:Date.now(),accessCount:1}),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[n,r]of this.accessOrder)e>r&&(e=r,t=n);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,n)=>t+(e-n.timestamp),0)/t.length:0,totalAccesses:t.reduce((t,e)=>t+e.accessCount,0)}}}const ii=new class{constructor(){this.domQueryCache=new ri(200,3e3),this.exprResultCache=new ri(500,2e3),this.cssMatchCache=new ri(100,5e3),this.formValueCache=new ri(50,1e3),this.hits=0,this.misses=0}querySelector(t){const e="querySelector:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.querySelector(t);return this.domQueryCache.set(e,r),r}querySelectorAll(t){const e="querySelectorAll:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.querySelectorAll(t));return this.domQueryCache.set(e,r),r}getElementById(t){const e="getElementById:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=document.getElementById(t);return this.domQueryCache.set(e,r),r}getElementsByClassName(t){const e="getElementsByClassName:"+t,n=this.domQueryCache.get(e);if(void 0!==n)return this.hits++,n;this.misses++;const r=Array.from(document.getElementsByClassName(t));return this.domQueryCache.set(e,r),r}matches(t,e){const n=`matches:${this.getElementCacheKey(t)}:${e}`,r=this.cssMatchCache.get(n);if(void 0!==r)return this.hits++,r;this.misses++;const i=t.matches(e);return this.cssMatchCache.set(n,i),i}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),n=this.formValueCache.get("formValue:"+e);if(void 0!==n)return this.hits++,n;this.misses++}setFormValue(t,e){const n=this.getElementCacheKey(t);this.formValueCache.set("formValue:"+n,e)}invalidateElementCache(t){const e=this.getElementCacheKey(t);for(const t of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const n of Array.from(t.cache.keys()))"string"==typeof n&&n.includes(e)&&t.delete(n)}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("."),n=this.getElementPosition(t);return`${t.tagName.toLowerCase()}${e?"."+e:""}@${n}`}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(([n,r])=>{t-r.timestamp>e.ttl&&e.delete(n)})})}};"undefined"!=typeof window&&setInterval(()=>{ii.cleanup()},1e4);const si=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 n=performance.now()-e;return this.startTimes.delete(t),n}return 0}recordTokenization(t){this.metrics.tokenizationTime+=t}recordEvaluation(t){this.metrics.evaluationTime+=t}updateCacheMetrics(){const t=ii.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 oi(){ii.cleanup(),si.getMetrics().memoryUsage>52428800&&si.reset()}let ai=null;function ci(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 n=t.trim();if(""===n)return 0;const r=parseFloat(n);if(isNaN(r))throw Error(`${e} cannot be converted to number: "${t}"`);return r}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 n=t[0];if(Array.isArray(n))throw Error(e+" is a nested array, cannot convert to number");return ci(n,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 n=parseFloat(t);if(!isNaN(n))return n}}const n=t.valueOf();if("number"==typeof n&&Number.isFinite(n))return n}throw Error(`${e} cannot be converted to number: ${typeof t}`)}function li(t){if("number"==typeof t)return Number.isFinite(t)?t:null;if("string"==typeof t){const e=t.trim();if(""===e)return 0;const n=parseFloat(e);return isNaN(n)?null:n}return"boolean"==typeof t?t?1:0:null==t?0:null}function ui(t,e){if(!Number.isFinite(t)){if(Number.isNaN(t))throw Error(e+" resulted in non-finite value: NaN");throw Error(`${e} resulted in non-finite value: ${t>0?"Infinity":"-Infinity"}`)}return t}function fi(t){try{return ci(t,"_"),!0}catch{return!1}}function hi(t,e,n){if("==="===n)return t===e;if("!=="===n)return t!==e;if(null==t||null==e)return function(t,e,n){if(null==t&&null==e)switch(n){case"==":case">=":case"<=":return!0;default:return!1}switch(n){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(t,e,n);const[r,i]=function(t,e){if("number"==typeof t&&"number"==typeof e)return[t,e];if("string"==typeof t&&"string"==typeof e){const n=parseFloat(t),r=parseFloat(e);return isNaN(n)||isNaN(r)?[t,e]:[n,r]}const n=li(t),r=li(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>i;case"<":return i>r;case">=":return r>=i;case"<=":return i>=r;case"==":return di(t,e);case"!=":return!di(t,e);default:return!1}}function di(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 n=parseFloat(e);return!isNaN(n)&&t===n}if("string"==typeof t&&"number"==typeof e){const n=parseFloat(t);return!isNaN(n)&&n===e}return"boolean"==typeof t?di(t?1:0,e):"boolean"==typeof e?di(t,e?1:0):t+""==e+""}function pi(t,e=[]){return{isValid:!1,errors:t,suggestions:e}}function mi(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function yi(t,e,n,r,i,s=!0,o){return e&&"object"==typeof e&&"evaluationHistory"in e&&Array.isArray(e.evaluationHistory)&&e.evaluationHistory.push({expressionName:t.name,category:t.category,input:n,output:r,timestamp:i,duration:Date.now()-i,success:s,...void 0!==o&&{error:o}}),r}function gi(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){ai&&clearInterval(ai),ai=setInterval(oi,t)}();const vi=ei([ni(),ni()]),bi=ei([ni(),Qr()]),wi={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return yi(this,t,[e,n],e==n,r)}catch(i){throw yi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Dn(t,"equals"),inputSchema:vi,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"]}},Ei={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e===n;return r&&yi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Dn(t,"strictEquals")},xi={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!=n;return r&&yi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Dn(t,"notEquals")},ki={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,i=e!==n;return r&&yi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Dn(t,"strictNotEquals")},Si={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=hi(e,n,"<");return r&&yi(this,t,[e,n],s,i),s},validate:t=>Dn(t,"lessThan")},Ai={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=hi(e,n,"<=");return r&&yi(this,t,[e,n],s,i),s},validate:t=>Dn(t,"lessThanOrEqual")},Ti={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=hi(e,n,">");return r&&yi(this,t,[e,n],s,i),s},validate:t=>Dn(t,"greaterThan")},Ci={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=hi(e,n,">=");return r&&yi(this,t,[e,n],s,i),s},validate:t=>Dn(t,"greaterThanOrEqual")},$i={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return yi(this,t,[e,n],e&&n,r)}catch(i){throw yi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>Dn(t,"and"),inputSchema:vi,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"]}},Ni={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,i=e||n;return r&&yi(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Dn(t,"or")},Oi={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&yi(this,t,[e],r,n?Date.now():0),r},validate:t=>qn(t,1,"not","operand")},Ri={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||(Sn(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:!(e instanceof Node||e instanceof Element||!Cn(e)||0!==Object.keys(e).length)),n&&yi(this,t,[e],i,r),i},validate:t=>qn(t,1,"isEmpty","value")},ji={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let i;return i=null==e||!1===e||(Array.isArray(e)||e instanceof NodeList?0===e.length:(Sn(e),!1)),n&&yi(this,t,[e],i,r),i},validate:t=>qn(t,1,"no","value")},Li={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!await Ri.evaluate(t,e);return n&&yi(this,t,[e],i,r),i},validate:t=>qn(t,1,"isNotEmpty","value")},Mi={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=Ii(e);return n&&yi(this,t,[e],i,r),i},validate:t=>qn(t,1,"exists","value")};function Ii(t){return null!=t&&(Array.isArray(t)?t.length>0:!("undefined"!=typeof NodeList&&t instanceof NodeList)||t.length>0)}const Pi={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=!Ii(e);return n&&yi(this,t,[e],i,r),i},validate:t=>qn(t,1,"doesNotExist","value")},qi={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let s;if(e&&n){if(gi(e)&&gi(n))return s=e.contains(n),r&&yi(this,t,[e,n],s,i),s;if(Sn(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&gi(n))return s=o.contains(n),r&&yi(this,t,[e,n],s,i),s;if(o&&Sn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=!!a&&o.contains(a),r&&yi(this,t,[e,n],s,i),s}}if(Sn(n)&&n.match(/^[.#][\w-]+$/)&&gi(e)){const o=document.querySelector(n);return s=!!o&&e.contains(o),r&&yi(this,t,[e,n],s,i),s}}if(Sn(e)&&Sn(n))s=e.includes(n);else if(Array.isArray(e)||"undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e);s=t.includes(n)||n instanceof Node&&t.some(t=>t instanceof Node&&t.contains(n))}else s=!(!Cn(e)||!Sn(n))&&n in e;return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"contains","container, value")},Hi={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=!await qi.evaluate(t,e,n);return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"doesNotContain","container, value")},Bi={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=null!=e&&null!=n&&(e+"").startsWith(n+"");return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"startsWith","str, prefix")},Di={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=null!=e&&null!=n&&(e+"").endsWith(n+"");return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"endsWith","str, suffix")},Fi={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const i=t.evaluationHistory;let s=n,o=r;if(null!=s&&null!=o&&s>o){const t=s;s=o,o=t}const a=null!=s&&null!=o&&e>=s&&o>=e;return i&&yi(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>qn(t,3,"between","value, min, max")},Ui={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&Sn(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{i=function(t,e){return ii.matches(t,e)}(e,t)}catch(t){i=!1}else i=!1}else if(Sn(e)&&Sn(n)){const t=e,r=n;try{i=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){i=t.includes(r)}}else i=!1;return yi(this,t,[e,n],i,r)}catch(i){throw yi(this,t,[e,n],!1,r,!1,i instanceof Error?i:Error(i+"")),i}},validate:t=>qn(t,2,"matches","element, selector"),inputSchema:bi,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"]}},Vi={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0;let s=!1;if(e instanceof Element&&Sn(n)){const t=n;t.startsWith(".")?s=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(s=e.hasAttribute(t.slice(1,-1)))}return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"has","element, selector")},_i={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,i=r?Date.now():0,s=!await Vi.evaluate(t,e,n);return r&&yi(this,t,[e,n],s,i),s},validate:t=>qn(t,2,"doesNotHave","element, selector")},zi={equals:wi,strictEquals:Ei,notEquals:xi,strictNotEquals:ki,lessThan:Si,lessThanOrEqual:Ai,greaterThan:Ti,greaterThanOrEqual:Ci,and:$i,or:Ni,not:Oi,no:ji,isEmpty:Ri,isNotEmpty:Li,exists:Mi,doesNotExist:Pi,contains:qi,doesNotContain:Hi,startsWith:Bi,endsWith:Di,between:Fi,matches:Ui,has:Vi,doesNotHave:_i};class Wi{trackPerformance(t,e,n,r){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:e,output:n.success?n.value:n.error,timestamp:r,duration:Date.now()-r,success:n.success})}trackSimple(t,e,n,r=(n?"success":"error")){t.evaluationHistory&&t.evaluationHistory.push({expressionName:this.name,category:this.category,input:"operation",output:r,timestamp:e,duration:Date.now()-e,success:n})}toBoolean(t){return!(!1===t||0===t||0n===t||""===t||null==t||An(t)&&isNaN(t))}success(t,e){return{success:!0,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:!1,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:!1,errors:[{type:t,message:e,suggestions:n}],suggestions:n}}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":Cn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":Sn(t)?"String":An(t)?"Number":Tn(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):Sn(t)?t.split(""):null==t?[]:Cn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(An(t)&&Number.isFinite(t))return t;if(Sn(t)){const e=Number(t);return Number.isFinite(e)?e:null}return Tn(t)?t?1:0:null}}const Zi=ti({value:Qr().describe("String literal value")}).strict(),Ji=ti({value:function(t={}){return Kr?Gr():Xr({validate:e=>{const n=Number(e);return isNaN(n)?{success:!1,error:Jr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:!1,error:Jr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:!1,error:Jr("runtime-error","Number must be at most "+t.max)}:{success:!0,data:n}}})}(Gi||{}).describe("Number literal value")}).strict(),Ki=ti({value:(Kr?Gr():Xr({validate:t=>"boolean"!=typeof t?{success:!1,error:Jr("type-mismatch","Expected boolean, received "+typeof t)}:{success:!0,data:t}})).describe("Boolean literal value")}).strict(),Xi=ti({left:ni().describe("Left operand"),right:ni().describe("Right operand")}).strict();var Gi;const Yi={stringLiteral:new class extends Wi{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=Zi,this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid){const e=this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);return this.trackSimple(t,n,!1),e}let i=e.value;(i.includes("${")||i.includes("$"))&&(i=this.interpolateString(i,t));const s=this.success(i,"string");return this.trackSimple(t,n,!0,i),s}catch(e){return this.trackSimple(t,n,!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 n=t.replace(/\$\{([^}]+)\}/g,(t,n)=>{try{const t=this.resolveExpression(n.trim(),e);return void 0!==t?t+"":""}catch(t){return""}});return n=n.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(t,n)=>{try{const t=this.resolveVariable(n,e);return void 0!==t?t+"":""}catch(t){return""}}),n}resolveExpression(t,e){if(t.includes(".")){const n=t.split(".");let r=this.resolveVariable(n[0],e);for(let t=1;n.length>t&&null!=r;t++)r=r[n[t]];return r}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)?(qt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Wi{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Ji,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?Number.isFinite(e.value)?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!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 Wi{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Ki,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);return r.isValid?(this.trackSimple(t,n,!0,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,!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 Wi{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Xi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ci(e.left,"left operand")+ci(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!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 Wi{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=Xi,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",r.suggestions);const i=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,!0,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,!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=Xi.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(Sn(t))return t;if(An(t))return""+t;if(Tn(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Wi{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Xi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return this.trackSimple(t,n,!1),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ci(e.left,"left operand")*ci(e.right,"right operand");return this.trackSimple(t,n,!0,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,!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"])}}}},Qi={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(t,e){const n=void 0!==e?e:t.it;return null==n?null:Array.isArray(n)||n instanceof NodeList||n instanceof HTMLCollection?n.length>0?n[0]:null:n instanceof Element?n.children.length>0?n.children[0]:null:Sn(n)?n.length>0?n[0]:null:Cn(n)&&"length"in n&&An(n.length)&&n.length>0?n[0]:null},validate:t=>Un(t,1,"first","collection")},ts={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(t,e){const n=void 0!==e?e:t.it;if(null==n)return null;if(Array.isArray(n))return n.length>0?n[n.length-1]:null;if(n instanceof NodeList||n instanceof HTMLCollection)return n.length>0?n[n.length-1]:null;if(n instanceof Element){const t=n.children;return t.length>0?t[t.length-1]:null}return Sn(n)?n.length>0?n[n.length-1]:null:Cn(n)&&"length"in n&&An(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Un(t,1,"last","collection")},es={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!An(n))throw Error("Index must be a number");const i=n,s=void 0!==r?r:t.it;if(null==s)return null;if(Array.isArray(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(s instanceof NodeList||s instanceof HTMLCollection){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(s instanceof Element){const t=s.children,e=0>i?t.length+i:i;return e>=0&&t.length>e?t[e]:null}if(Sn(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(Cn(s)&&"length"in s&&An(s.length)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}return null},validate:t=>Vn(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function ns(t,e){let n=t.nextElementSibling;for(;n;){if(n.matches(e))return n;const t=n.querySelector(e);if(t)return t;n=n.nextElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?ns(r,e):null}function rs(t,e){let n=t.previousElementSibling;for(;n;){const t=Array.from(n.querySelectorAll(e)).reverse();if(t.length>0)return t[0];if(n.matches(e))return n;n=n.previousElementSibling}const r=t.parentElement;return r&&r!==document.documentElement?rs(r,e):null}function is(t,e,n,r){if(n.inSearch){if(null==n.inElt)return;return function(t,e,n,r){const i=Array.from(e??[]),s=[];for(const e of i)(e.matches&&e.matches(n)||e===t)&&s.push(e);for(let e=0;s.length-1>e;e++)if(s[e]===t)return s[e+1];if(r){const t=s[0];if(t&&t.matches&&t.matches(n))return t}}(t,r?Array.from(n.inElt):Array.from(n.inElt).reverse(),e,!!n.wrapping)}const i=n.within??("undefined"!=typeof document?document.body:null);if(i)return r?function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=0;i.length>e;e++){const n=i[e];if(2===n.compareDocumentPosition(t))return n}return r?i[0]:void 0}(t,i,e,!!n.wrapping):function(t,e,n,r){const i=e.querySelectorAll(n);for(let e=i.length-1;e>=0;e--){const n=i[e];if(4===n.compareDocumentPosition(t))return n}return r?i[i.length-1]:void 0}(t,i,e,!!n.wrapping)}function ss(t){let e=0,n=t;for(;n&&n.parentElement;)e+=Array.from(n.parentElement.children).indexOf(n),n=n.parentElement,e+=1e3;return e}const os={first:Qi,last:ts,at:es,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r,i]=e,s=r||t.me;return s&&s instanceof Element?n?i?is(s,n,i,!0):ns(s,n):s.nextElementSibling:null},validate:t=>Un(t,3,"next","optional selector, optional fromElement, optional modifiers")||(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[n,r,i]=e,s=r||t.me;return s&&s instanceof Element?n?i?is(s,n,i,!1):rs(s,n):s.previousElementSibling:null},validate:t=>Un(t,3,"previous","optional selector, optional fromElement, optional modifiers")||(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[n,r,i]=e,s=i||t.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=ss(t);for(const t of r)if(ss(t)>i)return t;return null}(s,n,o):null},validate:t=>Vn(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[n,r,i]=e,s=i||t.me;if(!(s&&s instanceof Element))return null;const o=s.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),i=ss(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>ss(e))return e}return null}(s,n,o):null},validate:t=>Vn(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")}};function as(){return zr(Zr,zi,Yi,Kn,os)}class cs{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 n=dn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function ls(t,e,n,r,i,s){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,f=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,d=n.length-1;d>=0;d--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(t){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(t||null))};var y=(0,n[d])("accessor"===c?{get:f.get,set:f.set}:f[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))&&(f.get=a),(a=o(y.set))&&(f.set=a),(a=o(y.init))&&i.unshift(a)}else(a=o(y))&&("field"===c?i.unshift(a):f[l]=a)}u&&Object.defineProperty(u,r.name,f),h=!0}function us(t,e,n){for(var r=arguments.length>2,i=0;e.length>i;i++)n=r?e[i].call(t,n):e[i].call(t);return r?n:void 0}function fs(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}function hs(t){const e=t.trim();return!(!e.startsWith("[@")||!e.endsWith("]"))||!!e.startsWith("@")}function ds(t){const e=t.trim();if(e.startsWith("[@")&&e.endsWith("]")){const t=e.slice(2,-1),n=t.indexOf("=");if(-1===n)return{name:t.trim()};const r=t.slice(0,n).trim();let i=t.slice(n+1).trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),{name:r,value:i}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function ps(t,e){for(const n of t)e(n);return t}function ms(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function ys(t,e,n){const r=t.hasAttribute(e);void 0!==n?r&&t.getAttribute(e)===n?t.removeAttribute(e):t.setAttribute(e,n):r?t.removeAttribute(e):t.setAttribute(e,"")}function gs(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&&bs(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&&bs(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&bs(n)?[n]:[]}function vs(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function bs(t){if(!t||0===t.trim().length)return!1;const e=t.trim();return!!vs(e)||/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function ws(t,e){return t.map(t=>{if(vs(t)){const n=function(t){const e=t.trim(),n=e.match(/^\{(.+)\}$/);return n?n[1].trim():e}(t),r=e.locals.get(n)??e.globals.get(n);return null!=r?r+"":(ft(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function Es(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:!1,enumerable:!0})}}function xs(t){return{...t}}function ks(t){return()=>new t}function Ss(t,e){return e}function As(t,e,n){if(pn(t))return t;if(!t){const t=e.me;if(!t)throw Error(Ss(0,"No target element \u2014 provide explicit target or ensure context.me is set"));return Cs(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(Ss(0,'Context reference "me" is not available'));return Cs(e.me)}if("it"===n){if(!pn(e.it))throw Error(Ss(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(Ss(0,'Context reference "you" is not available'));return Cs(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(Ss(0,"DOM not available \u2014 cannot resolve element selector"));const i=r.querySelector(n);if(!i)throw Error(Ss(0,"Element not found with selector: "+n));if(!pn(i))throw Error(Ss(0,"Element found but is not an HTMLElement: "+n));return i}throw Error(Ss(0,"Invalid target type: "+typeof t))}function Ts(t,e){if(Array.isArray(t))return t.filter(pn);if(yn(t))return Array.from(t).filter(pn);if(pn(t))return[t];if(!t){const t=e.me;return t&&pn(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&pn(e.me)?[e.me]:[];if("it"===n)return pn(e.it)?[e.it]:[];if("you"===n)return e.you&&pn(e.you)?[e.you]:[];const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(r){let t=n;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=r.querySelectorAll(t);return Array.from(e).filter(pn)}}return[]}function Cs(t){if(pn(t))return t;throw Error("Value is not an HTMLElement")}function $s(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(Ss(0,'No "me" element in context'));if(!pn(e.me))throw Error(Ss(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(Ss(0,'No "it" value in context'));if(!pn(e.it))throw Error(Ss(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(Ss(0,'No "you" element in context'));if(!pn(e.you))throw Error(Ss(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(Ss(0,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const Ns=["on","from","to","in","with","at"];async function Os(t,e,n,r,i={},s){let o=t;if(i.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"!==e?.type||"string"!=typeof e.name||!Ns.includes(e.name.toLowerCase())})),(!o||0===o.length)&&i.fallbackModifierKey&&s){const t=s[i.fallbackModifierKey];t&&(o=[t])}if(!o||0===o.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!pn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of o){const i=await e.evaluate(t,n);if(""!==i&&("string"!=typeof i||""!==i.trim()))if(pn(i))a.push(i);else if(yn(i)){const t=Array.from(i).filter(pn);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(pn);a.push(...t)}else{if("string"!=typeof i){if(null==i)continue;throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof i}`)}try{let t=i;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),s=Array.from(r).filter(pn);a.push(...s)}catch(t){throw Error(`Invalid CSS selector: "${i}" - ${t instanceof Error?t.message:t+""}`)}}}if(0===a.length){if(!n.me)throw Error(r+" command: no target specified and context.me is null");if(!pn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function Rs(t){return"string"==typeof t&&t.trim().startsWith("*")}function js(t){const e=function(t){const e=t.trim();if(!e.startsWith("*"))return null;const n=e.substring(1).trim();return n?{property:n}:null}(t);if(!e)return null;const n=e.property.toLowerCase();return["display","visibility","opacity"].includes(n)?n:null}function Ls(t,e,n){t.style.setProperty(e,n)}const Ms=["dialog","details","summary","select"];function Is(t){return t&&"object"==typeof t?"string"==typeof t.selector?t.selector:"string"==typeof t.value?t.value:"string"==typeof t.name?t.name:null:null}async function Ps(t,e,n){return function(t){if(!t||"object"!=typeof t)return!1;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return!1;const n=Is(t);return"string"==typeof n&&n.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 n=Is(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:Is(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=Is(t);return"string"==typeof e&&e.startsWith("@")}return!1}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:Is(r)),extractedFromNode:!0}:{value:await e.evaluate(t,n),extractedFromNode:!1};var r}class qs{async resolveTargets(t,e,n,r){return Os(t,e,n,this.mode,{filterPrepositions:!0,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return Ps(t,e,n)}parseClassNames(t){return gs(t)}isAttribute(t){return hs(t.trim())}isCSSProperty(t){return Rs(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>pn(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 Hs=(()=>{let t,e,n=[Es({name:"add"})],r=[],i=qs;var s=e=class extends i{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return s.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("add command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if("object"==typeof r&&null!==r&&!Array.isArray(r))return{type:"styles",styles:r,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i)){const{name:r,value:s}=function(t){const e=ds(t);return{name:e.name,value:e.value??""}}(i);return{type:"attribute",name:r,value:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(i)){const r=i.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const s=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:s+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const i=this.parseClassNames(r);if(0===i.length)throw Error("add command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=ws(t.classes,e);n.length>0&&ms(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,ps(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":!function(t,e){ms(t,Object.entries(e),(t,[e,n])=>{t.style.setProperty(e,n)})}(t.targets,t.styles)}var n,r}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 n=e.styles;if(0===Object.keys(n).length)return!1;if(!Object.values(n).every(t=>"string"==typeof t))return!1}return!0}};return fs(e,"AddCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=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"],category:"dom",compatibility:"standard"}),us(e,r),s=e})();const Bs=ks(Hs),Ds={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function Fs(t){const e=Ds[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(Ds).join(", ")}.`);return e}function Us(t){return t.includes("<")&&t.includes(">")}function Vs(t,e,n){!function(t,e,n){"replace"!==n?mn(e)?function(t,e,n){switch(n){case"beforebegin":t.parentElement?.insertBefore(e,t);break;case"afterbegin":t.insertBefore(e,t.firstChild);break;case"beforeend":t.appendChild(e);break;case"afterend":t.parentElement?.insertBefore(e,t.nextSibling)}}(t,e,n):function(t,e,n){const r=n,i=["beforebegin","afterbegin","beforeend","afterend"];if(!i.includes(r))throw Error(`Invalid insert position '${n}'. Expected one of ${i.join(", ")} (or 'replace').`);Us(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){mn(e)?(t.innerHTML="",t.appendChild(e)):Us(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,Fs(n))}function _s(t,e,n){const r=t;if("function"==typeof r.moveBefore&&e.isConnected&&t.isConnected)try{return void r.moveBefore(e,n)}catch{}t.insertBefore(e,n)}function zs(t,e,n){switch(n){case"beforeend":for(const n of e)_s(t,n,null);break;case"afterbegin":for(let n=e.length-1;n>=0;n--)_s(t,e[n],t.firstChild);break;case"beforebegin":{const n=t.parentElement;if(!n)return;for(const r of e)_s(n,r,t);break}case"afterend":{const n=t.parentElement;if(!n)return;for(let r=e.length-1;r>=0;r--)_s(n,e[r],t.nextSibling);break}case"replace":t.innerHTML="";for(const n of e)_s(t,n,null)}}function Ws(t){return!!t.parentNode&&(t.remove(),!0)}let Zs=(()=>{let t,e,n=[Es({name:"remove"})],r=[],i=qs;var s=e=class extends i{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return s.metadata}async parseInput(t,e,n){if(!t.args||0===t.args.length)throw Error("remove command requires an argument");const{value:r}=await this.evaluateFirst(t.args[0],e,n);if(pn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&pn(r[0]))return{type:"element",targets:r.filter(t=>pn(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:ds(i).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(i))return{type:"styles",properties:[i.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const i=this.parseClassNames(r);if(0===i.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=ws(t.classes,e);n.length>0&&ms(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,ps(t.targets,t=>{t.removeAttribute(n)});break;case"styles":!function(t,e){ms(t,e,(t,e)=>{t.style.removeProperty(e)})}(t.targets,t.properties);break;case"element":for(const e of t.targets)Ws(e)}var n}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}};return fs(e,"RemoveCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=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"],category:"dom",compatibility:"standard"}),us(e,r),s=e})();const Js=ks(Zs);function Ks(t){const e=t.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!e)return null;const n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();return"ms"===r||"millisecond"===r||"milliseconds"===r?{number:n,milliseconds:Math.floor(n)}:"s"===r||"sec"===r||"second"===r||"seconds"===r?{number:n,milliseconds:Math.floor(1e3*n)}:null}function Xs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Ks(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Gs(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Ys(t){return"DIALOG"===t.tagName}function Qs(t){return"DETAILS"===t.tagName}function to(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&ys(t,n)}}function eo(t,e,n,r){const i=to(t,e,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function no(t,e,n,r){const i=to(t,e,n),s=()=>{i(),t.removeEventListener(r,s)};return t.addEventListener(r,s,{once:!0}),()=>{t.removeEventListener(r,s)}}function ro(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(!1===n?t.removeAttribute(r):t.setAttribute(r,!0===n?"":n+""))}const r=n+"";switch(e){case"textContent":return void(t.textContent=r);case"innerHTML":return void(t.innerHTML=r);case"innerText":return void(t.innerText=r);case"id":return void(t.id=r);case"className":return void(t.className=r);case"value":return void("value"in t&&(t.value=r));case"checked":return void("checked"in t&&(t.checked=!!n))}if(e.includes(".")){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++)if(i=i[r[t]],null==i)return;return void(i[r[r.length-1]]=n)}if(e.includes("-")||e in t.style)t.style.setProperty(e,r);else try{t[e]=n}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 io=/^the\s+(.+?)\s+of\s+(.+)$/i,so=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 oo(t){return"string"==typeof t&&io.test(t)}function ao(t,e){const n=t.match(io);if(!n)return null;try{return{element:As(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function co(t,e,n){if(function(t){return!(!t||"object"!=typeof t)&&"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property}(t))return async function(t,e,n){const r=t.property?.name;if(!r)return null;let i=await e.evaluate(t.target,n);return Array.isArray(i)&&(i=i[0]),pn(i)?{element:i,property:r}:null}(t,e,n);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,n){const r="string"==typeof t.property?t.property:t.property?.name;if(!r)return null;let i=await e.evaluate(t.object,n);return Array.isArray(i)&&(i=i[0]),pn(i)?{element:i,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,i=r.property;let s=await e.evaluate(t,n);if(Array.isArray(s)&&(s=s[0]),!pn(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function lo(t,e){const{element:n,property:r}=t;r.startsWith("*")?Ls(n,r.substring(1),e+""):ro(n,r,e)}async function uo(t,e,n){let r,i;if(t?.for){const i=await e.evaluate(t.for,n);r="number"==typeof i?i:"string"==typeof i?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=Ks(t);return n?n.milliseconds:e}return e}(i):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(i=r)}return{duration:r,untilEvent:i}}function fo(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return!1;if("identifier"!==t.type)return!1;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.includes(e)}(e)}(e);if(pn(t)||Array.isArray(t)&&t.every(t=>pn(t)))return{type:"element",expression:""};if(r&&n)return{type:"element",expression:n};if("string"==typeof t){const e=t.trim();return e.startsWith("@")||e.startsWith("[@")?{type:"attribute",expression:e}:e.startsWith("*")?{type:"css-property",expression:e}:e.startsWith(".")?{type:"class",expression:e}:e.startsWith("#")||function(t){if("string"!=typeof t)return!1;const e=t.toLowerCase();return Ms.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}const ho=ks((()=>{let t,e,n=[Es({name:"toggle"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");let r=!1;if(function(t){if(!t||"asExpression"!==t.type)return!1;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=!0;const e=t.args[0].expression;t={...t,args:[e,...t.args.slice(1)]}}const i=t.args[0],s=i?.name;if("between"===s&&t.args.length>=4){const{duration:r,untilEvent:i}=await uo(t.modifiers,e,n),s=async t=>{const r=t;return"selector"===r?.type?r.value:e.evaluate(t,n)},o=await s(t.args[1]),a=await s(t.args[3]),c=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&c.push(t.args[e])}const l={filterPrepositions:!0,fallbackModifierKey:"on"},u=await Os(c,e,n,"toggle",l,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:u,duration:r,untilEvent:i}}const o=await co(i,e,n);if(o)return{type:"property",target:o};if("selector"===i.type&&"string"==typeof i.value&&i.value.startsWith("*")){let r=i.value,s=1;if("*"===r&&t.args.length>1&&"identifier"===t.args[1].type&&(r="*"+t.args[1].name,s=2),"*"===r&&t.modifiers?.on){const i=t.modifiers.on?.name;if(i&&["display","visibility","opacity"].includes(i)){r="*"+i;const{duration:s,untilEvent:o}=await uo(t.modifiers,e,n),a=js(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:s,untilEvent:o}}}}const o=js(r);if(o){const{duration:r,untilEvent:i}=await uo(t.modifiers,e,n),a={filterPrepositions:!0,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Os(t.args.slice(s),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await uo(t.modifiers,e,n),{value:l}=await Ps(i,e,n);if(oo(l)){const t=ao(l,n);if(t)return{type:"property",target:t}}const{type:u,expression:f}=fo(l,i),h={filterPrepositions:!0,fallbackModifierKey:"on"};switch(u){case"attribute":{const{name:r,value:i}=ds(f);return{type:"attribute",name:r,value:i,targets:await Os(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=js(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await Os(t.args.slice(1),e,n,"toggle",h,t.modifiers)}}case"element":{let s;if(pn(l))s=[l];else if(Array.isArray(l)&&l.every(t=>pn(t)))s=l;else if(f){const t=document.querySelectorAll(f);s=Array.from(t).filter(t=>pn(t))}else s=await Os([i],e,n,"toggle",h,t.modifiers);const o=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"===o){const i=r?"modal":await async function(t,e,n,r){if(e?.as){const t=await n.evaluate(e.as,r);if("string"==typeof t&&"modal"===t.toLowerCase())return"modal"}if(t.length>=2){const e=await n.evaluate(t[1],r);if("string"==typeof e){const i=e.toLowerCase();if("modal"===i||"as modal"===i)return"modal";if("as"===i&&t.length>=3){const e=await n.evaluate(t[2],r);if("string"==typeof e&&"modal"===e.toLowerCase())return"modal"}}}return"non-modal"}(t.args,t.modifiers,e,n);return{type:"dialog",mode:i,targets:s}}return"details"===o?{type:"details",targets:Gs(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:gs(f),targets:s,duration:a,untilEvent:c}}default:{const r=gs(f||l);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Os(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}}}async execute(t,e){switch(t.type){case"classes":{const n=ws(t.classes,e);if(0===n.length)return[...t.targets];if(ms(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&eo(e,"class",n[0],t.duration),t.untilEvent&&no(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,ps(t.targets,t=>{ys(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&eo(e,"attribute",t.name,t.duration),t.untilEvent&&no(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return ps(t.targets,e=>function(t,e){const n=window.getComputedStyle(t);switch(e){case"display":"none"===n.display?(t.style.display=t.dataset.previousDisplay||"block",delete t.dataset.previousDisplay):(t.dataset.previousDisplay=n.display,t.style.display="none");break;case"visibility":t.style.visibility="hidden"===n.visibility?"visible":"hidden";break;case"opacity":t.style.opacity=0===parseFloat(n.opacity)?"1":"0"}}(e,t.property));case"property":return function(t){const e=function(t){const{element:e,property:n}=t;return n.startsWith("*")?function(t,e){return window.getComputedStyle(t).getPropertyValue(e)}(e,n.substring(1)):In(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||so.has(r)||so.has(r.toLowerCase())){const n=!e;return lo(t,n),n}if("number"==typeof e){const n=0===e?1:0;return lo(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(lo(t,i),i):(t.element[r]=e,lo(t,""),"")}lo(t,!e)}(t.target),[t.target.element];case"dialog":return ps(t.targets,e=>{return r=t.mode,void((n=e).open?n.close():"modal"===r?n.showModal():n.show());var n,r});case"details":return ps(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return ps(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 n=e.classList.contains(t.classA),r=e.classList.contains(t.classB);n?(e.classList.remove(t.classA),e.classList.add(t.classB)):r?(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&&eo(e,"class",t.classA,t.duration),t.untilEvent&&no(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return fs(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"dom",compatibility:"standard"}),us(e,r),i=e})());class po{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await Os(t.args,e,n,r)}}(t,e,n,this.mode);return{targets:r,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=>pn(t))||"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay)}showElement(t,e="block"){const n=t.dataset.originalDisplay;void 0!==n?(t.style.display=n||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 mo=(()=>{let t,e,n=[Es({name:"show"})],r=[],i=po;var s=e=class extends i{constructor(){super(...arguments),this.mode="show"}get metadata(){return s.metadata}async execute(t,e){const n=t.defaultDisplay||"block";for(const e of t.targets)this.showElement(e,n)}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&!!e.targets.every(t=>pn(t))&&"string"==typeof e.defaultDisplay}};return fs(e,"ShowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=xs({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),s=e})();const yo=ks(mo);let go=(()=>{let t,e,n=[Es({name:"hide"})],r=[],i=po;var s=e=class extends i{constructor(){super(...arguments),this.mode="hide"}get metadata(){return s.metadata}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=>pn(t))}};return fs(e,"HideCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:o},null,r),s=e=t.value,o&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:o})})(),e.metadata=xs({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),s=e})();const vo=ks(go);const bo=ks((()=>{let t,e,n=[Es({name:"put"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",i=["into","before","after","at","at start of","at end of"];let s=-1,o=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&i.includes(c)){s=e,o=c;break}}let a=null,c=null;if(-1===s){const e=i.find(e=>t.modifiers[e]);if(e)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,s)[0]||null,c=t.args.slice(s+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(o);let f,h,d=null;if(c){const t=r(c),i=await co(c,e,n);if(i)return{value:l,targets:[i.element],position:"into",memberPath:i.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const i=t.name;if("my"===i||"me"===i||"I"===i){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"into",memberPath:r.name}}else if("its"===i||"it"===i){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}else d=i}if(d&&r?.name)f=r.name;else if(!d&&!f){const t=await e.evaluate(c,n);"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&&oo(t)){const e=ao(t,n);if(e)return{value:l,targets:[e.element],position:"into",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:h=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const r=xn(await e.evaluate(c,n));if(r)return{value:l,targets:r,position:u,memberPath:f};h=t}}else{const t=await e.evaluate(c,n),r=xn(t);if(r)return{value:l,targets:r,position:u,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?d=t:h=t)}}return h?{value:l,targets:[],position:u,memberPath:f,variableName:h}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:f}}async execute(t,e){const{value:n,targets:r,position:i,memberPath:s,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,n),e[o]=n,void Object.assign(e,{it:n});if(s)for(const t of r)this.setProperty(t,s,n);else for(const t of r){const e=this.parseValue(n);Array.isArray(e)?zs(t,e,Fs(i)):Vs(t,e,i)}return r}mapPosition(t){switch(t){case"into":return"into";case"before":return"before";case"after":return"after";case"at start of":return"prepend";case"at end of":return"append";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!pn(e.me))throw Error("put: no target and context.me is null");return[e.me]}return function(t){if("undefined"==typeof document)throw Error("DOM not available");const e=Array.from(document.querySelectorAll(t)).filter(t=>pn(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}(t)}parseValue(t){return pn(t)||Array.isArray(t)&&t.length>0&&t.every(pn)||mn(t)?t:null==t?"":t+""}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,n){const r=e.split(".");let i=t;for(let t=0;r.length-1>t;t++){if(!i[r[t]])throw Error(`Property path "${e}" does not exist`);i=i[r[t]]}i[r[r.length-1]]=n}};return fs(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"dom",compatibility:"standard"}),us(e,r),i=e})()),wo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Eo(t){return t.replace(/[&<>"']/g,t=>wo[t])}let xo=(()=>{let t,e,n=[Es({name:"make"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.modifiers.an??t.modifiers.a??t.args[0];if(!r)throw Error("Make command requires class name or DOM element expression");const i=r.raw;let s="string"==typeof i&&i.startsWith("<")?i:await e.evaluate(r,n);if(null==s)throw Error("Make command requires class name or DOM element expression");"string"==typeof s&&s.startsWith("<")&&(s=await async function(t,e){if(!t.includes("{"))return t;const n=/\{([^{}]+)\}/g,r=[];let i;for(;null!==(i=n.exec(t));){let t=i[0];try{const n=await ar(i[1].trim(),e);null!=n&&(t=Eo(n+""))}catch{}r.push({index:i.index,length:i[0].length,text:t})}let s=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,text:i}=r[t];s=s.slice(0,e)+i+s.slice(e+n)}return s}(s,n));const o=void 0!==t.modifiers.an?"an":"a",a=await async function(t,e,n){if(!t)return[];if("arrayLiteral"===t.type&&Array.isArray(t.args)){const r=[];for(const i of t.args)r.push(await e.evaluate(i,n));return r}const r=await e.evaluate(t,n);return Array.isArray(r)?r:[r]}(t.modifiers.from,e,n),c=await async function(t,e,n){if(!t)return;if(("symbol"===t.type||"identifier"===t.type)&&"string"==typeof t.name)return t.name;const r=await e.evaluate(t,n);return"string"==typeof r?r:void 0}(t.modifiers.called,e,n);return{article:o,expression:s,constructorArgs:a,variableName:c}}async execute(t,e){const{expression:n,constructorArgs:r=[],variableName:i}=t,s="string"==typeof n&&n.startsWith("<"),o=s&&n.endsWith("/>")?function(t){const e=t.slice(1,-2);let n="div",r=e;const i=e.match(/^([a-zA-Z][a-zA-Z0-9]*)/);i&&(n=i[1],r=e.slice(i[0].length));const s=document.createElement(n),o=r.split(/(?=[.#])/);for(const t of o)if(t.startsWith("#")){const e=t.slice(1);e&&(s.id=e)}else if(t.startsWith(".")){const e=t.slice(1);e&&s.classList.add(e)}return s}(n):s&&/<\/[a-zA-Z]/.test(n)?function(t){const e=document.createElement("template");e.innerHTML=t.trim();const n=e.content.firstElementChild;if(n&&pn(n))return n;const r=document.createElement("div");r.innerHTML=t.trim();const i=r.firstElementChild;return i&&pn(i)?i:r}(n):function(t,e,n){if(pn(t))return t;const r=t+"";let i;if("undefined"!=typeof window&&(i=window[r]),i||"undefined"==typeof global||(i=global[r]),!i&&n.variables?.has(r)&&(i=n.variables.get(r)),!i||"function"!=typeof i)throw Error(`Constructor '${r}' not found or is not a function`);return 0===e.length?new i:new i(...e)}(n,r,e);return Object.assign(e,{it:o}),i&&bn(i,o,e),o}};return fs(e,"MakeCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"dom",compatibility:"standard"}),us(e,r),i=e})();const ko=ks(xo),So=ks((()=>{let t,e,n=[Es({name:"empty"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Os(t.args,e,n,"empty",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.innerHTML=""}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"EmptyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),i=e})());function Ao(t){if("string"!=typeof t)return;const e=t.toLowerCase().trim();return"non-modal"===e||"nonmodal"===e?"non-modal":"modal"===e?"modal":void 0}function To(t){return t.hasAttribute("popover")}const Co=ks((()=>{let t,e,n=[Es({name:"open"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=(t.args??[]).filter(t=>{const e=t;if("identifier"!==e?.type)return!0;const n=e.name?.toLowerCase();return"as"!==n&&"modal"!==n&&"non-modal"!==n&&"nonmodal"!==n}),i=Gs(await Os(r,e,n,"open",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)),s=await async function(t,e,n,r){if(e?.as){const t=Ao(await n.evaluate(e.as,r));if(t)return t}for(const e of t){const t=e;if("asExpression"!==t?.type)continue;const n=t.targetType,r=Ao(n?.name??n?.value);if(r)return r}for(let e=0;t.length-1>e;e++){const i=t[e];if("identifier"===i?.type&&"as"===i.name?.toLowerCase()){const i=await n.evaluate(t[e+1],r);if("string"==typeof i){const t=i.toLowerCase().trim();if("non-modal"===t||"nonmodal"===t)return"non-modal";if("modal"===t)return"modal"}}}return"modal"}(t.args??[],t.modifiers??{},e,n);return{targets:i,dialogMode:s}}async execute(t,e){for(const e of t.targets)if(Ys(e))e.open||("modal"===t.dialogMode?e.showModal():e.show());else if(Qs(e))e.open=!0;else if(To(e)){const t=e;if("function"==typeof t.showPopover)try{t.showPopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!(!Array.isArray(e.targets)||!e.targets.every(t=>pn(t))||"modal"!==e.dialogMode&&"non-modal"!==e.dialogMode)}};return fs(e,"OpenCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),i=e})());function $o(t){return t.hasAttribute("popover")}const No=ks((()=>{let t,e,n=[Es({name:"close"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:Gs(await Os(t.args,e,n,"close",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers))}}async execute(t,e){for(const e of t.targets)if(Ys(e))e.open&&e.close();else if(Qs(e))e.open=!1;else if($o(e)){const t=e;if("function"==typeof t.hidePopover)try{t.hidePopover()}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"CloseCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),i=e})());function Oo(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e}const Ro=ks((()=>{let t,e,n=[Es({name:"select"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Os(t.args,e,n,"select",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if(0!==t.targets.length)for(const e of t.targets){if(Oo(e)){e.select();continue}const t=e.ownerDocument??("undefined"!=typeof document?document:null),n=t?.defaultView;if(!t||!n)continue;const r=n.getSelection?.();if(r)try{const n=t.createRange();n.selectNodeContents(e),r.removeAllRanges(),r.addRange(n)}catch{}}}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"SelectCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),i=e})());function jo(t){return"FORM"===t.tagName}const Lo=ks((()=>{let t,e,n=[Es({name:"reset"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Os(t.args,e,n,"reset",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)jo(e)&&e.reset()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"ResetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),us(e,r),i=e})()),Mo=ks((()=>{let t,e,n=[Es({name:"focus"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Os(t.args,e,n,"focus",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.focus()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"FocusCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),us(e,r),i=e})()),Io=ks((()=>{let t,e,n=[Es({name:"blur"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{targets:await Os(t.args,e,n,"blur",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){for(const e of t.targets)e.blur()}validate(t){if("object"!=typeof t||null===t)return!1;const e=t;return!!Array.isArray(e.targets)&&e.targets.every(t=>pn(t))}};return fs(e,"BlurCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),us(e,r),i=e})());async function Po(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return pn(i)?i:null}const qo=ks((()=>{let t,e,n=[Es({name:"set"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],i=r?.name||r?.value,s=r?.scope,o=await async function(t,e,n,r){if(!t)return null;const i=t,s=i.type;if(s){const e=Mt(s);if(e)return{kind:"node-write",node:t,writer:e}}if(r.selectorSource&&"selector"===s&&"string"==typeof i.value)return{kind:"selector",selector:i.value};const o=await async function(t,e,n,r){const i=t;if("attributeAccess"===i?.type)return{elements:await r(),name:i.attributeName};if("binaryExpression"===i?.type&&"of"===i.operator&&"attributeAccess"===i.left?.type){const t=await Po(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await Po(i.object,e,n);if(t)return{elements:[t],name:i.property.attributeName}}return null}(t,e,n,r.scopeElements);if(o)return{kind:"attribute",elements:o.elements,name:o.name};const a=await co(t,e,n);if(a)return a.property.startsWith("*")?{kind:"style",element:a.element,property:a.property.substring(1)}:{kind:"property",target:a};if(r.bareReference&&("identifier"===s||"variable"===s||"symbol"===s)&&"string"==typeof i.name){const t=i.scope;return{kind:"variable",name:i.name,scope:"element"===t||"global"===t?t:void 0}}return null}(r,e,n,{scopeElements:()=>this.resolveTargets(t.modifiers.on,e,n)});if(o)return function(t,e){switch(t.kind){case"node-write":return{type:"node-write",node:t.node,value:e,writer:t.writer};case"attribute":return{type:"attribute",elements:t.elements,name:t.name,value:e};case"style":return{type:"style",element:t.element,property:t.property,value:e+""};case"property":return{type:"property",element:t.target.element,property:t.target.property,value:e};default:throw Error(`set: unrequested write-target rung '${t.kind}'`)}}(o,await this.extractValue(t,e,n));if("memberExpression"===r?.type||"propertyAccess"===r?.type){const i=await this.tryParseMemberExpression(r,t,e,n);if(i)return i}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof i?await e.evaluate(r,n):i,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return!1;if(pn(t)||t instanceof Node)return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}(a))return{type:"object-literal",properties:a,targets:await this.resolveTargets(t.modifiers.on,e,n)};if(oo(a)){const r=ao(a,n);if(r){const i=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:i}}return this.parseTheXofY(a,t,e,n)}if("string"==typeof a&&Rs(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:i+""}}if("string"==typeof a&&hs(a)){const r=a.substring(1).trim(),i=await this.extractValue(t,e,n);return{type:"attribute",elements:await this.resolveTargets(t.modifiers.on,e,n),name:r,value:i}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const i=$s(r[1],n),s=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:s}}}if(pn(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&pn(a[0])){const r=await this.extractValue(t,e,n);return{type:"property",element:a[0],property:"textContent",value:r}}if("string"!=typeof a)throw Error("set command target must be a string or object literal"+("memberExpression"===r?.type||"propertyAccess"===r?.type?` (a property chain evaluated to ${null===a?"null":typeof a} \u2014 check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(t,e,n),scope:"element"===s||"global"===s?s:void 0}}async execute(t,e){switch(t.type){case"variable":return"element"===t.scope?hn(e,t.name,t.value):"global"===t.scope?bn(t.name,t.value,e,"global"):bn(t.name,t.value,e),"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":for(const e of t.elements)e.setAttribute(t.name,t.value+"");return Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return ro(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Ls(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[n,r]of Object.entries(t.properties))ro(e,n,r);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"};case"node-write":return await t.writer(t.node,t.value,e),Object.assign(e,{it:t.value}),{target:t.node.name??"",value:t.value,targetType:"variable"};default:throw Error("Unknown input type: "+t.type)}}async tryParseMemberExpression(t,e,n,r){const i=t.object,s=t.property;if(i?.name&&s?.name){const t=i.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const i=$s(t,r),o=await this.extractValue(e,n,r);return{type:"property",element:i,property:s.name,value:o}}}const o=t.object,a=t.computed;if(o){const i=o;let c;if("memberExpression"===i.type&&!i.computed&&"style"===i.property?.name&&i.object){const t=await n.evaluate(i.object,r);c=(t&&"object"==typeof t&&"style"in t?t.style:void 0)??await n.evaluate(o,r)}else c=await n.evaluate(o,r);if(null!=c&&"object"==typeof c){const i=a?await n.evaluate(t.property,r)+"":s?.name||"";if(i)return{type:"member-assignment",container:c,property:i,value:await this.extractValue(e,n,r)}}}return null}async extractValue(t,e,n){if(t.modifiers.to)return e.evaluate(t.modifiers.to,n);const r=t.args.findIndex(t=>"identifier"===t.type&&"to"===t.name);if(r>=0&&t.args.length>r+1)return e.evaluate(t.args[r+1],n);if(t.args.length>=2)return e.evaluate(t.args[1],n);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(t,e,n){return As(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return Ts(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const i=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!i)throw Error('Invalid "the X of Y" syntax');const[,s,o]=i,a=As(o,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:s.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&&Array.isArray(e.elements)&&e.elements.every(pn)&&"value"in e;case"property":return"string"==typeof e.property&&pn(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&pn(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}}};return fs(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"data",compatibility:"standard"}),us(e,r),i=e})());function Ho(t){return t&&"object"==typeof t&&t.type||"unknown"}let Bo=(()=>{let t,e,n=[Es({name:"increment"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="decrement"===t.commandName?.toLowerCase()?"decrement":"increment",i=await async function(t,e,n,r){if(!t.args||0===t.args.length)throw Error(r+" command requires a target");const i=t.args[0];let s,o,a;const c=Ho(i);if("identifier"===c)s=i.name,i.scope&&(o=i.scope);else if("literal"===c)s=i.value;else{const t=Mt(c);if(t){const r=await e.evaluate(i,n),o="number"==typeof r?r:null==r?0:Number(r)||0;s=o,a={node:i,writer:t,currentValue:o}}else{const t=await e.evaluate(i,n);s=Array.isArray(t)&&t.length>0?t[0]:t}}let l=1,u=o;for(let r=1;t.args.length>r;r++){const i=t.args[r];if(i&&"literal"===i.type){const t=i.value;"global"===t?u="global":"number"==typeof t&&(l=t)}else if(i&&"literal"!==i.type){const t=await e.evaluate(i,n);"number"==typeof t&&(l=t)}}const f=t.modifiers?.by;if(f){const t=f.value;if("literal"===Ho(f)&&"number"==typeof t)l=t;else if("literal"!==Ho(f)){const t=await e.evaluate(f,n);"number"==typeof t&&(l=t)}}return{target:s,amount:l,...u&&{scope:u},...a&&{customWrite:a}}}(t,e,n,r);return{...i,operation:r}}async execute(t,e){const{target:n,property:r,scope:i,amount:s=1,operation:o="increment",customWrite:a}=t;if(a){const t=isFinite(s)?s:1,n="increment"===o?a.currentValue+t:a.currentValue-t;return await a.writer(a.node,n,e),Object.assign(e,{it:n}),n}const c=function(t,e,n,r){if("number"==typeof t)return t;if(pn(t)){const n=t;return e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?gn(n.getAttribute(e)):gn(n[e]):gn(n.value||n.textContent)}return"string"==typeof t?"element"===n?gn(vn(t,r,"element")):"global"===n?gn(vn(t,r,"global")):t.includes(".")?function(t,e){const n=t.split("."),r=n[1],i=wn(n[0],e);return i?gn(i[r]):0}(t,r):gn("me"===t&&r.me?r.me.value||0:"it"===t?r.it||0:"you"===t&&r.you?r.you.value||0:vn(t,r)):gn(t)}(n,r,i,e);let l;if(isNaN(c))l=NaN;else{const t=isFinite(s)?s:1;l="increment"===o?c+t:c-t}return function(t,e,n,r,i){if(pn(t)){const n=t;return void(e?e.startsWith("data-")||["id","class","title","alt","src","href"].includes(e)?n.setAttribute(e,r+""):n[e]=r:"value"in n&&void 0!==n.value?n.value=r+"":n.textContent=r+"")}if("string"==typeof t){if("element"===n)return void bn(t,r,i,"element");if("global"===n)return void bn(t,r,i,"global");if(t.includes("."))return void function(t,e,n){const r=t.split("."),i=r[1],s=wn(r[0],n);s&&(s[i]=e)}(t,r,i);if("me"===t&&i.me)return void(i.me.value=r);if("it"===t)return void Object.assign(i,{it:r});if("you"===t&&i.you)return void(i.you.value=r);bn(t,r,i)}}(n,r,i,l,e),Object.assign(e,{it:l}),l}};return fs(e,"NumericModifyCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"data",compatibility:"standard"}),us(e,r),i=e})();const Do=ks(Bo),Fo=ks(Bo);function Uo(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e}const Vo=ks((()=>{let t,e,n=[Es({name:"clear"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r=t.args?.[0],i=r?.type,s=r?.name;if(r&&("variable"===i||"identifier"===i&&"string"==typeof s))try{const t=await e.evaluate(r,n);if(!pn(t)&&!Array.isArray(t))return{type:"variable",name:s}}catch{return{type:"variable",name:s}}return{type:"form-fields",targets:await Os(t.args,e,n,"clear",{filterPrepositions:!0,fallbackModifierKey:"on"},t.modifiers)}}async execute(t,e){if("variable"===t.type)return e.locals.set(t.name,null),void Object.assign(e,{it:null});for(const e of t.targets)Uo(e)&&("SELECT"===e.tagName?e.selectedIndex=-1:e.value="")}validate(t){if("object"!=typeof t||null===t)return!1;if("variable"===t.type)return"string"==typeof t.name;if("form-fields"===t.type){const e=t.targets;return Array.isArray(e)&&e.every(t=>pn(t))}return!1}};return fs(e,"ClearCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"],category:"data",compatibility:"standard"}),us(e,r),i=e})());function _o(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 zo=(()=>{let t,e,n=[Es({name:"trigger"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",i=r;if(!t.args?.length)throw Error(i+" command requires an event name");const s=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===s(o)||"callExpression"===s(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===s(o)||"keyword"===s(o))a=o.name;else{const t=await e.evaluate(o,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return!1;const n=t.name||t.value;return"on"===n||"to"===n});if(-1!==r&&t.args.length-1>r){const s=t.args.slice(r+1),o=s.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?s:s.slice(0,o);l=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0===n.bubbles||n.bubbles,cancelable:void 0===n.cancelable||n.cancelable,composed:void 0!==n.composed&&n.composed})}(t.eventName,t.detail,t.options);for(const e of t.targets)e.dispatchEvent(n);e.it=n}async resolveTargets(t,e,n,r){const i=[];for(const r of t){const t=await e.evaluate(r,n);if("window"!==t&&t!==window)if("document"!==t&&t!==document)if("me"===t&&n.me)i.push(n.me);else if("you"===t&&n.you)i.push(n.you);else if("it"===t&&n.it)i.push(n.it);else if(pn(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(pn));else if(Array.isArray(t))i.push(...t.filter(pn));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);i.push(...Array.from(e).filter(pn));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);i.push(t)}else i.push(document);else i.push(window)}if(!i.length)throw Error(r+": no valid targets");return i}async parseEventDetail(t,e,n){if(!t?.length)return;if(1===t.length){const r=t[0];if("objectLiteral"!==r?.type)return await e.evaluate(r,n)}const r={};for(const i of t){const t=await e.evaluate(i,n);if("object"!=typeof t||null===t||Array.isArray(t)){if("string"==typeof t&&t.includes(":")){const[e,n]=t.split(":",2);r[e.trim()]=_o(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:!0,cancelable:!0,composed:!1},i=t.findIndex(t=>"with"===(t.name||t.value));if(-1===i)return r;for(const s of t.slice(i+1)){const t=await e.evaluate(s,n);if("string"==typeof t){const e=t.toLowerCase();"bubbles"===e?r.bubbles=!0:"nobubbles"===e?r.bubbles=!1:"cancelable"===e?r.cancelable=!0:"nocancelable"===e?r.cancelable=!1:"composed"===e&&(r.composed=!0)}}return r}};return fs(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"event",compatibility:"standard"}),us(e,r),i=e})();const Wo=ks(zo),Zo=ks(zo);function Jo(t,e,n,r){return t?new Promise(n=>{const i=()=>{s({event:null,timedOut:!1,cancelled:!0})},s=function(n,s){let a=!1;return n=>{a||(a=!0,t.removeEventListener(e,o),r&&r.removeEventListener("abort",i),s(n))}}(0,n),o=t=>{s({event:t,timedOut:!1,cancelled:!1})};r?.aborted?n({event:null,timedOut:!1,cancelled:!0}):(t.addEventListener(e,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function Ko(t){return new Promise(e=>setTimeout(e,t))}const Xo=ks((()=>{let t,e,n=[Es({name:"wait"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("wait command requires an argument");if(t.modifiers.or)return this.parseRaceCondition(t,e,n);if(t.modifiers.for)return this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n);const r=t.args[0];return"arrayLiteral"===r.type&&r.elements?this.parseEventArrayWait(r.elements,t.args[1],e,n):this.parseTimeWait(t.args[0],e,n)}async execute(t,e){const n=Date.now();if("time"===t.type)return await Ko(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await Jo(r,t.eventName)).event;if(Object.assign(e,{it:i}),t.destructure)for(const n of t.destructure)n in i&&e.locals.set(n,i[n]);return{type:"event",result:i,duration:Date.now()-n}}const{result:r,winningCondition:i}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===i?.type&&i.destructure)for(const t of i.destructure)t in r&&e.locals.set(t,r[t]);return{type:r instanceof Event?"event":"time",result:r,duration:Date.now()-n}}async parseTimeWait(t,e,n){return{type:"time",milliseconds:Xs(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const i=await n.evaluate(t,r);if("string"!=typeof i)throw Error("wait for: event name must be a string");const s=i.match(/^(\w+)\(([^)]+)\)$/),o=s?s[1]:i,a=s?s[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await n.evaluate(e,r);if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("wait for from: target must be an EventTarget");c=t}else c=r.me??void 0;return{type:"event",eventName:o,target:c,destructure:a}}async parseEventArrayWait(t,e,n,r){let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}i||(i=r.me??void 0);const s=[];for(const e of t){const t=e;if("objectLiteral"!==t.type||!t.properties)continue;let o,a="",c=[];for(const e of t.properties){const t=e.key?.name||e.key?.value;"name"===t&&e.value?a=e.value.value||"":"args"===t&&e.value?.elements?c=e.value.elements.map(t=>t.value||t.name||""):"duration"===t&&e.value&&(o=e.value)}if(o){const t=await n.evaluate(o,r);s.push({type:"time",milliseconds:Xs(t)})}else a&&s.push({type:"event",eventName:a,target:i,destructure:c.length>0?c:void 0})}return 1===s.length?s[0]:{type:"race",conditions:s}}async parseRaceCondition(t,e,n){const r=[];t.modifiers.for?r.push(await this.parseEventWait(t.modifiers.for,t.modifiers.from,e,n)):t.args[0]&&r.push(await this.parseTimeWait(t.args[0],e,n));const i=await e.evaluate(t.modifiers.or,n),s=Array.isArray(i)?i:[i];for(const t of s)try{r.push({type:"time",milliseconds:Xs(t)})}catch{if("string"==typeof t){const e=t.match(/^(\w+)\(([^)]+)\)$/);r.push(e?{type:"event",eventName:e[1],target:n.me??void 0,destructure:e[2].split(",").map(t=>t.trim())}:{type:"event",eventName:t,target:n.me??void 0})}}if(2>r.length)throw Error("wait: race requires at least 2 conditions");return{type:"race",conditions:r}}async executeRace(t,e){const n=new AbortController,r=n.signal,i=t.map(t=>"time"===t.type?Ko(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):Jo(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(i)}finally{n.abort()}}};return fs(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"async",compatibility:"standard"}),us(e,r),i=e})()),Go=new Map;let Yo=[/^4\d{2}$/,/^5\d{2}$/],Qo=(()=>{let t,e,n=[Es({name:"fetch"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){if(!t.args?.length)throw Error("fetch requires a URL");const r=await this.parseURL(t.args[0],e,n),i=this.parseResponseType(t.modifiers.as);return{url:r,responseType:i,options:await this.parseRequestOptions(t.modifiers.with,e,n),throwOnError:!t.modifiers.doNotThrow&&"response"!==i}}async execute(t,e){const n=Date.now(),{url:r,responseType:i,options:s}=t,o=new AbortController;let a;e.me&&(a=()=>o.abort(),e.me.addEventListener("fetch:abort",a,{once:!0}));const c={...s,signal:o.signal},l=Go.get(i);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;s.timeout&&(u=setTimeout(()=>o.abort(),s.timeout));try{let s=await fetch(r,c);if(e.me){const t={response:s};this.dispatchEvent(e.me,"fetch:afterResponse",t),s=t.response}if(t.throwOnError&&function(t){const e=t+"";return Yo.some(t=>t.test(e))}(s.status)){const t=Error(`Fetch failed for ${r}: HTTP ${s.status} ${s.statusText}`.trim());throw t.response=s,t.isFetchStatusError=!0,t}const o=await this.handleResponse(s,i,e);e.me&&this.dispatchEvent(e.me,"fetch:afterRequest",{result:o});const a={status:s.status,statusText:s.statusText,headers:s.headers,data:o,url:s.url,duration:Date.now()-n};return Object.assign(e,{it:o}),a}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 "+r);if(t instanceof Error&&!0===t.isFetchStatusError)throw t;throw Error(`Fetch failed for ${r}: ${t instanceof Error?t.message:t+""}`)}finally{u&&clearTimeout(u),e.me&&a&&e.me.removeEventListener("fetch:abort",a)}}async parseURL(t,e,n){const r=await e.evaluate(t,n);if("string"!=typeof r||!r){const e=t;if(null==r&&"identifier"===e?.type&&e.name)throw Error(`fetch: URL expression "${e.name}" evaluated to ${r+""} \u2014 check the variable is set, or quote it if you meant a literal URL (fetch 'https://example.com/path')`);throw Error("fetch: URL must be a non-empty string")}return r}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(Go.has(e))return e;throw Error(`fetch: invalid response type "${e}"`)}return"text"}async parseRequestOptions(t,e,n){if(!t)return{};const r=await e.evaluate(t,n);if("object"!=typeof r||null===r)throw Error('fetch: "with" options must be an object');const i={};return"method"in r&&(i.method=(r.method+"").toUpperCase()),"headers"in r&&(i.headers=this.parseHeaders(r.headers)),"body"in r&&(i.body=this.parseBody(r.body)),"credentials"in r&&(i.credentials=r.credentials),"mode"in r&&(i.mode=r.mode),"cache"in r&&(i.cache=r.cache),i}parseHeaders(t){if(t instanceof Headers)return t;const e=new Headers;if("object"==typeof t&&null!==t)for(const[n,r]of Object.entries(t))e.set(n,r+"");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,n){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 r=Go.get(e);return r?r.handler(t,n):t.text()}}}parseHTML(t){const e=(new DOMParser).parseFromString(t,"text/html"),n=document.createDocumentFragment();return Array.from(e.body.childNodes).forEach(t=>n.appendChild(t.cloneNode(!0))),1===n.childNodes.length&&pn(n.firstChild)?n.firstChild:n}dispatchEvent(t,e,n){t.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,cancelable:!0}))}};return fs(e,"FetchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"async",compatibility:"standard"}),us(e,r),i=e})();const ta=ks(Qo),ea=ks((()=>{let t,e,n=[Es({name:"go"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{args:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{args:[]}}async execute(t,e){const{args:n}=t;if(0===n.length)throw Error("Go command requires arguments");if("string"==typeof n[0]&&"back"===n[0].toLowerCase())return await this.goBack(),{result:"back",type:"back"};if(this.isUrlNavigation(n))return{result:await this.navigateToUrl(n,e),type:"url"};const r=this.findBareUrl(n);return null!==r?{result:await this.navigateToBareUrl(r,n),type:"url"}:{result:await this.scrollToElement(n,e),type:"scroll"}}isUrlNavigation(t){return-1!==t.findIndex(t=>"url"===t)}isBareUrl(t){return!!t.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(t)}findBareUrl(t){for(const e of t)if("to"!==e&&"the"!==e)return"string"==typeof e&&this.isBareUrl(e)?e:null;return null}async navigateToBareUrl(t,e){if(e.includes("new")&&e.includes("window")){if("undefined"!=typeof window&&window.open){const e=window.open(t,"_blank");e?.focus&&e.focus()}}else t.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=t):"undefined"!=typeof window&&(window.location.assign?.(t)??(window.location.href=t));return t}async goBack(){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");window.history.back()}async navigateToUrl(t,e){const n=t.findIndex(t=>"url"===t),r=t[n+1];if(!r)throw Error('URL is required after "url" keyword');const i="string"==typeof r?r:r+"",s=t.includes("new")&&t.includes("window");if(!this.isValidUrl(i))throw Error(`Invalid URL: "${i}"`);if(s){if("undefined"!=typeof window&&window.open){const t=window.open(i,"_blank");t?.focus&&t.focus()}}else i.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=i):"undefined"!=typeof window&&(window.location.assign?.(i)??(window.location.href=i));return i}isValidUrl(t){try{return t.startsWith("/")||t.startsWith("#")||new URL(t),!0}catch{return!1}}async scrollToElement(t,e){const n=this.parseScrollPosition(t),r=this.parseScrollTarget(t),i=this.parseScrollOffset(t),s=!t.includes("instantly"),o=this.resolveScrollTarget(r,e);if(!o)throw Error("Target element not found: "+r);if("undefined"!=typeof window){const t=s?"smooth":"instant",e=this.mapVerticalPosition(n.vertical),r=this.mapHorizontalPosition(n.horizontal);if(0!==i){o.scrollIntoView?.({behavior:t,block:e,inline:r});const{x:s,y:a}=this.calculateScrollPosition(o,n,i);window.scrollTo?.({left:s,top:a,behavior:t})}else o.scrollIntoView?.({behavior:t,block:e,inline:r})}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"},n=["top","middle","bottom"],r=["left","center","right"];let i=!1,s=!1;for(const o of t)"string"==typeof o&&(n.includes(o)?(e.vertical=o,i=!0):r.includes(o)&&(e.horizontal=o,s=!0));return s&&!i&&(e.vertical="nearest"),e}parseScrollTarget(t){const e=t.findIndex(t=>"of"===t);if(-1!==e&&t.length>e+1){let n=t[e+1];return"the"===n&&t.length>e+2&&(n=t[e+2]),n}for(const e of t)if("object"==typeof e&&e&&e.nodeType)return e;const n=["top","middle","bottom","left","center","right","of","the","to","smoothly","instantly"];for(const e of t)if("string"==typeof e&&!n.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 n=t[e];if("string"==typeof n){const t=n.match(/^([+-]?\d+)(px)?$/);if(t)return parseInt(t[1],10)}if(("+"===n||"-"===n)&&t.length>e+1){const r=t[e+1],i="number"==typeof r?r:parseInt((r+"").replace("px",""),10);if(!isNaN(i))return"-"===n?-i:i}}return 0}resolveScrollTarget(t,e){if("object"==typeof t&&t&&t.nodeType)return t;const n="string"==typeof t?t:t+"";if("body"===n&&"undefined"!=typeof document)return document.body;if("html"===n&&"undefined"!=typeof document)return document.documentElement;if("me"===n&&pn(e.me))return e.me;if("it"===n&&pn(e.it))return e.it;if("you"===n&&pn(e.you))return e.you;const r=vn(n,e);if(pn(r))return r;if("undefined"!=typeof document)try{const t=document.querySelector(n);if(t)return t}catch{try{const t=document.getElementsByTagName(n);if(t.length>0)return t[0]}catch{}}return null}calculateScrollPosition(t,e,n){if("undefined"==typeof window||!t.getBoundingClientRect)return{x:0,y:0};const r=t.getBoundingClientRect(),i=window.pageXOffset||document.documentElement?.scrollLeft||0,s=window.pageYOffset||document.documentElement?.scrollTop||0,o=window.innerWidth||800,a=window.innerHeight||600;let c=i,l=s;switch(e.horizontal){case"left":c=r.left+i;break;case"center":c=r.left+i+r.width/2-o/2;break;case"right":c=r.right+i-o}switch(e.vertical){case"top":l=r.top+s+n;break;case"middle":l=r.top+s+r.height/2-a/2+n;break;case"bottom":l=r.bottom+s-a+n}return{x:Math.max(0,c),y:Math.max(0,l)}}};return fs(e,"GoCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"navigation",compatibility:"standard"}),us(e,r),i=e})()),na=ks((()=>{let t,e,n=[Es({name:"log"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return t.args&&0!==t.args.length?{values:await Promise.all(t.args.map(t=>e.evaluate(t,n)))}:{values:[]}}async execute(t,e){const n="undefined"!=typeof window?window.console:console;0===t.values.length?n.log():n.log(...t.values)}validate(t){return"object"==typeof t&&null!==t&&Array.isArray(t.values)}};return fs(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=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"],category:"utility",compatibility:"standard"}),us(e,r),i=e})()),ra=ks((()=>{let t,e,n=[Es({name:"breakpoint"})],r=[];var i=e=class{get metadata(){return i.metadata}async parseInput(t,e,n){return{}}async execute(t,e){}validate(t){return"object"==typeof t&&null!==t}};return fs(e,"BreakpointCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ls(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),i=e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:s})})(),e.metadata=xs({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),us(e,r),i=e})()),ia=function(t,e){const n=new Ir(null);for(const e of t)n.register(e);return new _r({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??!0,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??!0,enableResultPattern:e.enableResultPattern??!0})}([Bs(),Js(),ho(),yo(),vo(),bo(),ko(),So(),Co(),No(),Ro(),Lo(),Mo(),Io(),qo(),Do(),Fo(),Vo(),Zo(),Wo(),Xo(),ta(),ea(),na(),ra()],{expressionRegistry:as()}),sa={parse:t=>tn(t),execute:async(t,e)=>{const n=function(t){if(!t)return dn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=dn(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),r=tn(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await ia.execute(r.node,n)}},oa=function(t){return new cs(t)}(sa),aa={runtime:sa,parse:t=>sa.parse(t),execute:async(t,e)=>sa.execute(t,e),createContext:dn,attributeProcessor:oa,version:"1.1.0-standard-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","make","empty","open","close","select","reset","focus","blur","set","increment","decrement","clear","send","trigger","wait","fetch","go","log","breakpoint"],eval:async(t,e)=>sa.execute(t,e),init:()=>{oa.init()}};"undefined"!=typeof window&&(window.hyperfixi=aa,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{oa.init()}):oa.init());class ca{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ci(t,"left operand");return{success:!0,value:ui(r+ci(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Addition failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){const e=function(t){if(null==t)return pi([mi("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return pi([mi("type-mismatch","Expected object, got "+typeof t)],["Provide an object with left and right operands"]);const e=t;if(!("left"in e)||!("right"in e)){const t=[];return"left"in e||t.push("left"),"right"in e||t.push("right"),pi([mi("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return fi(n)?fi(r)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[mi("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[mi("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const la={addition:new ca,subtraction:new class{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ci(t,"left operand");return{success:!0,value:ui(r-ci(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ca).validate(t)}},multiplication:new class{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ci(t,"left operand");return{success:!0,value:ui(r*ci(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ca).validate(t)}},division:new class{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=!0){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(ci(t,"left operand"),ci(n,"right operand"),!0);return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ca).validate(t)}},modulo:new class{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e){if(0===e)throw Error("Modulo by zero");return t%e}(ci(t,"left operand"),ci(n,"right operand"));return{success:!0,value:r,type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Modulo failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(t){return(new ca).validate(t)}},power:new class{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(t,e){const n=this.validate(e);if(!n.isValid)return{success:!1,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ci(t,"left operand"),i=ci(n,"right operand");return{success:!0,value:ui(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:!1,errors:[mi("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new ca).validate(t)}}};var ua=Object.freeze({__proto__:null,conversion:Kn,conversionExpressions:Kn,createCommonRegistry:as,createCoreRegistry:function(){return zr(Zr,zi,Yi)},createExpressionRegistry:zr,createFullExpressionRegistry:function(){return zr(Zr,zi,Kn,os,Qn,Yi,la)},createFullRegistry:function(){return zr(Zr,zi,Yi,Kn,os,Qn)},logical:zi,logicalExpressions:zi,positional:os,positionalExpressions:os,properties:Qn,propertiesExpressions:Qn,references:Zr,referencesExpressions:Zr,special:Yi,specialExpressions:Yi});return aa}();
|
|
2
2
|
//# sourceMappingURL=hyperfixi-standard.js.map
|