@hyperfixi/core 2.9.4 → 2.10.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.
Files changed (91) hide show
  1. package/dist/ast-utils/index.js +295 -85
  2. package/dist/ast-utils/index.mjs +295 -85
  3. package/dist/chunks/{bridge-DhmZ3Khh.js → bridge-CPNAPYAo.js} +2 -2
  4. package/dist/chunks/browser-modular-B0lGdcoP.js +2 -0
  5. package/dist/chunks/{index-DKrx4rv2.js → index-BQkkNlzO.js} +2 -2
  6. package/dist/commands/advanced/async.d.ts +0 -8
  7. package/dist/commands/advanced/js.d.ts +0 -8
  8. package/dist/commands/animation/measure.d.ts +0 -8
  9. package/dist/commands/animation/settle.d.ts +0 -8
  10. package/dist/commands/animation/start-view-transition.d.ts +0 -8
  11. package/dist/commands/animation/take.d.ts +0 -8
  12. package/dist/commands/animation/transition.d.ts +0 -8
  13. package/dist/commands/async/fetch.d.ts +0 -8
  14. package/dist/commands/async/wait.d.ts +0 -8
  15. package/dist/commands/behaviors/install.d.ts +0 -8
  16. package/dist/commands/content/append.d.ts +0 -8
  17. package/dist/commands/content/prepend.d.ts +0 -8
  18. package/dist/commands/control-flow/break.d.ts +0 -8
  19. package/dist/commands/control-flow/continue.d.ts +0 -8
  20. package/dist/commands/control-flow/exit.d.ts +0 -8
  21. package/dist/commands/control-flow/halt.d.ts +0 -8
  22. package/dist/commands/control-flow/if.d.ts +0 -8
  23. package/dist/commands/control-flow/repeat.d.ts +0 -8
  24. package/dist/commands/control-flow/return.d.ts +0 -8
  25. package/dist/commands/control-flow/throw.d.ts +0 -8
  26. package/dist/commands/data/clear.d.ts +0 -8
  27. package/dist/commands/data/default.d.ts +0 -8
  28. package/dist/commands/data/get.d.ts +0 -8
  29. package/dist/commands/data/increment.d.ts +0 -8
  30. package/dist/commands/data/set.d.ts +0 -8
  31. package/dist/commands/decorators/index.d.ts +2 -8
  32. package/dist/commands/dom/add.d.ts +0 -8
  33. package/dist/commands/dom/close.d.ts +0 -8
  34. package/dist/commands/dom/empty.d.ts +0 -8
  35. package/dist/commands/dom/hide.d.ts +0 -8
  36. package/dist/commands/dom/make.d.ts +0 -8
  37. package/dist/commands/dom/open.d.ts +0 -8
  38. package/dist/commands/dom/process-partials.d.ts +0 -8
  39. package/dist/commands/dom/put.d.ts +0 -8
  40. package/dist/commands/dom/remove.d.ts +0 -8
  41. package/dist/commands/dom/reset.d.ts +0 -8
  42. package/dist/commands/dom/select.d.ts +0 -8
  43. package/dist/commands/dom/show.d.ts +0 -8
  44. package/dist/commands/dom/swap.d.ts +2 -18
  45. package/dist/commands/dom/toggle.d.ts +0 -8
  46. package/dist/commands/events/trigger.d.ts +0 -8
  47. package/dist/commands/execution/blur.d.ts +0 -8
  48. package/dist/commands/execution/call.d.ts +0 -8
  49. package/dist/commands/execution/focus.d.ts +0 -8
  50. package/dist/commands/execution/pseudo-command.d.ts +0 -8
  51. package/dist/commands/index.js +82 -23
  52. package/dist/commands/index.mjs +82 -23
  53. package/dist/commands/navigation/go.d.ts +0 -8
  54. package/dist/commands/navigation/push-url.d.ts +0 -8
  55. package/dist/commands/navigation/scroll-to.d.ts +0 -8
  56. package/dist/commands/templates/render.d.ts +0 -8
  57. package/dist/commands/utility/beep.d.ts +0 -8
  58. package/dist/commands/utility/breakpoint.d.ts +0 -8
  59. package/dist/commands/utility/copy.d.ts +0 -8
  60. package/dist/commands/utility/log.d.ts +0 -8
  61. package/dist/commands/utility/pick.d.ts +0 -8
  62. package/dist/commands/utility/tell.d.ts +0 -8
  63. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  64. package/dist/hyperfixi-browser-minimal.js +1 -1
  65. package/dist/hyperfixi-browser-standard.js +1 -1
  66. package/dist/hyperfixi-browser.js +1 -1
  67. package/dist/hyperfixi-classic-i18n.js +1 -1
  68. package/dist/hyperfixi-hx-v4.js +1 -1
  69. package/dist/hyperfixi-minimal.js +1 -1
  70. package/dist/hyperfixi-multilingual.js +1 -1
  71. package/dist/hyperfixi-standard.js +1 -1
  72. package/dist/hyperfixi.js +1 -1
  73. package/dist/hyperfixi.mjs +1 -1
  74. package/dist/index.js +441 -143
  75. package/dist/index.min.js +1 -1
  76. package/dist/index.mjs +441 -143
  77. package/dist/lokascript-browser-classic-i18n.js +1 -1
  78. package/dist/lokascript-browser-minimal.js +1 -1
  79. package/dist/lokascript-browser-standard.js +1 -1
  80. package/dist/lokascript-browser.js +1 -1
  81. package/dist/lokascript-multilingual.js +1 -1
  82. package/dist/parser/command-parsers/dom-commands.d.ts +1 -0
  83. package/dist/parser/full-parser.js +47 -1
  84. package/dist/parser/full-parser.mjs +47 -1
  85. package/dist/reference/index.js +6 -5
  86. package/dist/reference/index.mjs +6 -5
  87. package/dist/registry/index.js +50 -6
  88. package/dist/registry/index.mjs +50 -6
  89. package/dist/runtime/command-adapter.d.ts +8 -8
  90. package/package.json +5 -5
  91. package/dist/chunks/browser-modular-BllAMlht.js +0 -2
@@ -1 +1 @@
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",u="index",l="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"]),$=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"]),C=new Set(["me","it","you","result","my","its","your"]),N=new Set(["and","or","not","no"]),R=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"]),O=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"]),L=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 j;!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"}(j||(j={}));const M=new Set(["+","-","*","/","mod"]),I=new Set(["ms","s","seconds","minutes","hours","days"]);function P(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function q(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 H(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;q(t)}}function B(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:D(t,s),column:a};t.tokens.push(c)}function D(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 F(t){const e=t.position;let n="";for(q(t),q(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=q(t);B(t,j.COMMENT,"--"+n,e)}function V(t){const e=t.position,n=q(t);let r=n;for(;t.input.length>t.position;){const e=q(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=q(t))}B(t,j.STRING,r,e)}function _(t){const e=t.position;q(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){q(t);break}if("\\"===e){if(q(t),t.input.length>t.position){const e=q(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+=q(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);B(t,j.TEMPLATE,n,e)}function U(t){const e=t.position;let n=q(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=q(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=q(t),"}"===e)break}B(t,j.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)q(t),t.input.length>t.position&&(n+=q(t));else{if(!Y(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=q(t)}}B(t,j.SELECTOR,n,e)}}function W(t){const e=t.position;if(Q(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+=q(t),e===s&&(s="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=q(t);if(n.length>t.position&&(r+=q(t)),i--,0>=i)break;continue}let e=0,s="";for(;n.length>t.position;){const i=n[t.position];if(s)r+=q(t),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=q(t);break}r+=q(t)}else s=i,r+=q(t)}if(e||i++,0>=i)break;continue}r+=q(t)}else s=e,r+=q(t)}B(t,j.SELECTOR,r,e)}(t,e);let n="";for(n+=q(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=q(t),"/"===e&&">"===r){n+=q(t);break}}B(t,j.SELECTOR,n,e)}function z(t){const e=t.position;let n=q(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!Y(e)&&"_"!==e&&"-"!==e)break;n+=q(t)}B(t,j.SYMBOL,n,e)}function Z(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===P(t,1))return n="'s",q(t),q(t),void B(t,j.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,q(t),q(t),q(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,q(t),q(t)):n=q(t),B(t,j.OPERATOR,n,e)}function J(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+=q(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=q(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=q(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+=q(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=q(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=q(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+=q(t)}I.has(o)?B(t,j.TIME,i+o,e):(t.position=s,B(t,j.NUMBER,i,e))}function X(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+=q(t)}const s=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return 0;const s=t.tokens[t.tokens.length-1];if(s&&(s.kind===j.IDENTIFIER||s.kind===j.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}H(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+=q(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){H(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+=q(t)}const i=n.toLowerCase();if("start"===i||"end"===i){H(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+=q(t)}if("of"===e.toLowerCase())return B(t,j.IDENTIFIER,`at the ${i} of`,r),1}return t.position=e,0}if("start"===s||"end"===s){H(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+=q(t)}return"of"===n.toLowerCase()?(B(t,j.IDENTIFIER,`at ${s} of`,r),1):(t.position=e,0)}}return 0}(t,r,e,n);if(s)return 1;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&&(H(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+=q(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");R.has(n)&&(i=n,s=t.position)}return R.has(i)&&i!==`${e} ${n}`?(t.position=s,i):(t.position=r,null)}(t,r,e);if(a)return B(t,j.OPERATOR,a,n),1;if(R.has(i))return B(t,j.OPERATOR,i,n),1}return R.has(r)?(t.position=i,B(t,j.OPERATOR,e,n),1):(t.position=i,0)}(t,i,e);if(s)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||N.has(e)||M.has(t)||M.has(e)||R.has(e)?j.OPERATOR:j.IDENTIFIER}(i);B(t,o,i,e)}function K(t){const e=t.position,n=t.input,r=n.length;q(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+=q(t)}B(t,j.IDENTIFIER,i,e)}function G(t){return/[a-zA-Z]/.test(t)}function Y(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return 0;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 tt(t){if(Q(t))return 1;let e=t.position+1,n=0;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(Y(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=1,e++;else{if(" "!==r&&"\t"!==r)return 0;e++}if(e-t.position>50)return 0}return 0}function et(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const nt=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),rt=nt,it=nt,st=nt,ot=nt,at=(...t)=>{rt&&console.log("\ud83d\udd27",...t)},ct=(...t)=>{it&&console.log("\ud83c\udfaf",...t)},ut=(...t)=>{st&&console.log("\ud83d\udcdd",...t)},lt=(...t)=>{ot&&console.log("\ud83d\ude80",...t)};let ft=0,ht=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ft=1,ht=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let dt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class pt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(pt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const n=t.toLowerCase();return/\bjs\b/.test(n)||/\btell\b/.test(n)||/\*[a-zA-Z]/.test(t)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,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(ft){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(!ft)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(),ht){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});ht.dispatchEvent(e)}}(a),n=a,dt.totalParses++,n.semanticSuccess?dt.semanticSuccesses++:n.fallbackTriggered?dt.semanticFallbacks++:dt.traditionalParses++,dt.confidenceHistory.push(n.confidence),dt.confidenceHistory.length>100&&dt.confidenceHistory.shift(),dt.averageConfidence=dt.confidenceHistory.reduce((t,e)=>t+e,0)/dt.confidenceHistory.length}return s?{success:1,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:0,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:0,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:0,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:0,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:0,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:0,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:0,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}}pt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const mt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),yt=new Set([")","]","}",","]);function gt(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 vt(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 bt(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:1,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function wt(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=1;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=0),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:s,negated:t,start:e.start,end:i.end}}}const Et=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",gt(10)],["||",gt(10)],["and",gt(20)],["&&",gt(20)],["==",gt(30)],["!=",gt(30)],["<",gt(30)],[">",gt(30)],["<=",gt(30)],[">=",gt(30)],["is",gt(30)],["matches",gt(30)],["contains",gt(30)],["starts with",gt(30)],["ends with",gt(30)],["does not start with",gt(30)],["does not end with",gt(30)],["is between",gt(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}})],["is not between",gt(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 between",gt(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 not between",gt(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}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=1,t)}}],["where",gt(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",gt(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",gt(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",gt(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",gt(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}})],["+",{...gt(40),...bt(80)}],["-",{...gt(40),...bt(80)}],["*",gt(50)],["/",gt(50)],["%",gt(50)],["mod",gt(50)],["^",vt(60)],["**",vt(60)],["as",gt(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",bt(80)],["!",bt(80)],["no",bt(27)]]),new Map([["===",gt(30)],["!==",gt(30)],["is not",gt(30)],["am",gt(30)],["is in",gt(30)],["is not in",gt(30)],["precedes",gt(30)],["does not precede",gt(30)],["follows",gt(30)],["does not follow",gt(30)],["is a",gt(30,wt(0))],["is an",gt(30,wt(0))],["is not a",gt(30,wt(1))],["is not an",gt(30,wt(1))],["has",gt(30)],["have",gt(30)],["match",gt(30)],["include",gt(30)],["includes",gt(30)],["equals",gt(30)],["does not contain",gt(30)],["does not include",gt(30)],["am in",gt(30)],["am not in",gt(30)],["is really",gt(30)],["is not really",gt(30)],["is equal",gt(30)],["is not equal",gt(30)],["contain",gt(30)],["do not contain",gt(30)],["does not contains",gt(30)],["do not match",gt(30)],["does not match",gt(30)],["is equal to",gt(30)],["is not equal to",gt(30)],["is really equal to",gt(30)],["is not really equal to",gt(30)],["really equals",gt(30)],["is greater than",gt(30)],["is less than",gt(30)],["is greater than or equal to",gt(30)],["is less than or equal to",gt(30)],["in",gt(30)],["of",vt(30)],["really",gt(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:0,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["some",bt(80)]]),new Map([["=",vt(5)]])),xt=new Map,kt=new Map,St=new Map,At=new Set,Tt=new Set,$t=new Set,Ct=new Set;function Nt(t){return xt.get(t.toLowerCase())}function Rt(t,e){if(0!==Tt.size)for(const n of Tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Ot(t,e,n){if(0!==$t.size)for(const r of $t)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function Lt(t,e){if(0!==Ct.size)for(const n of Ct)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function jt(t,e,n){if(t.globals.set(e,n),0!==At.size)for(const r of At)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function Mt(t){return t.kind!==j.IDENTIFIER?0:E.has(t.value.toLowerCase())}function It(t){return t.kind!==j.IDENTIFIER?0:L.has(t.value.toLowerCase())}function Pt(t){return t.kind!==j.IDENTIFIER?0:O.has(t.value.toLowerCase())}function qt(t){return t.kind!==j.IDENTIFIER?0:C.has(t.value.toLowerCase())}function Ht(t){return R.has(t.value.toLowerCase())}function Bt(t){return t.kind===j.IDENTIFIER}function Dt(t){return t.kind===j.SELECTOR}function Ft(t){return t.kind!==j.SELECTOR?0:!t.value.startsWith("<")}function Vt(t){return t.kind===j.STRING||t.kind===j.NUMBER||t.kind===j.TEMPLATE}function _t(t){return t.kind===j.IDENTIFIER}function Ut(t){return t.kind===j.TIME}function Wt(t){return t.kind===j.SYMBOL}function zt(t){return t.kind===j.COMMENT}function Zt(t){if(t.kind!==j.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(E.has(e)||L.has(e)||O.has(e)||C.has(e))}function Jt(t){return t.kind===j.STRING}function Xt(t){return t.kind===j.NUMBER}function Kt(t){if(t.kind===j.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Gt(t){return t.kind===j.TEMPLATE}function Yt(t){return t.kind===j.SELECTOR&&t.value.startsWith("<")}function Qt(t){return t.kind===j.SELECTOR&&t.value.startsWith("#")}function te(t){return t.kind===j.SELECTOR&&t.value.startsWith(".")}function ee(t){return t.kind!==j.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function ne(t){if(t.kind!==j.OPERATOR)return 0;const e=t.value.toLowerCase();return!N.has(e)&&!R.has(e)}function re(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function ie(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function se(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function oe(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 ae(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ce(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ue(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function le(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function fe(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function he(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 de=[{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 pe(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const me=[t,r,e,n];function ye(t,e=[]){if(t.isAtEnd())return 1;for(const e of me)if(t.check(e))return 1;for(const n of e)if(t.check(n))return 1;return t.checkIsCommand()?1:0}function ge(t,e=[]){if(!ye(t,e))return t.parseExpression()}function ve(t,e,n){return t.check(e)?(t.advance(),n.push(t.createIdentifier(e)),1):0}function be(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function we(t,e){return t.check(e)?(t.advance(),1):0}function Ee(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 xe{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new xe(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 xe(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 xe(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=1){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 xe(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 ke(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}=Ee(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(;!ye(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 xe.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Se(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 xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ae(i,s){const o=[],a=()=>i.check(n)||s&&i.check(e);for(;!i.isAtEnd()&&!a();){if(zt(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 Te=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function $e(t,e,n){return null===e||Te.has(e.value?.toLowerCase?.()??"")?0:t.checkIsCommand()||t.isCommand(n.value?.toLowerCase())}function Ce(r,i){const s=[];let o=0;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=1;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;if(void 0!==e.line&&e.line!==i.line&&$e(r,c,e))break;zt(e)||(c=e),r.advance()}r.restorePosition(a);let u=0;if(!o){const t=r.savePosition(),s=i.line,o=100;let a=0,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&&(u=1);break}if($e(r,c,t)){if(void 0!==t.line&&t.line!==s){u=1;break}a=1}zt(t)||(c=t),r.advance()}r.restorePosition(t)}const l=o||u;let f;if(l)f=r.parseExpression();else{const e=[],n=20;let s=0,o=1;for(;!r.isAtEnd()&&!r.check(t)&&(o||!r.checkIsCommand()&&!r.isCommand(r.peek().value))&&n>s;){o=0;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),l){we(r,t);const o=Ae(r,1);if(0===o.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");s.push(ae(o,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}));let a=0;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Ce(r,t);s.push(ae([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=Ae(r,0);s.push(ae(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(ae([t],{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}}return xe.from(i).withArgs(...s).endingAt(r.getPosition()).build()}function Ne(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=xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Re=new Set(["my","its","your"]);function Oe(t){const e={};if(we(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||!Bt(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&Bt(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},we(t,h)){const n=ge(t);n&&(e.from=n)}return e}function Le(t,e){const n=[],r=ge(t,[h]);r&&n.push(r),ve(t,h,n);const i=ge(t);return i&&n.push(i),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function je(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const s=ge(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),ve(t,r,n);const e=ge(t,[h,m,i]);e&&n.push(e)}if(be(t,[h,m],n)){const e=ge(t);e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).withModifiers(Oe(t)).endingAt(t.getPosition()).build()}const s=ge(t,[h,m]);if(s&&n.push(s),be(t,[h,m],n)){const e=ge(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),xe.fromIdentifier(e).withArgs(...n).withModifiers(Oe(t)).endingAt(t.getPosition()).build()}function Me(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)?(we(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?xe.fromIdentifier(e).withArgs(r,t.createIdentifier(s),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Ie=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function Pe(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 fe(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:fe(se(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 u=i.parseExpression()??i.parsePrimary();let l;var h;i.check(m)&&(h=i.peekAt(1))&&("selector"===h.kind||h.value.startsWith("<")||qe.has(h.value))&&(i.advance(),l=ge(i));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(i.createIdentifier(f)),u&&d.push(u);const y=xe.fromIdentifier(s).withArgs(...d);return l&&y.withModifier("on",l),y.endingAt(i.getPosition()).build()}const qe=new Set(["me","my","it","its","you","your","yourself"]),He=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function Be(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function De(t,e){const n=[];for(;!ye(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Fe(t){const e=t.peek();if("/"===e.value)return 1;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return 0}const Ve=new Set(["{",")"]);function _e(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(Ve.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 Ue(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function We(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 ze=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Ze{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 pt({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=1),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,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:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&Nt(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!==Nt(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?Nt(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:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,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")){ut("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];ut(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){ut(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(ut("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,ut(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),ut(`\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 ut("\u26a0\ufe0f PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};ut("\u2705 PARSER: No more event handlers, at end of input");break}}return ut(`\u2705 PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:0,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:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:1,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,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=Ze.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=Ze.PRATT_TABLE.get(e.value);if(!n?.infix){if(mt.has(e.value)||yt.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){ut("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()&&!Ze.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(ze.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 0;const e=t.value;return mt.has(e)||yt.has(e)?0:"number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind?1:["(","[","{","-","+","!","#",".","<","$","@"].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?mt.has(e.value)||yt.has(e.value):1},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):(t=>E.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>T.has(t.toLowerCase()))(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:0,...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 x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,o){switch(o.name.toLowerCase()){case"put":return Me(s,o);case"trigger":case"send":return ke(s,o);case"remove":return Le(s,o);case"take":return function(t,e){const n=[],r={},s=ge(t,[h,i]);if(s&&n.push(s),t.check(h)){ve(t,h,n);const e=ge(t,[i]);e&&n.push(e)}if(we(t,i)){const e=ge(t);e&&(r.for=e)}return xe.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(s,o);case"toggle":return je(s,o);case"set":return Pe(s,o);case"halt":return Se(s,o);case"measure":return Ne(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 xe.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,o);case"go":return function(t,e){const n=[];for(;!ye(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(He.has(r)){t.advance(),n.push(Be(r,e));continue}if(Fe(t)){const r=_e(t);if(r){n.push(r);continue}t.advance(),n.push(Be(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(Be(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(Be(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return xe.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");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)||i.check(n))break;if(i.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return xe.fromIdentifier(s).withArgs(o,...a).endingAt(i.getPosition()).build()}(s,o);case"pick":return function(t,e){const n=xe.fromIdentifier(e);we(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=0;(t.match("to")||t.match(".."))&&(t.match("end")?o=1:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=s(),u=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return o?u.withModifier("rangeEnd",i("end")):r&&u.withModifier("rangeEnd",r),u.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 De(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 xe.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();Ie.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),xe.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 xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o);default:return De(s,o)}}(this.getContext(),s)}parsePutCommand(t){return Me(this.getContext(),t)}parseSetCommand(t){return Pe(this.getContext(),t)}parseHaltCommand(t){return Se(this.getContext(),t)}parseMeasureCommand(t){return Ne(this.getContext(),t)}parseTriggerCommand(t){return ke(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(ut("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){ut("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){ut(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&&(ut("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(ut("\u2705 Parsed command:",r.name),e.push(r),t=1)}catch(t){ut("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&ut("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){ut("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(ut("\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(","));)ut("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ut("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ut("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}ut("\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=""),ut("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(ut('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ut('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return ut('\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();Bt(e)&&(v=e.value,t.advance()),t.check(l)&&(t.advance(),g=t.parseExpression())}else if(t.check(l))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(ut("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!Bt(e)&&!Pt(e))throw Error('Expected event name after "event"');if(f=e.value,t.advance(),ut("\u2705 Got event name:",f,"Next token:",t.peek().value),ut('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(h)){ut('\u2705 Found "from", advancing...'),t.advance(),ut('\ud83d\udccd After consuming "from", current token:',t.peek().value),we(t,b)&&ut('\u2705 Found "the", advancing...');const e=t.peek();ut("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),ut("\u2705 After parsePrimary, eventTarget:",p)}else ut('\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()===u&&(t.advance(),t.advance(),x=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(x=e.value,t.advance()):x=u}let k=null,S=0;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=1,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(ce(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(ce(f,A)),p&&n.push(p),x&&n.push(ce(x,A)),n.push(ae(E,{...A,end:A.end||0})),null!==k&&n.push(ae(k,{...A,end:A.end||0}));const T=xe.from(e).withArgs(...n);return S&&T.withModifier("bottomTested",{type:"literal",value:1,...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(!Bt(s))throw Error('Expected variable name after "for"');if(r=s.value,t.advance(),!t.check(l))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()===u&&(t.advance(),t.advance(),o=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(o=e.value,t.advance()):o=u}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(ce(r,c)),n.push(i),o&&n.push(ce(o,c)),n.push(ae(a,{...c,end:c.end||0})),xe.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")&&!ye(t)){const r=t.parseExpression();return n.push(r),xe.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(!Bt(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(!Bt(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(),we(t,b),i=t.parsePrimary());const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(le(r.map(t=>ue("duration"===t.kind?[{key:se("duration",s),value:t.expr}]:[{key:se("name",s),value:ie(t.name,`"${t.name}"`,s)},{key:se("args",s),value:le(t.params.map(t=>ie(t,`"${t}"`,s)),s)}],s)),s)),i&&n.push(i)}return xe.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(se(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(Ee(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(ue(r.map(t=>({key:t.name?se(t.name,i):ie("_positional","_positional",i),value:t.value})),i))}}return xe.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("<")||Bt(o)&&Re.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&&(Bt(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 xe.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=ge(t,[f]);e&&n.push(e)}if(t.check(f)){t.advance();const e=ge(t);e&&n.push(e)}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Ce(this.getContext(),t)}parseRemoveCommand(t){return Le(this.getContext(),t)}parseToggleCommand(t){return je(this.getContext(),t)}parseRegularCommand(t){return De(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),0)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),0);n.optional=1,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}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):Wt(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()&&Bt(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=1;break;case"false":e=0;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=1,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(Zt)||this.matchPredicate(It)||this.matchPredicate(qt)||this.matchPredicate(Mt)||this.matchPredicate(Pt))){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(Wt(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),0)}}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(Zt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=0;for(;this.check("-");)this.advance(),t+="-",n=1;for(this.checkPredicate(Zt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=1,this.checkPredicate(Zt)&&(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(Zt))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=0,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=1),"{"===t.value&&s++,"}"===t.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),u=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:u}),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:1,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:0,...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:0,...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(!(Ze.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Zt(r)&&!this.isCommand(r.value)||qt(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};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}}),Ze.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:0,targetFailed:1}}return{node:this.createPseudoCommandNode(n,t,i,s,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(ut("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return ut("\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,ut(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,ut(`\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(){ut("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=0;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=1,ut("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),ut("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),ut("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),ut("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(ut("\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,ut(`\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"),ut("\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=1,ut("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=1,ut("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=1,ut("\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,ut(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,ut(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else ut(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,u;if(this.parseTemporalKeywordModifiers(s),e&&(s.once=1),Object.keys(s).length>0&&ut("\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,ut(`\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,ut("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(ut("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),ut("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const l=[];for(ut(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ut(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ut("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ut("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ut("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){ut(`\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();l.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(l.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(l.push(t),ut("\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&&l.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){ut("\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(l.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:0,...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}};l.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:l,...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},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:p.start,end:p.end,line:p.line,column:p.column};return ut(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${u?"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();Zt(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,u,l;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:u,finallyHandler:l}=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!==u&&{errorHandler:u},...void 0!==l&&{finallyHandler:l},...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")||(ut("\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"));)ut("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ut('\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=he(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 de.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return pe(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!ye(t,["catch","finally",...r.keywords])&&!pe(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&pe(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&pe(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(s[e]=n),!pe(t.peek(),r.keywords))break}const o=xe.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?(ut(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(ut(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return ut("[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(Mt(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"].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()&&Fe(t)&&(r=_e(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),xe.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:1,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=Ue(t)?We(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||we(t,"a")||we(t,"an"),n.as=t.parsePrimary();const i=xe.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:1,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=0;t.check(v)&&(i=1,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=ie(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},u=oe(r,s,o,c);u.coerceNumeric=1;const l=[a,se(f,c),u];return xe.from(e).withName("set").withArgs(...l).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:0,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=0,i=0;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=1,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=1),{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(""),0);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),0)}{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},1)}if(Wt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}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),0)}}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;$.has(e.toLowerCase())&&ut(`\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 ie(t,e,this.getPosition())}createIdentifier(t){return se(t,this.getPosition())}createBinaryExpression(t,e,n){return oe(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(ut(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return ut("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return ut(`\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 ut(`\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(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return ne(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Ft)}matchSelector(){return this.matchPredicate(Ft)}checkAnySelector(){return this.checkPredicate(Dt)}checkLiteral(){return this.checkPredicate(Vt)}checkIdentifierLike(){return this.checkPredicate(Bt)}checkIsCommand(){return this.checkPredicate(Mt)}checkCommandTerminator(){return this.checkPredicate(re)}checkReference(){return this.checkPredicate(_t)}checkTimeExpression(){return this.checkPredicate(Ut)}checkEvent(){return this.checkPredicate(Pt)}checkContextVar(){return this.checkPredicate(qt)}checkComment(){return this.checkPredicate(zt)}checkIdentifier(){return this.checkPredicate(Zt)}checkKeyword(){return this.checkPredicate(It)}checkString(){return this.checkPredicate(Jt)}matchString(){return this.matchPredicate(Jt)}checkNumber(){return this.checkPredicate(Xt)}matchNumber(){return this.matchPredicate(Xt)}checkBoolean(){return this.checkPredicate(Kt)}matchBoolean(){return this.matchPredicate(Kt)}checkTemplateLiteral(){return this.checkPredicate(Gt)}matchTemplateLiteral(){return this.matchPredicate(Gt)}checkQueryReference(){return this.checkPredicate(Yt)}matchQueryReference(){return this.matchPredicate(Yt)}checkIdSelector(){return this.checkPredicate(Qt)}checkClassSelector(){return this.checkPredicate(te)}checkCssSelector(){return this.checkPredicate(ee)}checkBasicOperator(){return this.checkPredicate(ne)}matchBasicOperator(){return this.matchPredicate(ne)}matchTimeExpression(){return this.matchPredicate(Ut)}matchIdentifierLike(){return this.matchPredicate(Bt)}matchComparisonOperator(){return this.matchPredicate(Ht)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Zt,t)}consumeIdentifierLike(t){return this.consumePredicate(Bt,t)}consumeEvent(t){return this.consumePredicate(Pt,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;ut("\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:1,configurable:1}),e}}function Je(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&&(H(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==P(e,1))if('"'!==n){if("'"===n||"'"===n){const t=P(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==j.IDENTIFIER&&n.kind!==j.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)V(e);else{const t=e.position;q(e),q(e),B(e,j.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===P(e,1)){const t=e.position;q(e),q(e),B(e,j.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===j.IDENTIFIER&&E.has(t.value.toLowerCase()),i=t&&t.kind===j.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===j.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(G(P(e))||"{"===P(e)||"-"===P(e))){U(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===j.IDENTIFIER&&O.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==j.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(q(e),B(e,j.SYMBOL,"[")):(q(e),B(e,j.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=P(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){K(e);continue}}et(n)?Z(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(B(e,j.UNKNOWN,n),q(e)):X(e):J(e)}else q(e),B(e,j.OPERATOR,"]")}else q(e),B(e,j.OPERATOR,"}");else q(e),B(e,j.OPERATOR,"{");else z(e)}else U(e);else tt(e)?W(e):Z(e);else _(e)}else V(e);else F(e)}return e.tokens}(t);return new Ze(n,e,t).parse()}Ze.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Ze.PRATT_TABLE=Et,Ze.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Xe{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 0;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 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Ke(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ge(t){return{ok:1,value:t}}function Ye(t){return{ok:0,error:t}}function Qe(t){return 1==t.ok}const tn=new Map,en=new WeakMap;function nn(t){let e=en.get(t);return e||(e=new Map,en.set(t,e)),e}function rn(t){return t.owner||(t.me instanceof Element?t.me:null)}function sn(t,e){const n=rn(t);if(n)return Lt(e,t),nn(n).get(e)}function on(t,e,n){const r=rn(t);r&&(nn(r).set(e,n),Ot(e,n,t))}function an(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||tn,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}function cn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function un(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function ln(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 fn(t,e,n,r){if("element"!==r){if("global"===r)return jt(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void jt(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Ot(t,e,n);if(n.globals&&n.globals.has(t))return jt(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 jt(n,t,e);n.locals.set(t,e),Ot(t,e,n)}}else on(n,t,e)}function hn(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function dn(t){if(cn(t))return[t];if(Array.isArray(t)){const e=t.filter(cn);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(cn);return e.length>0?e:null}return null}const pn=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...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 0;if(n.isType(t))return 1;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:1,direct:1}:{possible:0,direct:0}}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:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0: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=>1,defaultValue:null,description:"Unknown/any value type"})}};function mn(t){const e=pn.get("String");return e?e.isType(t):"string"==typeof t}function yn(t){const e=pn.get("Number");return e?e.isType(t):"number"==typeof t}function gn(t){const e=pn.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function vn(t){const e=pn.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function bn(t){const e=pn.get("Function");return e?e.isType(t):"function"==typeof t}function wn(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function En(t){return t instanceof Element}function xn(t){return t instanceof HTMLElement}const kn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Sn(t,e){return kn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const An={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 0;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=>wn(t)?t.tabIndex:void 0,hidden:t=>wn(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 Tn(t,e){if(e.startsWith("*"))return function(t,e){if(!xn(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 xn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return Sn(t,e.slice(1));const n=An[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Sn(t,e);const r=t[e];return bn(r)?r.bind(t):r}const $n={1:"one",2:"two",3:"three",4:"four",5:"five"};function Cn(t,e,n,r){return t.length!==e?`${n} requires exactly ${i=e,$n[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var i}function Nn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Rn(t,e,n){return Cn(t,1,e,n)??Nn(t,0,e,n)}function On(t,e){return Cn(t,2,e,"left, right")}function Ln(){return null}function jn(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 Mn(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const In={conversions:{dynamicResolvers:[]}},Pn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":mn(t)?t:vn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(gn(t))return t;if(null==t)return 0;if(mn(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return yn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(yn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(yn(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(!yn(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=Pn.Number(t);return Math.trunc(e)},Float:t=>{const e=Pn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(mn(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(!mn(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(vn(t))return t;if(mn(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=>mn(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:Pn.String(t)).join(""):t instanceof Element?t.outerHTML:Pn.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=qn(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]=qn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?Pn.Values(t,e):t;if(!vn(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=Pn.Values(t,e);return Pn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=Pn.Values(t,e);return JSON.stringify(n)}};function qn(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 Hn={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 Bn(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 Pn.Number(t).toFixed(n??0)}if(null==t)return t;let r=Pn[e];if(r)return r(t,n);const i=Hn[e.toLowerCase()];if(i&&(r=Pn[i],r))return r(t,n);const s=In.conversions[e];if("function"==typeof s)return s(t,n);for(const n of In.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Dn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Bn(n,r,t)},validate:t=>Cn(t,2,"as","value, type")??Nn(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(!mn(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 mn(n);case"number":return yn(n)&&!isNaN(n);case"boolean":return gn(n);case"object":return vn(n);case"array":return Array.isArray(n);case"function":return bn(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||vn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>Cn(t,2,"is","value, type")??Nn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Cn(t,1,"async","expression")}},Fn=new Set(["__proto__","constructor","prototype"]);function Vn(t,e){if(t instanceof Element)return Tn(t,e);if(vn(t)){if(Fn.has(e))return;return t[e]}return t[e]}function _n(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return 0;e=Array.from(t)}return 0===e.length?0:e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const Un={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 _n(n)&&!(r in n)?Array.from(n,t=>Vn(t,r)):Vn(n,r)}},validate:t=>Cn(t,2,"possessive","element, property")??Nn(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 Tn(t.me,n);if(vn(t.me)){if(Fn.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Rn(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 Tn(r,n);if(vn(r)){if(Fn.has(n))return;return r[n]}return r[n]},validate:t=>Rn(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 Tn(t.you,n);if(vn(t.you)){if(Fn.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Rn(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 Tn(r,n);if(vn(r)){if(Fn.has(n))return;return r[n]}return r[n]}},validate:t=>Cn(t,2,"of","property, object")??Nn(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=>Mn(t,1,2,"attribute","attributeName, optional element")??Nn(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:0},validate:t=>Mn(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Nn(t,0,"attributeWithValue","attribute name")??Nn(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=>Rn(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=>Rn(t,"idReference","idValue")}};function Wn(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 zn(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 Zn(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 Jn(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 er(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return er(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await Jn(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?jt(e,t.slice(1),n):"global"===i.scope?jt(e,t,n):"element"===i.scope?on(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 Jn(t.left,e);return n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith(".")?n.classList.contains(r.value.slice(1)):0}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 Jn(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 Jn(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 Jn(t.right,e);return zn(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=nr(t.left);if(n){const r=await Jn(t.right,e);let i=r;for(const t of n){if(null==i)return;i=En(i)?Tn(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const s=await Jn(t.left,e);if("and"===n){if(!s)return s;const n=await Jn(t.right,e);return zn(e,"and").evaluate(e,s,n)}if("or"===n){if(s)return s;const n=await Jn(t.right,e);return zn(e,"or").evaluate(e,s,n)}const o=await Jn(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(s):s,u=t.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=ln(n)),"string"==typeof r&&(r=ln(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:Zn(await zn(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return Zn(await zn(e,"subtraction").evaluate(e,{left:s,right:o}));case"*":return Zn(await zn(e,"multiplication").evaluate(e,{left:s,right:o}));case"/":return Zn(await zn(e,"division").evaluate(e,{left:s,right:o}));case"%":case"mod":return Zn(await zn(e,"modulo").evaluate(e,{left:s,right:o}));case"^":case"**":return Zn(await zn(e,"power").evaluate(e,{left:s,right:o}));case">":case"is greater than":return zn(e,"greaterThan").evaluate(e,s,o);case"<":case"is less than":return zn(e,"lessThan").evaluate(e,s,o);case">=":case"is greater than or equal to":return zn(e,"greaterThanOrEqual").evaluate(e,s,o);case"<=":case"is less than or equal to":return zn(e,"lessThanOrEqual").evaluate(e,s,o);case"==":return zn(e,"equals").evaluate(e,c,u);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=sr(t,s,o);return void 0!==n?n:zn(e,"equals").evaluate(e,c,u)}case"!=":return zn(e,"notEquals").evaluate(e,c,u);case"is not":case"is not equal":case"is not equal to":{const n=sr(t,s,o);return void 0!==n?!n:zn(e,"notEquals").evaluate(e,c,u)}case"===":case"really equals":case"is really":case"is really equal to":return zn(e,"strictEquals").evaluate(e,c,u);case"!==":case"is not really":case"is not really equal to":return zn(e,"strictNotEquals").evaluate(e,c,u);case"as":return zn(e,"as").evaluate(e,s,ar(o));case"contains":case"contain":case"includes":case"include":return zn(e,"contains").evaluate(e,c,u);case"does not contain":case"do not contain":case"does not contains":case"does not include":return zn(e,"doesNotContain").evaluate(e,c,u);case"starts with":return zn(e,"startsWith").evaluate(e,c,u);case"ends with":return zn(e,"endsWith").evaluate(e,c,u);case"does not start with":return!await zn(e,"startsWith").evaluate(e,c,u);case"does not end with":return!await zn(e,"endsWith").evaluate(e,c,u);case"match":case"matches":return zn(e,"matches").evaluate(e,c,ir(t.right,u));case"does not match":case"do not match":return!await zn(e,"matches").evaluate(e,c,ir(t.right,u));case"in":case"is in":case"am in":return rr(s,o);case"is not in":case"am not in":return!rr(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return or(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!or(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return or(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!or(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 Jn(t.expression,e),r=ar(t.targetType);return zn(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await Jn(t.value,e),r=await Jn(t.min,e),i=await Jn(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],u=await zn(e,"between").evaluate(e,o,a,c);return t.negated?!u:u}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return 1;if(Object.prototype.toString.call(t).slice(8,-1)===e)return 1;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await Jn(t.value,e),t.typeName+"",0!=t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await Jn(t.collection,e);if(null==n)return n;const r=async(t,n)=>Jn(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=Wn(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=[...Wn(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=Wn(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return s=await Jn(t.right,e),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return Wn(t).map(t=>null==t?"":t+"").join(n)}(n,await Jn(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 Jn(n,e);switch(t.operator){case"not":case"!":return zn(e,"not").evaluate(e,r);case"no":return zn(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return zn(e,"exists").evaluate(e,r);case"does not exist":return zn(e,"doesNotExist").evaluate(e,r);case"is empty":return zn(e,"isEmpty").evaluate(e,r);case"is not empty":return zn(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 Jn(t.object,e);if(t.computed){const r=await Jn(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return fr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await Jn(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await fr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await Jn(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>Jn(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return hr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:Jn(t,n))):Promise.all(t.map(t=>Jn(t,n)))}(t.arguments,r,e);switch(r){case"closest":return zn(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?dr(await Jn(n.from,e)):e.me,s=n.within?dr(await Jn(n.within,e)):void 0,o=n.inElt?await Jn(n.inElt,e):void 0;return zn(e,r).evaluate(e,i[0],t,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return zn(e,r).evaluate(e,...i)}case"first":return zn(e,"first").evaluate(e,...i);case"last":return zn(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=>Jn(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await Jn(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 zn(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=vr(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>Yn(t.expr,e)));return br(n,r)}(n,e),s=yr(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await zn(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 lr(t,/\{([^}]*)\}/g,async(t,n)=>(await Yn(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?yr(t,n):n;return hn(await zn(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 zn(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return zn(e,"me").evaluate(e);case"your":case"yourself":return zn(e,"you").evaluate(e);case"its":return zn(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??zn(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return zn(e,"document").evaluate(e);case"window":return zn(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await Jn(t.object,e),r=t.property.name;return zn(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 Jn(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await Jn(t.test,e)?Jn(t.consequent,e):t.alternate?Jn(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 Jn(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 Jn(t,e)+"",n[i]=await Jn(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 Jn(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return zn(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await lr(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=ur(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(ur(n,e)??"")+""}catch{return""}}),n=await lr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await Yn(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await Jn(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return cr(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class Xn extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Kn(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 Xn("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Xn("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=vr(t),r=n.filter(t=>"expr"in t).map(t=>Gn(t.expr,e));return br(n,r)}(n,e),s=yr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Xn("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)=>(Gn(n.trim(),e)??"")+"")}(n,e):n,i=yr(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new Xn("selector");return hn(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?sn(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 Xn("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>Kn(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:Kn(t,e)+"",n[i]=Kn(r.value,e)}return n}(n,e);case"asExpression":return Bn(Kn(n.expression,e),ar(n.targetType),e);case"stringPostfix":return`${Kn(n.expression,e)}${n.unit}`;case"blockLiteral":return cr(n,e);case"memberExpression":{const t=Kn(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new Xn("memberExpression");const r=t[n.computed?Kn(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new Xn(n?.type??"unknown")}}function Gn(t,e){const n=Je(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return Kn(n.node,e)}async function Yn(t,e){const n=Je(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 tr()};return Jn(n.node,r)}let Qn=null;async function tr(){if(!Qn){const t=await Promise.resolve().then(function(){return vo});Qn=t.createFullExpressionRegistry()}return Qn}async function er(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?zn(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?zn(e,"you").evaluate(e):"it"===n||"its"===n?zn(e,"it").evaluate(e):"result"===n?zn(e,"result").evaluate(e):"window"===n?zn(e,"window").evaluate(e):"document"===n?zn(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?(Rt(n,e),e.globals.get(n)):"element"===t.scope?sn(e,n):e.locals&&e.locals.has(n)?(Lt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&Rt(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(Rt(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 nr(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=nr(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 rr(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 ir(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function sr(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?1==i:void 0}function or(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function ar(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 cr(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 Kn(t.body,s)}catch(e){if(e instanceof Xn)return Jn(t.body,s);throw e}}}function ur(t,e){if(e.locals?.has(t))return Lt(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 lr(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 fr(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?Tn(t,e):_n(t)&&!(e in t)?zn(n,"possessive").evaluate(n,t,e):t?.[e]}const hr=new Set(["closest","previous","next"]);function dr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const pr=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"),mr=/[:&()[\]/]/g;function yr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(pr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(mr,"\\$&")}(e)}const gr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function vr(t){const e=[];let n,r=0;for(gr.lastIndex=0;null!==(n=gr.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 br(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++];En(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class wr{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??0}registerListener(t,e,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&lt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&lt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&lt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&lt("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&&lt("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&&lt(`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&&lt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&lt(`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&&lt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&lt(`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 Er{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&lt("[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 0}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 lt("[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)):0}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 xr{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??1,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??1,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)?1: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){lt(`[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 kr={evaluate:(t,e)=>Jn(t,e)};class Sr{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 Ar{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:Array.isArray(t)?t.join(" | "):t||""}}async execute(t,...e){const n=e[0],r=this.createHookContext(t,e,n&&"object"==typeof n&&"modifiers"in n&&n.modifiers||{});try{if(at(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void at(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Sr.toTyped(t);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(at(`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 Jn(r,t))return void at(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},kr,t)}else s=e;else at(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=e;if(at("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 at("CommandAdapterV2: Command result:",o),Object.assign(t,Sr.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Or(t)||at(`CommandAdapterV2: Error executing '${this.name}':`,t),this.hookRegistry&&t instanceof Error)throw await this.hookRegistry.runOnError(r,t);throw t}}validate(t){return this.impl.validate?this.impl.validate(t):{isValid:1,errors:[],suggestions:[]}}}class Tr{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);lt(`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();lt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Ar(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:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let $r=null;function Cr(){return $r||($r=function(){const t=new Tr,e=new Er,n=new xr,r=new Set,i={commands:t,eventSources:e,context:n,use(s){if(r.has(s.name))lt(`[LokaScriptRegistry] Plugin '${s.name}' is already installed`);else{if(s.commands)for(const e of s.commands)t.register(e);if(s.eventSources)for(const t of s.eventSources)e.register(t.name,t);if(s.contextProviders)for(const{name:t,provide:e,options:r}of s.contextProviders)n.register(t,e,r);s.setup?.(i),r.add(s.name)}},reset(){r.clear()}};return i}()),$r}class Nr{constructor(t={}){this.contextCache=new WeakMap;const e=Cr();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,lt(`[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),lt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return lt("[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 lt(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return lt(`[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 lt(`[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,lt("[RegistryIntegration] Destroyed")}}function Rr(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Or(t){return t instanceof Error?null!==Ke(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Lr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const jr=new WeakMap;function Mr(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)Mr(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&&Mr(n[t],e);return e}class Ir{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=tn,this.hookRegistry=new Xe,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new wr,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Nr("object"==typeof t.registryIntegration?t.registryIntegration:{}),lt("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&&lt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}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(),lt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){lt(`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 lt("\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(!Qe(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Rr(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=Ke(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(!Qe(r))throw Rr(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(!Qe(n))throw Rr(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(at(`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 Or(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=Ke(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(at(`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 Ge(await o.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ye(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];lt("\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(!Qe(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}),Ge(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!Qe(t))return t;n=t.value}}return Ge(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await Jn(t,n);return Lr(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 Ge(await Jn(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ye({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ye({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ye({type:"break"});if(e.isContinue)return Ye({type:"continue"});if(e.isReturn)return Ye({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!Qe(r))return r;const i=r.value;if(Lr(i)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:i.command,args:[{type:"literal",value:i.selector}]},e);try{return Ge(await this.executeCommandFromPattern(i.command,i.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ye(e);throw t}}return Ge(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 u=async t=>{const e=await n.executeCommandSequenceWithResult(t,c);if(!Qe(e))throw Ke(e.error);return e.value};if(!s&&!o)return await u(i);try{return await u(i)}catch(t){if(!s||Or(t))throw t;return a&&c.locals.set(a,t),await u(s)}finally{o&&await u(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(Or(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Or(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Or(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(Or(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(Or(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}),lt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),lt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){lt("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&&(lt(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),lt(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));lt("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:0,returned:0,broke:0,continued:0,async:0},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){lt("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))]),lt("BEHAVIOR: Init block completed for "+t)}catch(e){if(lt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Or(e)))throw e}}if(lt(`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))])}lt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:s,args:o,selector:a,condition:c,attributeName:u,watchTarget:l,modifiers:f,errorSymbol:h,errorHandler:d,finallyHandler:p}=t,m=r&&r.length>0?r:[n];lt(`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);lt(`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 lt(`BEHAVIOR: Target resolution: querying for '${s}'`),y=this.queryElements(s,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void lt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&u)return void this.setupMutationObserver(y,u,i,e);if("change"===n&&l)return void this.setupChangeObserver(l,i,e);const v=t.customEventSource;if(v&&this.registryIntegration){lt(`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);lt(`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);lt(`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=Ir.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:1}: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:0,cancelable:0});if(t.synthetic=1,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=jr.get(a)??0;if(c>=100)return;if(jr.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{lt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const u=new Map(n.locals),l={...n,locals:u,it:a,event:a};u.has("target")||l.locals.set("target",a.target);const f=t.enhanceContext(l);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 Mr(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 lt("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(Or(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||Or(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){lt(`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){ct(`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(Or(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),lt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){lt("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))),lt(`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){ct("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(Or(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,r),lt("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 lt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}function Pr(...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 qr(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 Hr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Ln},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Ln},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Ln},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:Ln},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:Ln},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=>Rn(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=>Rn(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=>Rn(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=>Rn(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:Ln},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Ln},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Ln},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=>Rn(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 qr(i,n)},validate:t=>Mn(t,1,2,"styleRef","property, optional element")??Nn(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 qr(i,r)},validate:t=>Cn(t,2,"possessiveStyleRef","possessor, property")??Nn(t,0,"possessiveStyleRef","possessor")??Nn(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 qr(i,n)},validate:t=>Cn(t,2,"ofStyleRef","property, reference")??Nn(t,0,"ofStyleRef","property")??Nn(t,1,"ofStyleRef","reference")}};function Br(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Dr=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Fr;function Vr(){return Fr({validate:t=>({success:1,data:t})})}function _r(t,e){if(Dr)return Vr();const n=Fr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:Br("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:0,error:Br("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:0,error:Br("missing-argument",`Required field "${e}" is missing`,e)};const s=n.validate(t);if(!s.success)return{success:0,error:Br("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:1,data:i}}});return n.strict=()=>_r(t,{strict:1}),n}Fr=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:1,data:e.data}:{success:0,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:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return Fr(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:0,error:Br("runtime-error",`String must be at least ${t} characters long`)}:r}};return Fr(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:0,error:Br("runtime-error",`String must be at most ${t} characters long`)}:r}};return Fr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:1,validate:n=>void 0===n?{success:1,data:t}:e(n)};return Fr(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:0,error:Br("runtime-error",e||"Refinement validation failed")}:i}};return Fr(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 Ur=t=>function(t={}){return Dr?Vr():Fr({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:Br("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:Br("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:Br("runtime-error",`String must be at most ${t.maxLength} characters long`)}:t.pattern&&!t.pattern.test(e)?t.pattern.source.startsWith("^")&&t.pattern.source.endsWith("$")?{success:0,error:Br("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:Br("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),Wr=t=>_r(t),zr=t=>function(t){return Dr?Vr():Fr({validate:e=>{if(!Array.isArray(e))return{success:0,error:Br("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:Br("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:0,error:Br("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:1,data:n}}})}(t),Zr=()=>Vr();class Jr{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 Xr=new class{constructor(){this.domQueryCache=new Jr(200,3e3),this.exprResultCache=new Jr(500,2e3),this.cssMatchCache=new Jr(100,5e3),this.formValueCache=new Jr(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(()=>{Xr.cleanup()},1e4);const Kr=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=Xr.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 Gr(){Xr.cleanup(),Kr.getMetrics().memoryUsage>52428800&&Kr.reset()}let Yr=null;function Qr(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 Qr(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 ti(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 ei(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 ni(t){try{return Qr(t,"_"),1}catch{return 0}}function ri(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 1;default:return 0}switch(n){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(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=ti(t),r=ti(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 ii(t,e);case"!=":return!ii(t,e);default:return 0}}function ii(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;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?ii(t?1:0,e):"boolean"==typeof e?ii(t,e?1:0):t+""==e+""}function si(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function oi(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function ai(t,e,n,r,i,s=1,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 ci(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){Yr&&clearInterval(Yr),Yr=setInterval(Gr,t)}();const ui=zr([Zr(),Zr()]),li=zr([Zr(),Ur()]),fi={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return ai(this,t,[e,n],e==n,r)}catch(i){throw ai(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>On(t,"equals"),inputSchema:ui,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],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:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,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"]}},hi={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&&ai(this,t,[e,n],i,r?Date.now():0),i},validate:t=>On(t,"strictEquals")},di={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&&ai(this,t,[e,n],i,r?Date.now():0),i},validate:t=>On(t,"notEquals")},pi={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&&ai(this,t,[e,n],i,r?Date.now():0),i},validate:t=>On(t,"strictNotEquals")},mi={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=ri(e,n,"<");return r&&ai(this,t,[e,n],s,i),s},validate:t=>On(t,"lessThan")},yi={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=ri(e,n,"<=");return r&&ai(this,t,[e,n],s,i),s},validate:t=>On(t,"lessThanOrEqual")},gi={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=ri(e,n,">");return r&&ai(this,t,[e,n],s,i),s},validate:t=>On(t,"greaterThan")},vi={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=ri(e,n,">=");return r&&ai(this,t,[e,n],s,i),s},validate:t=>On(t,"greaterThanOrEqual")},bi={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return ai(this,t,[e,n],e&&n,r)}catch(i){throw ai(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>On(t,"and"),inputSchema:ui,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,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:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,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"]}},wi={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&&ai(this,t,[e,n],i,r?Date.now():0),i},validate:t=>On(t,"or")},Ei={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&ai(this,t,[e],r,n?Date.now():0),r},validate:t=>Cn(t,1,"not","operand")},xi={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?1:mn(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:vn(e)?0===Object.keys(e).length:0,n&&ai(this,t,[e],i,r),i},validate:t=>Cn(t,1,"isEmpty","value")},ki={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||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:(mn(e),0),n&&ai(this,t,[e],i,r),i},validate:t=>Cn(t,1,"no","value")},Si={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 xi.evaluate(t,e);return n&&ai(this,t,[e],i,r),i},validate:t=>Cn(t,1,"isNotEmpty","value")},Ai={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=Ti(e);return n&&ai(this,t,[e],i,r),i},validate:t=>Cn(t,1,"exists","value")};function Ti(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const $i={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=!Ti(e);return n&&ai(this,t,[e],i,r),i},validate:t=>Cn(t,1,"doesNotExist","value")},Ci={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(ci(e)&&ci(n))return s=e.contains(n),r&&ai(this,t,[e,n],s,i),s;if(mn(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&ci(n))return s=o.contains(n),r&&ai(this,t,[e,n],s,i),s;if(o&&mn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=a?o.contains(a):0,r&&ai(this,t,[e,n],s,i),s}}if(mn(n)&&n.match(/^[.#][\w-]+$/)&&ci(e)){const o=document.querySelector(n);return s=o?e.contains(o):0,r&&ai(this,t,[e,n],s,i),s}}if(mn(e)&&mn(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=vn(e)&&mn(n)?n in e:0;return r&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"contains","container, value")},Ni={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 Ci.evaluate(t,e,n);return r&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"doesNotContain","container, value")},Ri={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+""):0;return r&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"startsWith","str, prefix")},Oi={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+""):0;return r&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"endsWith","str, suffix")},Li={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&&ai(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>Cn(t,3,"between","value, min, max")},ji={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&mn(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 Xr.matches(t,e)}(e,t)}catch(t){i=0}else i=0}else if(mn(e)&&mn(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=0;return ai(this,t,[e,n],i,r)}catch(i){throw ai(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>Cn(t,2,"matches","element, selector"),inputSchema:li,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,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:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,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"]}},Mi={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=0;if(e instanceof Element&&mn(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&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"has","element, selector")},Ii={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 Mi.evaluate(t,e,n);return r&&ai(this,t,[e,n],s,i),s},validate:t=>Cn(t,2,"doesNotHave","element, selector")},Pi={equals:fi,strictEquals:hi,notEquals:di,strictNotEquals:pi,lessThan:mi,lessThanOrEqual:yi,greaterThan:gi,greaterThanOrEqual:vi,and:bi,or:wi,not:Ei,no:ki,isEmpty:xi,isNotEmpty:Si,exists:Ai,doesNotExist:$i,contains:Ci,doesNotContain:Ni,startsWith:Ri,endsWith:Oi,between:Li,matches:ji,has:Mi,doesNotHave:Ii};class qi{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 0==t||0===t||0n===t||""===t||null==t||yn(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:0,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:0,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":vn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":mn(t)?"String":yn(t)?"Number":gn(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):mn(t)?t.split(""):null==t?[]:vn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(yn(t)&&Number.isFinite(t))return t;if(mn(t)){const e=Number(t);return Number.isFinite(e)?e:null}return gn(t)?t?1:0:null}}const Hi=Wr({value:Ur().describe("String literal value")}).strict(),Bi=Wr({value:function(t={}){return Dr?Vr():Fr({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:Br("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:Br("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:Br("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}({}).describe("Number literal value")}).strict(),Di=Wr({value:(Dr?Vr():Fr({validate:t=>"boolean"!=typeof t?{success:0,error:Br("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}})).describe("Boolean literal value")}).strict(),Fi=Wr({left:Zr().describe("Left operand"),right:Zr().describe("Right operand")}).strict();const Vi={stringLiteral:new class extends qi{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=Hi,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,0),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,1,i),s}catch(e){return this.trackSimple(t,n,0),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)?(Lt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends qi{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Bi,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,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),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 qi{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Di,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,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),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 qi{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Fi,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,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=Qr(e.left,"left operand")+Qr(e.right,"right operand");return this.trackSimple(t,n,1,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,0),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 qi{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=Fi,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,0),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,1,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,0),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=Fi.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(mn(t))return t;if(yn(t))return""+t;if(gn(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends qi{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Fi,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,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=Qr(e.left,"left operand")*Qr(e.right,"right operand");return this.trackSimple(t,n,1,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,0),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"])}}}};function _i(){return Pr(Hr,Pi,Vi)}class Ui{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,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:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}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=an(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function Wi(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,u="getter"===c?"get":"setter"===c?"set":"value",l=!e&&t?r.static?t:t.prototype:null,f=e||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),h=0,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[u],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[u]=a)}l&&Object.defineProperty(l,r.name,f),h=1}function zi(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 Zi(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:n?"".concat(n," ",e):e})}function Ji(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function Xi(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 Ki(t,e){for(const n of t)e(n);return t}function Gi(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function Yi(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 Qi(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&&es(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&&es(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&es(n)?[n]:[]}function ts(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function es(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return ts(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function ns(t,e){return t.map(t=>{if(ts(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+"":(at(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function rs(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function is(t){return{isBlocking:0,hasBody:0,version:"1.0.0",...t}}function ss(t){return()=>new t}function os(t,e){return e}function as(t,e,n){if(cn(t))return t;if(!t){const t=e.me;if(!t)throw Error(os(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(os(0,'Context reference "me" is not available'));return cs(e.me)}if("it"===n){if(!cn(e.it))throw Error(os(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(os(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(os(0,"DOM not available \u2014 cannot resolve element selector"));const i=r.querySelector(n);if(!i)throw Error(os(0,"Element not found with selector: "+n));if(!cn(i))throw Error(os(0,"Element found but is not an HTMLElement: "+n));return i}throw Error(os(0,"Invalid target type: "+typeof t))}function cs(t){if(cn(t))return t;throw Error("Value is not an HTMLElement")}function us(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(os(0,'No "me" element in context'));if(!cn(e.me))throw Error(os(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(os(0,'No "it" value in context'));if(!cn(e.it))throw Error(os(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(os(0,'No "you" element in context'));if(!cn(e.you))throw Error(os(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(os(0,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const ls=["on","from","to","in","with","at"];async function fs(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?!ls.includes(e.name.toLowerCase()):1})),(!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(!cn(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(cn(i))a.push(i);else if(un(i)){const t=Array.from(i).filter(cn);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(cn);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(cn);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(!cn(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function hs(t){return"string"==typeof t&&t.trim().startsWith("*")}function ds(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 ps(t,e,n){t.style.setProperty(e,n)}const ms=["dialog","details","summary","select"];function ys(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 gs(t,e,n){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const n=ys(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const n=ys(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:ys(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=ys(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:ys(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class vs{async resolveTargets(t,e,n,r){return fs(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return gs(t,e,n)}parseClassNames(t){return Qi(t)}isAttribute(t){return Ji(t.trim())}isCSSProperty(t){return hs(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>cn(t))}(t)}validateType(t,e){return function(t,e){return"string"==typeof t&&e.includes(t)}(t,e)}validateStringArray(t,e=1){return Array.isArray(t)&&function(t,e=1){return Array.isArray(t)&&t.length>=e&&t.every(t=>"string"==typeof t&&t.length>0)}(t,e)}}let bs=(()=>{let t,e,n=[rs({name:"add"})],r=[],i=vs;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=Xi(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=ns(t.classes,e);n.length>0&&Gi(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Ki(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":Gi(t.targets,Object.entries(t.styles),(t,[e,n])=>{t.style.setProperty(e,n)})}var n,r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const n=e.styles;if(0===Object.keys(n).length)return 0;if(!Object.values(n).every(t=>"string"==typeof t))return 0}return 1}};return Zi(e,"AddCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Wi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=is({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"}),zi(e,r),s=e})();const ws=ss(bs),Es={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function xs(t){return t.includes("<")&&t.includes(">")}function ks(t,e,n){!function(t,e,n){"replace"!==n?cn(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').`);xs(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){cn(e)?(t.innerHTML="",t.appendChild(e)):xs(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,function(t){const e=Es[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(Es).join(", ")}.`);return e}(n))}function Ss(t){return t.parentNode?(t.remove(),1):0}let As=(()=>{let t,e,n=[rs({name:"remove"})],r=[],i=vs;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(cn(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&cn(r[0]))return{type:"element",targets:r.filter(t=>cn(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Xi(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=ns(t.classes,e);n.length>0&&Gi(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Ki(t.targets,t=>{t.removeAttribute(n)});break;case"styles":Gi(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)Ss(e)}var n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}};return Zi(e,"RemoveCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Wi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=is({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"}),zi(e,r),s=e})();const Ts=ss(As);function $s(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 Cs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=$s(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Ns(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Rs(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&Yi(t,n)}}function Os(t,e,n,r){const i=Rs(t,e,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function Ls(t,e,n,r){const i=Rs(t,e,n),s=()=>{i(),t.removeEventListener(r,s)};return t.addEventListener(r,s,{once:1}),()=>{t.removeEventListener(r,s)}}function js(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(0==n?t.removeAttribute(r):t.setAttribute(r,1==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 Ms=/^the\s+(.+?)\s+of\s+(.+)$/i,Is=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 Ps(t){return"string"==typeof t&&Ms.test(t)}function qs(t,e){const n=t.match(Ms);if(!n)return null;try{return{element:as(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Hs(t,e,n){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(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]),cn(i)?{element:i,property:r}:null}(t,e,n);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(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]),cn(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]),!cn(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function Bs(t,e){const{element:n,property:r}=t;r.startsWith("*")?ps(n,r.substring(1),e+""):js(n,r,e)}async function Ds(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=$s(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}}const Fs=ss((()=>{let t,e,n=[rs({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=0;if(function(t){if(!t||"asExpression"!==t.type)return 0;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=1;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 Ds(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 u={filterPrepositions:1,fallbackModifierKey:"on"},l=await fs(c,e,n,"toggle",u,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:l,duration:r,untilEvent:i}}const o=await Hs(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 Ds(t.modifiers,e,n),a=ds(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:s,untilEvent:o}}}}const o=ds(r);if(o){const{duration:r,untilEvent:i}=await Ds(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await fs(t.args.slice(s),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await Ds(t.modifiers,e,n),{value:u}=await gs(i,e,n);if(Ps(u)){const t=qs(u,n);if(t)return{type:"property",target:t}}const{type:l,expression:f}=function(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return ms.includes(e)}(e)}(e);if(cn(t)||Array.isArray(t)&&t.every(t=>cn(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 0;const e=t.toLowerCase();return ms.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(u,i),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:i}=Xi(f);return{type:"attribute",name:r,value:i,targets:await fs(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=ds(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await fs(t.args.slice(1),e,n,"toggle",h,t.modifiers)}}case"element":{let s;if(cn(u))s=[u];else if(Array.isArray(u)&&u.every(t=>cn(t)))s=u;else if(f){const t=document.querySelectorAll(f);s=Array.from(t).filter(t=>cn(t))}else s=await fs([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:Ns(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:Qi(f),targets:s,duration:a,untilEvent:c}}default:{const r=Qi(f||u);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await fs(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=ns(t.classes,e);if(0===n.length)return[...t.targets];if(Gi(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&Os(e,"class",n[0],t.duration),t.untilEvent&&Ls(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Ki(t.targets,t=>{Yi(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Os(e,"attribute",t.name,t.duration),t.untilEvent&&Ls(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Ki(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)):Tn(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Is.has(r)||Is.has(r.toLowerCase())){const n=!e;return Bs(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Bs(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(Bs(t,i),i):(t.element[r]=e,Bs(t,""),"")}Bs(t,!e)}(t.target),[t.target.element];case"dialog":return Ki(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 Ki(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Ki(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:1,cancelable:1});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&&Os(e,"class",t.classA,t.duration),t.untilEvent&&Ls(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return Zi(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})());class Vs{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await fs(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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>cn(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}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 _s=(()=>{let t,e,n=[rs({name:"show"})],r=[],i=Vs;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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>cn(t))?"string"!=typeof e.defaultDisplay?0:1:0}};return Zi(e,"ShowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Wi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=is({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"}),zi(e,r),s=e})();const Us=ss(_s);let Ws=(()=>{let t,e,n=[rs({name:"hide"})],r=[],i=Vs;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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>cn(t))?1:0}};return Zi(e,"HideCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;Wi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=is({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"}),zi(e,r),s=e})();const zs=ss(Ws),Zs=ss((()=>{let t,e,n=[rs({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 u=await e.evaluate(a,n),l=this.mapPosition(o);let f,h,d=null;if(c){const t=r(c),i=await Hs(c,e,n);if(i)return{value:u,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:u,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&&Ps(t)){const e=qs(t,n);if(e)return{value:u,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=dn(await e.evaluate(c,n));if(r)return{value:u,targets:r,position:l,memberPath:f};h=t}}else{const t=await e.evaluate(c,n),r=dn(t);if(r)return{value:u,targets:r,position:l,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?d=t:h=t)}}return h?{value:u,targets:[],position:l,memberPath:f,variableName:h}:{value:u,targets:await this.resolveTargets(d,n),position:l,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)ks(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||!cn(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=>cn(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}(t)}parseValue(t){return cn(t)?t:null==t?"":t+""}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["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()):0}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 Zi(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})());async function Js(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return cn(i)?i:null}const Xs=ss((()=>{let t,e,n=[rs({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=St.get(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 Js(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await Js(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 Hs(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 0;if(cn(t)||t instanceof Node)return 0;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(Ps(a)){const r=qs(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&&hs(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&&Ji(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=us(r[1],n),s=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:s}}}if(cn(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&cn(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?on(e,t.name,t.value):"global"===t.scope?fn(t.name,t.value,e,"global"):fn(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 js(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return ps(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))js(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=us(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 function(t,e){if(Array.isArray(t))return t.filter(cn);if(un(t))return Array.from(t).filter(cn);if(cn(t))return[t];if(!t){const t=e.me;return t&&cn(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&cn(e.me)?[e.me]:[];if("it"===n)return cn(e.it)?[e.it]:[];if("you"===n)return e.you&&cn(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(cn)}}return[]}(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 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;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(cn)&&"value"in e;case"property":return"string"==typeof e.property&&cn(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&cn(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 0}}};return Zi(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})());function Ks(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}let Gs=(()=>{let t,e,n=[rs({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,u;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 l=t.modifiers?.on||t.modifiers?.to;if(l)u=await this.resolveTargets([l],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return 0;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);u=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");u=[n.me]}}return{eventName:a,detail:c,targets:u,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:1,cancelable:void 0!==n.cancelable?n.cancelable:1,composed:void 0!==n.composed?n.composed:0})}(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(cn(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(cn));else if(Array.isArray(t))i.push(...t.filter(cn));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(cn));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()]=Ks(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:1,cancelable:1,composed:0},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=1:"nobubbles"===e?r.bubbles=0:"cancelable"===e?r.cancelable=1:"nocancelable"===e?r.cancelable=0:"composed"===e&&(r.composed=1)}}return r}};return Zi(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})();const Ys=ss(Gs),Qs=ss((()=>{let t,e,n=[rs({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?0:Array.isArray(t.values)}};return Zi(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})());function to(t,e,n,r){return t?new Promise(n=>{const i=()=>{s({event:null,timedOut:0,cancelled:1})},s=function(n,s){let a=0;return n=>{a||(a=1,t.removeEventListener(e,o),r&&r.removeEventListener("abort",i),s(n))}}(0,n),o=t=>{s({event:t,timedOut:0,cancelled:0})};r?.aborted?n({event:null,timedOut:0,cancelled:1}):(t.addEventListener(e,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function eo(t){return new Promise(e=>setTimeout(e,t))}const no=ss((()=>{let t,e,n=[rs({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 eo(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await to(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:Cs(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:Cs(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:Cs(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?eo(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):to(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 Zi(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Wi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=is({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"}),zi(e,r),i=e})()),ro=function(t,e){const n=new Tr(null);for(const e of t)n.register(e);return new Ir({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([ws(),Ts(),Fs(),Us(),zs(),Zs(),Xs(),Ys(),Qs(),no()],{expressionRegistry:_i()}),io={parse:t=>Je(t),execute:async(t,e)=>{const n=function(t){if(!t)return an();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=an(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=Je(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await ro.execute(r.node,n)}},so=function(t){return new Ui(t)}(io),oo={runtime:io,parse:t=>io.parse(t),execute:async(t,e)=>io.execute(t,e),createContext:an,attributeProcessor:so,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>io.execute(t,e),init:()=>{so.init()}};"undefined"!=typeof window&&(window.hyperfixi=oo,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{so.init()}):so.init());const ao={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:mn(n)?n.length>0?n[0]:null:vn(n)&&"length"in n&&yn(n.length)&&n.length>0?n[0]:null},validate:t=>jn(t,1,"first","collection")},co={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 mn(n)?n.length>0?n[n.length-1]:null:vn(n)&&"length"in n&&yn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>jn(t,1,"last","collection")},uo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!yn(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(mn(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(vn(s)&&"length"in s&&yn(s.length)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}return null},validate:t=>Mn(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function lo(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?lo(r,e):null}function fo(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?fo(r,e):null}function ho(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 po(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 mo={first:ao,last:co,at:uo,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?ho(s,n,i,1):lo(s,n):s.nextElementSibling:null},validate:t=>jn(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?ho(s,n,i,0):fo(s,n):s.previousElementSibling:null},validate:t=>jn(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=po(t);for(const t of r)if(po(t)>i)return t;return null}(s,n,o):null},validate:t=>Mn(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=po(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>po(e))return e}return null}(s,n,o):null},validate:t=>Mn(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")}};class yo{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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ei(Qr(t,"left operand")+Qr(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[oi("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 si([oi("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return si([oi("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"),si([oi("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:1,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return ni(n)?ni(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[oi("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[oi("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const go={addition:new yo,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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ei(Qr(t,"left operand")-Qr(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[oi("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new yo).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ei(Qr(t,"left operand")*Qr(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[oi("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new yo).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=1){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(Qr(t,"left operand"),Qr(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[oi("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new yo).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:0,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}(Qr(t,"left operand"),Qr(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[oi("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 yo).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=Qr(t,"left operand"),i=Qr(n,"right operand");return{success:1,value:ei(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:0,errors:[oi("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new yo).validate(t)}}};var vo=Object.freeze({__proto__:null,conversion:Dn,conversionExpressions:Dn,createCommonRegistry:function(){return Pr(Hr,Pi,Vi,Dn,mo)},createCoreRegistry:_i,createExpressionRegistry:Pr,createFullExpressionRegistry:function(){return Pr(Hr,Pi,Dn,mo,Un,Vi,go)},createFullRegistry:function(){return Pr(Hr,Pi,Vi,Dn,mo,Un)},logical:Pi,logicalExpressions:Pi,positional:mo,positionalExpressions:mo,properties:Un,propertiesExpressions:Un,references:Hr,referencesExpressions:Hr,special:Vi,specialExpressions:Vi});return oo}();
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",u="index",l="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"]),$=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"]),C=new Set(["me","it","you","result","my","its","your"]),N=new Set(["and","or","not","no"]),R=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"]),O=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"]),L=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 j;!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"}(j||(j={}));const M=new Set(["+","-","*","/","mod"]),I=new Set(["ms","s","seconds","minutes","hours","days"]);function P(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function q(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 H(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;q(t)}}function B(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:D(t,s),column:a};t.tokens.push(c)}function D(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 F(t){const e=t.position;let n="";for(q(t),q(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=q(t);B(t,j.COMMENT,"--"+n,e)}function V(t){const e=t.position,n=q(t);let r=n;for(;t.input.length>t.position;){const e=q(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=q(t))}B(t,j.STRING,r,e)}function _(t){const e=t.position;q(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){q(t);break}if("\\"===e){if(q(t),t.input.length>t.position){const e=q(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+=q(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);B(t,j.TEMPLATE,n,e)}function U(t){const e=t.position;let n=q(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=q(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=q(t),"}"===e)break}B(t,j.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if("\\"===e)q(t),t.input.length>t.position&&(n+=q(t));else{if(!Y(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=q(t)}}B(t,j.SELECTOR,n,e)}}function W(t){const e=t.position;if(Q(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+=q(t),e===s&&(s="");else if('"'!==e&&"'"!==e){if("<"===e){if("/"===n[t.position+1]){for(;n.length>t.position&&">"!==n[t.position];)r+=q(t);if(n.length>t.position&&(r+=q(t)),i--,0>=i)break;continue}let e=0,s="";for(;n.length>t.position;){const i=n[t.position];if(s)r+=q(t),i===s&&(s="");else if('"'!==i&&"'"!==i){if(">"===i){e="/"===n[t.position-1],r+=q(t);break}r+=q(t)}else s=i,r+=q(t)}if(e||i++,0>=i)break;continue}r+=q(t)}else s=e,r+=q(t)}B(t,j.SELECTOR,r,e)}(t,e);let n="";for(n+=q(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=q(t),"/"===e&&">"===r){n+=q(t);break}}B(t,j.SELECTOR,n,e)}function z(t){const e=t.position;let n=q(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!Y(e)&&"_"!==e&&"-"!==e)break;n+=q(t)}B(t,j.SYMBOL,n,e)}function Z(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===P(t,1))return n="'s",q(t),q(t),void B(t,j.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,q(t),q(t),q(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(i)?(n=i,q(t),q(t)):n=q(t),B(t,j.OPERATOR,n,e)}function J(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+=q(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(i+=q(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=q(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+=q(t),"+"!==n[t.position]&&"-"!==n[t.position]||(i+=q(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;i+=q(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+=q(t)}I.has(o)?B(t,j.TIME,i+o,e):(t.position=s,B(t,j.NUMBER,i,e))}function X(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+=q(t)}const s=function(t,e,n){const r=e.toLowerCase(),i=t.position;if("'s"===e||"'s"===e)return 0;const s=t.tokens[t.tokens.length-1];if(s&&(s.kind===j.IDENTIFIER||s.kind===j.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}H(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+=q(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){H(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+=q(t)}const i=n.toLowerCase();if("start"===i||"end"===i){H(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+=q(t)}if("of"===e.toLowerCase())return B(t,j.IDENTIFIER,`at the ${i} of`,r),1}return t.position=e,0}if("start"===s||"end"===s){H(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+=q(t)}return"of"===n.toLowerCase()?(B(t,j.IDENTIFIER,`at ${s} of`,r),1):(t.position=e,0)}}return 0}(t,r,e,n);if(s)return 1;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&&(H(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+=q(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");R.has(n)&&(i=n,s=t.position)}return R.has(i)&&i!==`${e} ${n}`?(t.position=s,i):(t.position=r,null)}(t,r,e);if(a)return B(t,j.OPERATOR,a,n),1;if(R.has(i))return B(t,j.OPERATOR,i,n),1}return R.has(r)?(t.position=i,B(t,j.OPERATOR,e,n),1):(t.position=i,0)}(t,i,e);if(s)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||N.has(e)||M.has(t)||M.has(e)||R.has(e)?j.OPERATOR:j.IDENTIFIER}(i);B(t,o,i,e)}function K(t){const e=t.position,n=t.input,r=n.length;q(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+=q(t)}B(t,j.IDENTIFIER,i,e)}function G(t){return/[a-zA-Z]/.test(t)}function Y(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){const e=t.input,n=e[t.position+1];if(!n||!/[a-zA-Z]/.test(n))return 0;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 tt(t){if(Q(t))return 1;let e=t.position+1,n=0;for(;t.input.length>e;){const r=t.input[e];if("/"===r&&t.input.length>e+1&&">"===t.input[e+1])return n;if(Y(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=1,e++;else{if(" "!==r&&"\t"!==r)return 0;e++}if(e-t.position>50)return 0}return 0}function et(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const nt=function(){if("undefined"!=typeof localStorage)try{const t=localStorage,e=t.getItem("hyperfixi:debug")||t.getItem("lokascript:debug");if("*"===e||"true"===e)return 1}catch{}return"undefined"!=typeof process&&"true"===process.env?.HYPERFIXI_DEBUG?1:0}(),rt=nt,it=nt,st=nt,ot=nt,at=(...t)=>{rt&&console.log("\ud83d\udd27",...t)},ct=(...t)=>{it&&console.log("\ud83c\udfaf",...t)},ut=(...t)=>{st&&console.log("\ud83d\udcdd",...t)},lt=(...t)=>{ot&&console.log("\ud83d\ude80",...t)};let ft=0,ht=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ft=1,ht=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let dt={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class pt{constructor(t){this.analyzer=t.analyzer,this.language=t.language,this.confidenceThreshold=t.confidenceThreshold??.5,this.debugEnabled=t.debug??0}isAvailable(){return this.analyzer.supportsLanguage(this.language)}shouldSkipSemantic(t){const e=t.trim().split(/\s+/)[0]?.toLowerCase();if(pt.SKIP_SEMANTIC_COMMANDS.has(e))return 1;const n=t.toLowerCase();return/\bjs\b/.test(n)||/\btell\b/.test(n)||/\*[a-zA-Z]/.test(t)?1:0}trySemanticParse(t){const e=performance.now();if(this.shouldSkipSemantic(t))return{success:0,confidence:0,errors:["Command skipped for semantic parsing - using traditional parser"]};if(!this.isAvailable())return{success:0,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(ft){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(!ft)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(),ht){const e=new CustomEvent("lokascript:semantic:parse",{detail:t,bubbles:1});ht.dispatchEvent(e)}}(a),n=a,dt.totalParses++,n.semanticSuccess?dt.semanticSuccesses++:n.fallbackTriggered?dt.semanticFallbacks++:dt.traditionalParses++,dt.confidenceHistory.push(n.confidence),dt.confidenceHistory.length>100&&dt.confidenceHistory.shift(),dt.averageConfidence=dt.confidenceHistory.reduce((t,e)=>t+e,0)/dt.confidenceHistory.length}return s?{success:1,node:this.buildCommandNode(r),confidence:r.confidence,tokensConsumed:r.tokensConsumed}:{success:0,confidence:r.confidence,tokensConsumed:r.tokensConsumed,errors:r.errors}}catch(t){return{success:0,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:0,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:0,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:0,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:0,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:0,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}}pt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const mt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),yt=new Set([")","]","}",","]);function gt(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 vt(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 bt(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:1,start:e.start,end:r.end??e.end,line:e.line,column:e.column}})}}}function wt(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=1;const o=r.peek();return o&&"!"===o.value&&(r.advance(),s=0),{type:"typeCheckExpression",value:e,typeName:i.value,nullOk:s,negated:t,start:e.start,end:i.end}}}const Et=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",gt(10)],["||",gt(10)],["and",gt(20)],["&&",gt(20)],["==",gt(30)],["!=",gt(30)],["<",gt(30)],[">",gt(30)],["<=",gt(30)],[">=",gt(30)],["is",gt(30)],["matches",gt(30)],["contains",gt(30)],["starts with",gt(30)],["ends with",gt(30)],["does not start with",gt(30)],["does not end with",gt(30)],["is between",gt(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}})],["is not between",gt(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 between",gt(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 not between",gt(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}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=1,t)}}],["where",gt(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",gt(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",gt(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",gt(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",gt(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}})],["+",{...gt(40),...bt(80)}],["-",{...gt(40),...bt(80)}],["*",gt(50)],["/",gt(50)],["%",gt(50)],["mod",gt(50)],["^",vt(60)],["**",vt(60)],["as",gt(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",bt(80)],["!",bt(80)],["no",bt(27)]]),new Map([["===",gt(30)],["!==",gt(30)],["is not",gt(30)],["am",gt(30)],["is in",gt(30)],["is not in",gt(30)],["precedes",gt(30)],["does not precede",gt(30)],["follows",gt(30)],["does not follow",gt(30)],["is a",gt(30,wt(0))],["is an",gt(30,wt(0))],["is not a",gt(30,wt(1))],["is not an",gt(30,wt(1))],["has",gt(30)],["have",gt(30)],["match",gt(30)],["include",gt(30)],["includes",gt(30)],["equals",gt(30)],["does not contain",gt(30)],["does not include",gt(30)],["am in",gt(30)],["am not in",gt(30)],["is really",gt(30)],["is not really",gt(30)],["is equal",gt(30)],["is not equal",gt(30)],["contain",gt(30)],["do not contain",gt(30)],["does not contains",gt(30)],["do not match",gt(30)],["does not match",gt(30)],["is equal to",gt(30)],["is not equal to",gt(30)],["is really equal to",gt(30)],["is not really equal to",gt(30)],["really equals",gt(30)],["is greater than",gt(30)],["is less than",gt(30)],["is greater than or equal to",gt(30)],["is less than or equal to",gt(30)],["in",gt(30)],["of",vt(30)],["really",gt(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:0,start:t.start})}}],["does not exist",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["is not empty",{infix:{bp:[30,31],handler:(t,e)=>({type:"unaryExpression",operator:e.value,operand:t,prefix:0,start:t.start})}}],["some",bt(80)]]),new Map([["=",vt(5)]])),xt=new Map,kt=new Map,St=new Map,At=new Set,Tt=new Set,$t=new Set,Ct=new Set;function Nt(t){return xt.get(t.toLowerCase())}function Rt(t,e){if(0!==Tt.size)for(const n of Tt)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function Ot(t,e,n){if(0!==$t.size)for(const r of $t)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function Lt(t,e){if(0!==Ct.size)for(const n of Ct)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] localReadHook threw:",t)}}function jt(t,e,n){if(t.globals.set(e,n),0!==At.size)for(const r of At)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function Mt(t){return t.kind!==j.IDENTIFIER?0:E.has(t.value.toLowerCase())}function It(t){return t.kind!==j.IDENTIFIER?0:L.has(t.value.toLowerCase())}function Pt(t){return t.kind!==j.IDENTIFIER?0:O.has(t.value.toLowerCase())}function qt(t){return t.kind!==j.IDENTIFIER?0:C.has(t.value.toLowerCase())}function Ht(t){return R.has(t.value.toLowerCase())}function Bt(t){return t.kind===j.IDENTIFIER}function Dt(t){return t.kind===j.SELECTOR}function Ft(t){return t.kind!==j.SELECTOR?0:!t.value.startsWith("<")}function Vt(t){return t.kind===j.STRING||t.kind===j.NUMBER||t.kind===j.TEMPLATE}function _t(t){return t.kind===j.IDENTIFIER}function Ut(t){return t.kind===j.TIME}function Wt(t){return t.kind===j.SYMBOL}function zt(t){return t.kind===j.COMMENT}function Zt(t){if(t.kind!==j.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(E.has(e)||L.has(e)||O.has(e)||C.has(e))}function Jt(t){return t.kind===j.STRING}function Xt(t){return t.kind===j.NUMBER}function Kt(t){if(t.kind===j.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Gt(t){return t.kind===j.TEMPLATE}function Yt(t){return t.kind===j.SELECTOR&&t.value.startsWith("<")}function Qt(t){return t.kind===j.SELECTOR&&t.value.startsWith("#")}function te(t){return t.kind===j.SELECTOR&&t.value.startsWith(".")}function ee(t){return t.kind!==j.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function ne(t){if(t.kind!==j.OPERATOR)return 0;const e=t.value.toLowerCase();return!N.has(e)&&!R.has(e)}function re(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function ie(t,e,n){return{type:"literal",value:t,raw:e,start:n.start,end:n.end,line:n.line,column:n.column}}function se(t,e){return{type:"identifier",name:t,start:e.start,end:e.end,line:e.line,column:e.column}}function oe(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 ae(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ce(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ue(t,e){return{type:"objectLiteral",properties:t,start:e.start,end:e.end,line:e.line,column:e.column}}function le(t,e){return{type:"arrayLiteral",elements:t,start:e.start,end:e.end,line:e.line,column:e.column}}function fe(t,e,n){return{type:"propertyOfExpression",property:t,target:e,start:n.start,end:n.end,line:n.line,column:n.column}}function he(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 de=[{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 pe(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const me=[t,r,e,n];function ye(t,e=[]){if(t.isAtEnd())return 1;for(const e of me)if(t.check(e))return 1;for(const n of e)if(t.check(n))return 1;return t.checkIsCommand()?1:0}function ge(t,e=[]){if(!ye(t,e))return t.parseExpression()}function ve(t,e,n){return t.check(e)?(t.advance(),n.push(t.createIdentifier(e)),1):0}function be(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function we(t,e){return t.check(e)?(t.advance(),1):0}function Ee(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 xe{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new xe(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 xe(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 xe(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=1){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 xe(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 ke(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}=Ee(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(;!ye(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 xe.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function Se(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 xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ae(i,s){const o=[],a=()=>i.check(n)||s&&i.check(e);for(;!i.isAtEnd()&&!a();){if(zt(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 Te=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function $e(t,e,n){return null===e||Te.has(e.value?.toLowerCase?.()??"")?0:t.checkIsCommand()||t.isCommand(n.value?.toLowerCase())}function Ce(r,i){const s=[];let o=0;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=1;break}if(e.value===n||e.value===g||"def"===e.value||e.value===m)break;if(void 0!==e.line&&e.line!==i.line&&$e(r,c,e))break;zt(e)||(c=e),r.advance()}r.restorePosition(a);let u=0;if(!o){const t=r.savePosition(),s=i.line,o=100;let a=0,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&&(u=1);break}if($e(r,c,t)){if(void 0!==t.line&&t.line!==s){u=1;break}a=1}zt(t)||(c=t),r.advance()}r.restorePosition(t)}const l=o||u;let f;if(l)f=r.parseExpression();else{const e=[],n=20;let s=0,o=1;for(;!r.isAtEnd()&&!r.check(t)&&(o||!r.checkIsCommand()&&!r.isCommand(r.peek().value))&&n>s;){o=0;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),l){we(r,t);const o=Ae(r,1);if(0===o.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");s.push(ae(o,{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}));let a=0;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Ce(r,t);s.push(ae([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=Ae(r,0);s.push(ae(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(ae([t],{start:i.start,end:r.getPosition().end,line:i.line,column:i.column}))}}return xe.from(i).withArgs(...s).endingAt(r.getPosition()).build()}function Ne(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=xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&i.withModifiers(r),i.build()}const Re=new Set(["my","its","your"]);function Oe(t){const e={};if(we(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||!Bt(n))return e;t.advance();let r=n.value;if(t.check(":")){t.advance();const e=t.peek();e&&Bt(e)&&(t.advance(),r=`${r}:${e.value}`)}if(e.until={type:"literal",value:r,raw:r},we(t,h)){const n=ge(t);n&&(e.from=n)}return e}function Le(t,e){const n=[],r=ge(t,[h]);r&&n.push(r),ve(t,h,n);const i=ge(t);return i&&n.push(i),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function je(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const s=ge(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),ve(t,r,n);const e=ge(t,[h,m,i]);e&&n.push(e)}if(be(t,[h,m],n)){const e=ge(t);e&&n.push(e)}return xe.fromIdentifier(e).withArgs(...n).withModifiers(Oe(t)).endingAt(t.getPosition()).build()}const s=ge(t,[h,m]);if(s&&n.push(s),be(t,[h,m],n)){const e=ge(t);e&&n.push(e)}return t.check("modal")&&(t.advance(),n.push({type:"literal",value:"modal",raw:"modal"})),xe.fromIdentifier(e).withArgs(...n).withModifiers(Oe(t)).endingAt(t.getPosition()).build()}function Me(t,e){if(!t.check("using"))return 0;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")),1}function Ie(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)?(we(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?xe.fromIdentifier(e).withArgs(r,t.createIdentifier(s),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Pe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function qe(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 fe(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:fe(se(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 u=i.parseExpression()??i.parsePrimary();let l;var h;i.check(m)&&(h=i.peekAt(1))&&("selector"===h.kind||h.value.startsWith("<")||He.has(h.value))&&(i.advance(),l=ge(i));const d=[];a?d.push(a):c.length>0&&d.push(...c),d.push(i.createIdentifier(f)),u&&d.push(u);const y=xe.fromIdentifier(s).withArgs(...d);return l&&y.withModifier("on",l),y.endingAt(i.getPosition()).build()}const He=new Set(["me","my","it","its","you","your","yourself"]),Be=new Set(["to","the","url","of","in","new","window","top","middle","bottom","left","center","right","smoothly","instantly","back","forward"]);function De(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function Fe(t,e){const n=[];for(;!ye(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ve(t){const e=t.peek();if("/"===e.value)return 1;if(t.checkIdentifierLike()){const n=t.peekAt(1);return!!n&&":"===n.value&&n.start===e.end}return 0}const _e=new Set(["{",")"]);function Ue(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(_e.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 We(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function ze(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 Ze=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]);class Je{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 pt({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=1),t}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:0,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:0,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:1===t.length?t[0]:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}const t=this.peek(),e=t&&Nt(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!==Nt(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?Nt(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:0,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,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")){ut("\u2705 PARSER: Found event handlers after command sequence, parsing as program");const e=[t];ut(`\u2705 PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){ut(`\u2705 PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(ut("\u2705 PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,ut(`\u2705 PARSER: Added event handler, now have ${e.length} statements total`)),ut(`\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 ut("\u26a0\ufe0f PARSER: Unexpected token after event handlers: "+this.peek().value),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error};ut("\u2705 PARSER: No more event handlers, at end of input");break}}return ut(`\u2705 PARSER: Finished parsing, creating Program node with ${e.length} statements`),this.error?{success:0,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:0,node:t,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:1,node:t,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:0,node:t||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const n=this.parseExpression();if(this.error)return{success:0,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:0,node:n||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:1,node:n,tokens:this.tokens,warnings:this.warnings}}catch(t){return this.addError(t instanceof Error?t.message:"Unknown parsing error"),{success:0,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=Je.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=Je.PRATT_TABLE.get(e.value);if(!n?.infix){if(mt.has(e.value)||yt.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){ut("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()&&!Je.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(Ze.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 0;const e=t.value;return mt.has(e)||yt.has(e)?0:"number"===t.kind||"string"===t.kind||"identifier"===t.kind||"symbol"===t.kind?1:["(","[","{","-","+","!","#",".","<","$","@"].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?mt.has(e.value)||yt.has(e.value):1},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):(t=>E.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>T.has(t.toLowerCase()))(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:0,...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 x.has(t.toLowerCase())}parseCompoundCommand(s){return function(s,o){switch(o.name.toLowerCase()){case"put":return Ie(s,o);case"trigger":case"send":return ke(s,o);case"remove":return Le(s,o);case"take":return function(t,e){const n=[],r={},s=ge(t,[h,i]);if(s&&n.push(s),t.check(h)){ve(t,h,n);const e=ge(t,[i]);e&&n.push(e)}if(we(t,i)){const e=ge(t);e&&(r.for=e)}return xe.fromIdentifier(e).withArgs(...n).withModifiers(r).endingAt(t.getPosition()).build()}(s,o);case"toggle":return je(s,o);case"set":return qe(s,o);case"halt":return Se(s,o);case"measure":return Ne(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 xe.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,o);case"go":return function(t,e){const n=[];for(;!ye(t,["when","where","catch","finally"]);){const e=t.peek(),r=t.resolveKeyword(e.value).toLowerCase();if(Be.has(r)){t.advance(),n.push(De(r,e));continue}if(Ve(t)){const r=Ue(t);if(r){n.push(r);continue}t.advance(),n.push(De(e.value,e));continue}if("+"===e.value||"-"===e.value){t.advance(),n.push(De(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(De(e.value+"px",{...e,end:r.end}))}continue}const i=t.current;if(n.push(t.parsePrimary()),t.current===i)break}return xe.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 xe.fromIdentifier(s).withArgs(o,...a).endingAt(i.getPosition()).build()}(s,o);case"pick":return function(t,e){const n=xe.fromIdentifier(e);we(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=0;(t.match("to")||t.match(".."))&&(t.match("end")?o=1:r=t.parsePrimary());let a="default";t.match("inclusive")?a="inclusive":t.match("exclusive")&&(a="exclusive");const c=s(),u=n.withArgs(c).withModifier("variant",i("range")).withModifier("rangeStart",e).withModifier("rangeMode",i(a));return o?u.withModifier("rangeEnd",i("end")):r&&u.withModifier("rangeEnd",r),u.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 Fe(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 xe.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();Pe.includes(i)&&(r=i,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),xe.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 Me(t,n),xe.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(ve(t,"partials",n),ve(t,l,n)){const e=ge(t,["using"]);e&&n.push(e)}return Me(t,n),xe.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,o)??Fe(s,o);default:return Fe(s,o)}}(this.getContext(),s)}parsePutCommand(t){return Ie(this.getContext(),t)}parseSetCommand(t){return qe(this.getContext(),t)}parseHaltCommand(t){return Se(this.getContext(),t)}parseMeasureCommand(t){return Ne(this.getContext(),t)}parseTriggerCommand(t){return ke(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(ut("\ud83d\udd04 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){ut("\ud83d\udccd Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;const r=this.checkIsCommand(),i=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||i){ut(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&&(ut("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(ut("\u2705 Parsed command:",r.name),e.push(r),t=1)}catch(t){ut("\u26a0\ufe0f parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&ut("\u274c IDENTIFIER is not a command:",this.peek().value);if(!t){ut("\u274c No command parsed, breaking. Current token:",this.peek().value);break}for(ut("\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(","));)ut("\u26a0\ufe0f Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ut("\u2705 Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ut("\ud83d\udccd No separator and no command, breaking. Current token:",this.peek().value);break}ut("\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=""),ut("\u2705 parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(t="repeat"){const{commands:e}=this.parseCommandListUntilTerminator([]);if(ut('\ud83d\udd0d After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ut('\u274c ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error(`Expected "end" to close ${t} block`);return ut('\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();Bt(e)&&(v=e.value,t.advance()),t.check(l)&&(t.advance(),g=t.parseExpression())}else if(t.check(l))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(ut("\ud83d\udccd Parsing event name, current token:",{value:e.value,kind:e.kind}),!Bt(e)&&!Pt(e))throw Error('Expected event name after "event"');if(f=e.value,t.advance(),ut("\u2705 Got event name:",f,"Next token:",t.peek().value),ut('\ud83d\udd0d Checking for "from", current token:',t.peek().value),t.check(h)){ut('\u2705 Found "from", advancing...'),t.advance(),ut('\ud83d\udccd After consuming "from", current token:',t.peek().value),we(t,b)&&ut('\u2705 Found "the", advancing...');const e=t.peek();ut("\ud83d\udd0d Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),ut("\u2705 After parsePrimary, eventTarget:",p)}else ut('\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()===u&&(t.advance(),t.advance(),x=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(x=e.value,t.advance()):x=u}let k=null,S=0;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=1,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(ce(v,A)),g&&n.push(g),m&&n.push(m),w&&n.push(w),f&&n.push(ce(f,A)),p&&n.push(p),x&&n.push(ce(x,A)),n.push(ae(E,{...A,end:A.end||0})),null!==k&&n.push(ae(k,{...A,end:A.end||0}));const T=xe.from(e).withArgs(...n);return S&&T.withModifier("bottomTested",{type:"literal",value:1,...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(!Bt(s))throw Error('Expected variable name after "for"');if(r=s.value,t.advance(),!t.check(l))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()===u&&(t.advance(),t.advance(),o=u)}else if(t.check(u)){t.advance();const e=t.peek();Bt(e)?(o=e.value,t.advance()):o=u}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(ce(r,c)),n.push(i),o&&n.push(ce(o,c)),n.push(ae(a,{...c,end:c.end||0})),xe.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")&&!ye(t)){const r=t.parseExpression();return n.push(r),xe.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(!Bt(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(!Bt(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(),we(t,b),i=t.parsePrimary());const s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(le(r.map(t=>ue("duration"===t.kind?[{key:se("duration",s),value:t.expr}]:[{key:se("name",s),value:ie(t.name,`"${t.name}"`,s)},{key:se("args",s),value:le(t.params.map(t=>ie(t,`"${t}"`,s)),s)}],s)),s)),i&&n.push(i)}return xe.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(se(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(Ee(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(ue(r.map(t=>({key:t.name?se(t.name,i):ie("_positional","_positional",i),value:t.value})),i))}}return xe.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("<")||Bt(o)&&Re.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&&(Bt(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 xe.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=ge(t,[f]);e&&n.push(e)}if(t.check(f)){t.advance();const e=ge(t);e&&n.push(e)}return xe.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Ce(this.getContext(),t)}parseRemoveCommand(t){return Le(this.getContext(),t)}parseToggleCommand(t){return je(this.getContext(),t)}parseRegularCommand(t){return Fe(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),0)}else if(this.match("?.")){const e=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),n=this.createMemberExpression(t,this.createIdentifier(e.value),0);n.optional=1,t=n}else if(this.match("[")){const e=this.parseExpression();this.consume("]","Expected ']' after array index"),t=this.createMemberExpression(t,e,1)}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):Wt(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()&&Bt(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=1;break;case"false":e=0;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=1,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(Zt)||this.matchPredicate(It)||this.matchPredicate(qt)||this.matchPredicate(Mt)||this.matchPredicate(Pt))){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(Wt(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),0)}}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(Zt))return this.addError("Expected property name in object literal"),this.createErrorNode();{let t="",n=0;for(;this.check("-");)this.advance(),t+="-",n=1;for(this.checkPredicate(Zt)&&(t+=this.advance().value);this.check("-");)this.advance(),t+="-",n=1,this.checkPredicate(Zt)&&(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(Zt))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=0,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=1),"{"===t.value&&s++,"}"===t.value&&s--}const c=this.originalInput&&o>=0&&a>o?this.originalInput.slice(o,a):r.join(""),u=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:u}),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:1,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:0,...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:0,...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(!(Je.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Zt(r)&&!this.isCommand(r.value)||qt(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};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}}),Je.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:0,targetFailed:1}}return{node:this.createPseudoCommandNode(n,t,i,s,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(ut("\u26a0\ufe0f Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return ut("\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,ut(`\ud83d\udd27 parseEventHandler: Parsed '${e} at ${i.value}' (${s}ms)`)}else if(this.matchNumber()){const r=parseInt(this.previous().value,10);t[n]=r,ut(`\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(){ut("\ud83d\udd27 parseEventHandler: ENTRY - parsing event handler");const t=[];let e=0;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=1,ut("\ud83d\udd27 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),ut("\ud83d\udd27 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),ut("\ud83d\udd27 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),ut("\ud83d\udd27 parseEventHandler: Parsed additional event name: "+e)}let r;if(ut("\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,ut(`\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"),ut("\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=1,ut("\ud83d\udd27 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)s.prevent=1,ut("\ud83d\udd27 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)s.stop=1,ut("\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,ut(`\ud83d\udd27 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(s.throttle=n,ut(`\ud83d\udd27 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else ut(`\ud83d\udd27 parseEventHandler: Warning - unknown modifier '.${t}'`)}let o,a,c,u;if(this.parseTemporalKeywordModifiers(s),e&&(s.once=1),Object.keys(s).length>0&&ut("\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,ut(`\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,ut("\ud83d\udd27 parseEventHandler: Parsed attribute name: "+c)}this.match("in")&&(ut("\ud83d\udd27 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),ut("\ud83d\udd27 parseEventHandler: Parsed watch target expression"));const l=[];for(ut(`\u2705 parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ut(`\u2705 parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ut("\u2705 parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ut("\u2705 parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ut("\u2705 parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.check("catch")||this.check("finally")){ut(`\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();l.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(l.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(l.push(t),ut("\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&&l.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){ut("\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(l.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:0,...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}};l.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:l,...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},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(s).length>0&&{modifiers:s},start:p.start,end:p.end,line:p.line,column:p.column};return ut(`\ud83d\udd27 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${c||"none"}, watchTarget: ${u?"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();Zt(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,u,l;if("catch"!==a&&"finally"!==a||({errorSymbol:c,errorHandler:u,finallyHandler:l}=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!==u&&{errorHandler:u},...void 0!==l&&{finallyHandler:l},...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")||(ut("\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"));)ut("\u26a0\ufe0f parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ut('\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=he(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 de.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return pe(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const i=[],s={};for(;!ye(t,["catch","finally",...r.keywords])&&!pe(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(i.push(e),!t.match(",")&&pe(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&pe(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(s[e]=n),!pe(t.peek(),r.keywords))break}const o=xe.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?(ut(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(ut(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return ut("[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(Mt(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()&&Ve(t)&&(r=Ue(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),xe.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:1,start:e.start,end:r.end,line:e.line,column:e.column};continue}}break}t.advance(),n.with=We(t)?ze(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||we(t,"a")||we(t,"an"),n.as=t.parsePrimary();const i=xe.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:1,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=0;t.check(v)&&(i=1,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=ie(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},u=oe(r,s,o,c);u.coerceNumeric=1;const l=[a,se(f,c),u];return xe.from(e).withName("set").withArgs(...l).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:0,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=0,i=0;return this.match("from")&&(t=this.parseRelativePositionalOperand()),this.match("in")?(r=1,n=this.parseRelativePositionalOperand()):this.match("within")&&(e=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),i=1),{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(""),0);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),0)}{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},1)}if(Wt(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}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),0)}}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;$.has(e.toLowerCase())&&ut(`\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 ie(t,e,this.getPosition())}createIdentifier(t){return se(t,this.getPosition())}createBinaryExpression(t,e,n){return oe(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(ut(`\u2705 createProgramNode: Called with ${t.length} statements`),0===t.length)return ut("\u2705 createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return ut(`\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 ut(`\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(),1;return 0}matchOperator(t){if(this.isAtEnd())return 0;const e=this.peek();return ne(e)&&e.value===t?(this.advance(),1):0}check(t){if(this.isAtEnd())return 0;const e=this.peek().value;return this.resolveKeyword(e)===t}checkPredicate(t){return this.isAtEnd()?0:t(this.peek())}matchPredicate(t){return this.checkPredicate(t)?(this.advance(),1):0}checkSelector(){return this.checkPredicate(Ft)}matchSelector(){return this.matchPredicate(Ft)}checkAnySelector(){return this.checkPredicate(Dt)}checkLiteral(){return this.checkPredicate(Vt)}checkIdentifierLike(){return this.checkPredicate(Bt)}checkIsCommand(){return this.checkPredicate(Mt)}checkCommandTerminator(){return this.checkPredicate(re)}checkReference(){return this.checkPredicate(_t)}checkTimeExpression(){return this.checkPredicate(Ut)}checkEvent(){return this.checkPredicate(Pt)}checkContextVar(){return this.checkPredicate(qt)}checkComment(){return this.checkPredicate(zt)}checkIdentifier(){return this.checkPredicate(Zt)}checkKeyword(){return this.checkPredicate(It)}checkString(){return this.checkPredicate(Jt)}matchString(){return this.matchPredicate(Jt)}checkNumber(){return this.checkPredicate(Xt)}matchNumber(){return this.matchPredicate(Xt)}checkBoolean(){return this.checkPredicate(Kt)}matchBoolean(){return this.matchPredicate(Kt)}checkTemplateLiteral(){return this.checkPredicate(Gt)}matchTemplateLiteral(){return this.matchPredicate(Gt)}checkQueryReference(){return this.checkPredicate(Yt)}matchQueryReference(){return this.matchPredicate(Yt)}checkIdSelector(){return this.checkPredicate(Qt)}checkClassSelector(){return this.checkPredicate(te)}checkCssSelector(){return this.checkPredicate(ee)}checkBasicOperator(){return this.checkPredicate(ne)}matchBasicOperator(){return this.matchPredicate(ne)}matchTimeExpression(){return this.matchPredicate(Ut)}matchIdentifierLike(){return this.matchPredicate(Bt)}matchComparisonOperator(){return this.matchPredicate(Ht)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Zt,t)}consumeIdentifierLike(t){return this.consumePredicate(Bt,t)}consumeEvent(t){return this.consumePredicate(Pt,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;ut("\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:1,configurable:1}),e}}function Xe(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&&(H(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==P(e,1))if('"'!==n){if("'"===n||"'"===n){const t=P(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||/\s/.test(e.input[e.position-1]??" ")||n.kind!==j.IDENTIFIER&&n.kind!==j.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)V(e);else{const t=e.position;q(e),q(e),B(e,j.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===P(e,1)){const t=e.position;q(e),q(e),B(e,j.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===j.IDENTIFIER&&E.has(t.value.toLowerCase()),i=t&&t.kind===j.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===j.OPERATOR&&")"!==t.value&&"]"!==t.value||r||i||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(G(P(e))||"{"===P(e)||"-"===P(e))){U(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===j.IDENTIFIER&&O.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==j.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(q(e),B(e,j.SYMBOL,"[")):(q(e),B(e,j.OPERATOR,"["));continue}if("]"!==n){if("$"===n){const t=P(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){K(e);continue}}et(n)?Z(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(B(e,j.UNKNOWN,n),q(e)):X(e):J(e)}else q(e),B(e,j.OPERATOR,"]")}else q(e),B(e,j.OPERATOR,"}");else q(e),B(e,j.OPERATOR,"{");else z(e)}else U(e);else tt(e)?W(e):Z(e);else _(e)}else V(e);else F(e)}return e.tokens}(t);return new Je(n,e,t).parse()}Je.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Je.PRATT_TABLE=Et,Je.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Ke{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 0;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 1;return 0}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}function Ge(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Ye(t){return{ok:1,value:t}}function Qe(t){return{ok:0,error:t}}function tn(t){return 1==t.ok}const en=new Map,nn=new WeakMap;function rn(t){let e=nn.get(t);return e||(e=new Map,nn.set(t,e)),e}function sn(t){return t.owner||(t.me instanceof Element?t.me:null)}function on(t,e){const n=sn(t);if(n)return Lt(e,t),rn(n).get(e)}function an(t,e,n){const r=sn(t);r&&(rn(r).set(e,n),Ot(e,n,t))}function cn(t,e){return{me:t??null,owner:t??null,it:null,you:null,result:null,locals:new Map,globals:e||en,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}function un(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function ln(t){return null!==t&&"object"==typeof t&&"length"in t&&"number"==typeof t.length&&(Symbol.iterator in t||"function"==typeof t.item)}function fn(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 hn(t,e,n,r){if("element"!==r){if("global"===r)return jt(n,t,e),void("undefined"!=typeof window&&(window[t]=e));if(t.startsWith("$"))return void jt(n,t.slice(1),e);if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void Ot(t,e,n);if(n.globals&&n.globals.has(t))return jt(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 jt(n,t,e);n.locals.set(t,e),Ot(t,e,n)}}else an(n,t,e)}function dn(t,e,n){return n||"string"!=typeof e||!e.startsWith("#")?t:Array.isArray(t)?t[0]??null:t}function pn(t){if(un(t))return[t];if(Array.isArray(t)){const e=t.filter(un);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(un);return e.length>0?e:null}return null}const mn=new class{constructor(t={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:0,cacheCoercions:1,...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 0;if(n.isType(t))return 1;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:1,direct:1}:{possible:0,direct:0}}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:0,description:"True or false value",examples:[1,0],coerceFrom:{String:t=>{const e=t.toLowerCase().trim();return"true"===e||"yes"===e||"1"===e?1:"false"===e||"no"===e||"0"===e||""===e?0:e.length>0},Number:t=>0!==t,Null:()=>0,Undefined:()=>0,Array:t=>Array.isArray(t)?t.length>0: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=>1,defaultValue:null,description:"Unknown/any value type"})}};function yn(t){const e=mn.get("String");return e?e.isType(t):"string"==typeof t}function gn(t){const e=mn.get("Number");return e?e.isType(t):"number"==typeof t}function vn(t){const e=mn.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function bn(t){const e=mn.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function wn(t){const e=mn.get("Function");return e?e.isType(t):"function"==typeof t}function En(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}function xn(t){return t instanceof Element}function kn(t){return t instanceof HTMLElement}const Sn=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function An(t,e){return Sn.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Tn={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 0;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=>En(t)?t.tabIndex:void 0,hidden:t=>En(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 $n(t,e){if(e.startsWith("*"))return function(t,e){if(!kn(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 kn(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return An(t,e.slice(1));const n=Tn[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return An(t,e);const r=t[e];return wn(r)?r.bind(t):r}const Cn={1:"one",2:"two",3:"three",4:"four",5:"five"};function Nn(t,e,n,r){return t.length!==e?`${n} requires exactly ${i=e,Cn[i]??i+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var i}function Rn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function On(t,e,n){return Nn(t,1,e,n)??Rn(t,0,e,n)}function Ln(t,e){return Nn(t,2,e,"left, right")}function jn(){return null}function Mn(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 In(t,e,n,r,i){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${i?` (${i})`:""}`:null}const Pn={conversions:{dynamicResolvers:[]}},qn={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":yn(t)?t:bn(t)?JSON.stringify(t):t+"",Boolean:t=>{if(vn(t))return t;if(null==t)return 0;if(yn(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return gn(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(gn(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(gn(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(!gn(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=qn.Number(t);return Math.trunc(e)},Float:t=>{const e=qn.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(yn(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(!yn(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(bn(t))return t;if(yn(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=>yn(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:qn.String(t)).join(""):t instanceof Element?t.outerHTML:qn.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=Hn(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]=Hn(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?qn.Values(t,e):t;if(!bn(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=qn.Values(t,e);return qn.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=qn.Values(t,e);return JSON.stringify(n)}};function Hn(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 Bn={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 Dn(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 qn.Number(t).toFixed(n??0)}if(null==t)return t;let r=qn[e];if(r)return r(t,n);const i=Bn[e.toLowerCase()];if(i&&(r=qn[i],r))return r(t,n);const s=Pn.conversions[e];if("function"==typeof s)return s(t,n);for(const n of Pn.conversions.dynamicResolvers){const r=n(e,t);if(void 0!==r)return r}return console.warn("Unknown conversion type: "+e),t}const Fn={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;return Dn(n,r,t)},validate:t=>Nn(t,2,"as","value, type")??Rn(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(!yn(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 yn(n);case"number":return gn(n)&&!isNaN(n);case"boolean":return vn(n);case"object":return bn(n);case"array":return Array.isArray(n);case"function":return wn(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||bn(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>Nn(t,2,"is","value, type")??Rn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>Nn(t,1,"async","expression")}},Vn=new Set(["__proto__","constructor","prototype"]);function _n(t,e){if(t instanceof Element)return $n(t,e);if(bn(t)){if(Vn.has(e))return;return t[e]}return t[e]}function Un(t){let e;if(Array.isArray(t))e=t;else{if(!("undefined"!=typeof NodeList&&t instanceof NodeList||"undefined"!=typeof HTMLCollection&&t instanceof HTMLCollection))return 0;e=Array.from(t)}return 0===e.length?0:e.every(t=>t instanceof Element||null!=t&&"object"==typeof t&&t.constructor!==Object&&!Array.isArray(t))}const Wn={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 Un(n)&&!(r in n)?Array.from(n,t=>_n(t,r)):_n(n,r)}},validate:t=>Nn(t,2,"possessive","element, property")??Rn(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 $n(t.me,n);if(bn(t.me)){if(Vn.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>On(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 $n(r,n);if(bn(r)){if(Vn.has(n))return;return r[n]}return r[n]},validate:t=>On(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 $n(t.you,n);if(bn(t.you)){if(Vn.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>On(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 $n(r,n);if(bn(r)){if(Vn.has(n))return;return r[n]}return r[n]}},validate:t=>Nn(t,2,"of","property, object")??Rn(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=>In(t,1,2,"attribute","attributeName, optional element")??Rn(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:0},validate:t=>In(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Rn(t,0,"attributeWithValue","attribute name")??Rn(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=>On(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=>On(t,"idReference","idValue")}};function zn(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 Zn(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 Jn(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 Xn(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 nr(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return nr(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,i=t.left;if("="===n){const n=await Xn(t.right,e);if("identifier"===i?.type&&"string"==typeof i.name){const t=i.name;return t.startsWith("$")?jt(e,t.slice(1),n):"global"===i.scope?jt(e,t,n):"element"===i.scope?an(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 Xn(t.left,e);return n instanceof Element&&"selector"===r.type&&"string"==typeof r.value&&r.value.startsWith(".")?n.classList.contains(r.value.slice(1)):0}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 Xn(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 Xn(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 Xn(t.right,e);return Zn(e,"styleRef").evaluate(e,i.value.slice(1),n)}if("of"===n){const n=rr(t.left);if(n){const r=await Xn(t.right,e);let i=r;for(const t of n){if(null==i)return;i=xn(i)?$n(i,t):i[t]}return"function"==typeof i?i.bind(r):i}}const s=await Xn(t.left,e);if("and"===n){if(!s)return s;const n=await Xn(t.right,e);return Zn(e,"and").evaluate(e,s,n)}if("or"===n){if(s)return s;const n=await Xn(t.right,e);return Zn(e,"or").evaluate(e,s,n)}const o=await Xn(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(s):s,u=t.ignoringCase?a(o):o;switch(n){case"+":{let n=s,r=o;return t.coerceNumeric&&("string"==typeof n&&(n=fn(n)),"string"==typeof r&&(r=fn(r))),"string"==typeof n||"string"==typeof r?(n??"")+""+(r??""):Array.isArray(n)?Array.isArray(r)?[...n,...r]:[...n,r]:Jn(await Zn(e,"addition").evaluate(e,{left:n,right:r}))}case"-":return Jn(await Zn(e,"subtraction").evaluate(e,{left:s,right:o}));case"*":return Jn(await Zn(e,"multiplication").evaluate(e,{left:s,right:o}));case"/":return Jn(await Zn(e,"division").evaluate(e,{left:s,right:o}));case"%":case"mod":return Jn(await Zn(e,"modulo").evaluate(e,{left:s,right:o}));case"^":case"**":return Jn(await Zn(e,"power").evaluate(e,{left:s,right:o}));case">":case"is greater than":return Zn(e,"greaterThan").evaluate(e,s,o);case"<":case"is less than":return Zn(e,"lessThan").evaluate(e,s,o);case">=":case"is greater than or equal to":return Zn(e,"greaterThanOrEqual").evaluate(e,s,o);case"<=":case"is less than or equal to":return Zn(e,"lessThanOrEqual").evaluate(e,s,o);case"==":return Zn(e,"equals").evaluate(e,c,u);case"is":case"am":case"equals":case"is equal":case"is equal to":{const n=or(t,s,o);return void 0!==n?n:Zn(e,"equals").evaluate(e,c,u)}case"!=":return Zn(e,"notEquals").evaluate(e,c,u);case"is not":case"is not equal":case"is not equal to":{const n=or(t,s,o);return void 0!==n?!n:Zn(e,"notEquals").evaluate(e,c,u)}case"===":case"really equals":case"is really":case"is really equal to":return Zn(e,"strictEquals").evaluate(e,c,u);case"!==":case"is not really":case"is not really equal to":return Zn(e,"strictNotEquals").evaluate(e,c,u);case"as":return Zn(e,"as").evaluate(e,s,cr(o));case"contains":case"contain":case"includes":case"include":return Zn(e,"contains").evaluate(e,c,u);case"does not contain":case"do not contain":case"does not contains":case"does not include":return Zn(e,"doesNotContain").evaluate(e,c,u);case"starts with":return Zn(e,"startsWith").evaluate(e,c,u);case"ends with":return Zn(e,"endsWith").evaluate(e,c,u);case"does not start with":return!await Zn(e,"startsWith").evaluate(e,c,u);case"does not end with":return!await Zn(e,"endsWith").evaluate(e,c,u);case"match":case"matches":return Zn(e,"matches").evaluate(e,c,sr(t.right,u));case"does not match":case"do not match":return!await Zn(e,"matches").evaluate(e,c,sr(t.right,u));case"in":case"is in":case"am in":return ir(s,o);case"is not in":case"am not in":return!ir(s,o);case"of":return o&&"object"==typeof o?o[s]:void 0;case"precedes":return ar(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!ar(s,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return ar(s,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!ar(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 Xn(t.expression,e),r=cr(t.targetType);return Zn(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await Xn(t.value,e),r=await Xn(t.min,e),i=await Xn(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],u=await Zn(e,"between").evaluate(e,o,a,c);return t.negated?!u:u}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return 1;if(Object.prototype.toString.call(t).slice(8,-1)===e)return 1;const r=globalThis[e];return"function"==typeof r&&t instanceof r}(await Xn(t.value,e),t.typeName+"",0!=t.nullOk);return t.negated?!n:n}(n,e);case"collectionExpression":return async function(t,e){const n=await Xn(t.collection,e);if(null==n)return n;const r=async(t,n)=>Xn(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=zn(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=[...zn(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=zn(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return s=await Xn(t.right,e),null==(i=n)?[]:(i+"").split(null==s?"":s+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return zn(t).map(t=>null==t?"":t+"").join(n)}(n,await Xn(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 Xn(n,e);switch(t.operator){case"not":case"!":return Zn(e,"not").evaluate(e,r);case"no":return Zn(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return Zn(e,"exists").evaluate(e,r);case"does not exist":return Zn(e,"doesNotExist").evaluate(e,r);case"is empty":return Zn(e,"isEmpty").evaluate(e,r);case"is not empty":return Zn(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 Xn(t.object,e);if(t.computed){const r=await Xn(t.property,e);return Array.isArray(n)&&"number"==typeof r&&0>r?n[n.length+r]:n?.[r]}return hr(n,t.property.name,e)}(n,e);case"propertyAccess":return async function(t,e){let n=await Xn(t.object,e);for(const r of(t.property+"").split(".")){if(null==n)return;n=await hr(n,r,e)}return n}(n,e);case"callExpression":return async function(t,e){const n=await Xn(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>Xn(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,i=await async function(t,e,n){return dr.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:Xn(t,n))):Promise.all(t.map(t=>Xn(t,n)))}(t.arguments,r,e);switch(r){case"closest":return Zn(e,"closest").evaluate(e,...i);case"previous":case"next":{const n=t.relativePositional;if(n){const t=n.from?pr(await Xn(n.from,e)):e.me,s=n.within?pr(await Xn(n.within,e)):void 0,o=n.inElt?await Xn(n.inElt,e):void 0;return Zn(e,r).evaluate(e,i[0],t,{within:s,inElt:o,inSearch:n.inSearch,wrapping:n.wrapping})}return Zn(e,r).evaluate(e,...i)}case"first":return Zn(e,"first").evaluate(e,...i);case"last":return Zn(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=>Xn(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const i=await Xn(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 Zn(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=br(t),r=await Promise.all(n.filter(t=>"expr"in t).map(t=>Qn(t.expr,e)));return wr(n,r)}(n,e),s=gr(t,r);i.forEach((t,e)=>t.setAttribute("data-hs-query-id",e+""));try{return await Zn(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 fr(t,/\{([^}]*)\}/g,async(t,n)=>(await Qn(n.trim(),e)??"")+"")}(n,e));const r="string"==typeof n?gr(t,n):n;return dn(await Zn(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 Zn(e,t.contextType).evaluate(e);case"my":case"myself":case"I":return Zn(e,"me").evaluate(e);case"your":case"yourself":return Zn(e,"you").evaluate(e);case"its":return Zn(e,"it").evaluate(e);case"event":return e.event;case"target":return e.target??e.event?.target??Zn(e,"me").evaluate(e);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return Zn(e,"document").evaluate(e);case"window":return Zn(e,"window").evaluate(e);default:return}}(n,e);case"possessiveExpression":return async function(t,e){const n=await Xn(t.object,e),r=t.property.name;return Zn(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 Xn(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await Xn(t.test,e)?Xn(t.consequent,e):t.alternate?Xn(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 Xn(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 Xn(t,e)+"",n[i]=await Xn(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 Xn(t.target,e);if(null==i)throw Error(`Cannot access property "${r}" of ${i}`);return Zn(e,"possessive").evaluate(e,i,r)}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await fr(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=lr(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(lr(n,e)??"")+""}catch{return""}}),n=await fr(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const i=n||r;try{return await Qn(i,e)+""}catch{return"undefined"}}),n}(n,e);case"stringPostfix":return async function(t,e){return`${await Xn(t.expression,e)}${t.unit}`}(n,e);case"blockLiteral":return ur(n,e);default:{const n=kt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}class Kn extends Error{constructor(t){super(`Expression node "${t}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}function Gn(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 Kn("selector");if(!t.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(n))throw new Kn("selector");if(t.fromQuery&&/\$[^=]/.test(n)){const{selector:r,elements:i}=function(t,e){const n=br(t),r=n.filter(t=>"expr"in t).map(t=>Yn(t.expr,e));return wr(n,r)}(n,e),s=gr(t,r),o=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!o)throw new Kn("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)=>(Yn(n.trim(),e)??"")+"")}(n,e):n,i=gr(t,r),s=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw new Kn("selector");return dn(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?on(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 Kn("contextReference")}}(n.contextType,e);case"arrayLiteral":return n.elements.map(t=>Gn(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:Gn(t,e)+"",n[i]=Gn(r.value,e)}return n}(n,e);case"asExpression":return Dn(Gn(n.expression,e),cr(n.targetType),e);case"stringPostfix":return`${Gn(n.expression,e)}${n.unit}`;case"blockLiteral":return ur(n,e);case"memberExpression":{const t=Gn(n.object,e);if(null==t)return;if(t instanceof Element||Array.isArray(t)||"undefined"!=typeof Node&&t instanceof Node)throw new Kn("memberExpression");const r=t[n.computed?Gn(n.property,e)+"":n.property?.name];return"function"==typeof r?r.bind(t):r}default:throw new Kn(n?.type??"unknown")}}function Yn(t,e){const n=Xe(t);if(!n.success||!n.node){const t=n.error??n.errors?.[0];throw Error("Failed to parse expression: "+(t?.message??"unknown error"))}return Gn(n.node,e)}async function Qn(t,e){const n=Xe(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 er()};return Xn(n.node,r)}let tr=null;async function er(){if(!tr){const t=await Promise.resolve().then(function(){return bo});tr=t.createFullExpressionRegistry()}return tr}async function nr(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?Zn(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?Zn(e,"you").evaluate(e):"it"===n||"its"===n?Zn(e,"it").evaluate(e):"result"===n?Zn(e,"result").evaluate(e):"window"===n?Zn(e,"window").evaluate(e):"document"===n?Zn(e,"document").evaluate(e):"global"===t.scope&&e.globals?.has(n)?(Rt(n,e),e.globals.get(n)):"element"===t.scope?on(e,n):e.locals&&e.locals.has(n)?(Lt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&Rt(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(Rt(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 rr(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=rr(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 ir(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 sr(t,e){return t&&"selector"===t.type&&"string"==typeof t.value?t.value:e}function or(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?1==i:void 0}function ar(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function cr(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 ur(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 Gn(t.body,s)}catch(e){if(e instanceof Kn)return Xn(t.body,s);throw e}}}function lr(t,e){if(e.locals?.has(t))return Lt(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 fr(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 hr(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?$n(t,e):Un(t)&&!(e in t)?Zn(n,"possessive").evaluate(n,t,e):t?.[e]}const dr=new Set(["closest","previous","next"]);function pr(t){return t instanceof Element?t:Array.isArray(t)&&t[0]instanceof Element?t[0]:void 0}const mr=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"),yr=/[:&()[\]/]/g;function gr(t,e){return t.fromQuery||!e.startsWith(".")||e.includes("{")?function(t){return t.replace(mr,"$1\\:")}(e):function(t){return t[0]+t.slice(1).replace(yr,"\\$&")}(e)}const vr=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function br(t){const e=[];let n,r=0;for(vr.lastIndex=0;null!==(n=vr.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 wr(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++];xn(t)?(n+=`[data-hs-query-id='${r.length}']`,r.push(t)):n+=(t??"")+""}return{selector:n,elements:r}}class Er{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??0}registerListener(t,e,n,r,i){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,i),this.debugMode&&lt(`CleanupRegistry: Removed listener '${n}'`)},description:n+" listener"})}registerObserver(t,e){this.addCleanup(t,{type:"observer",cleanup:()=>{e.disconnect(),this.debugMode&&lt("CleanupRegistry: Disconnected MutationObserver")},description:"MutationObserver"})}registerInterval(t,e){this.addCleanup(t,{type:"interval",cleanup:()=>{clearInterval(e),this.debugMode&&lt("CleanupRegistry: Cleared interval")},description:"Interval"})}registerTimeout(t,e){this.addCleanup(t,{type:"timeout",cleanup:()=>{clearTimeout(e),this.debugMode&&lt("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&&lt("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&&lt(`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&&lt("CleanupRegistry: Error during cleanup:",t)}this.typeCounts[t.type]--}return this.elementCleanups.delete(t),this.elementCount--,this.debugMode&&lt(`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&&lt("CleanupRegistry: Error during global cleanup:",t)}return this.globalCleanups=[],this.debugMode&&lt(`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 xr{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(t,e){const n=t.toLowerCase();this.sources.has(n)&&lt("[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 0}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 lt("[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)):0}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 kr{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??1,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??1,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)?1: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){lt(`[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 Sr={evaluate:(t,e)=>Xn(t,e)};class Ar{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 Tr{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(at(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void at(`CommandAdapterV2: '${this.name}' intercepted by hook`);const i=Ar.toTyped(t);let s,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(at(`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 Xn(r,t))return void at(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);s=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},Sr,t)}else s=e;else at(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),s=e;if(at("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 at("CommandAdapterV2: Command result:",o),Object.assign(t,Ar.fromTyped(i,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Lr(t)||at(`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):1,errors:[],suggestions:[]}}}class $r{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);lt(`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();lt(`CommandRegistryV2: Registering command '${n}'`),this.implementations.set(n,t);const r=new Tr(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:0,errors:[{type:"runtime-error",message:"Unknown command: "+t,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}let Cr=null;function Nr(){return Cr||(Cr=function(){const t=new $r,e=new xr,n=new kr,r=new Set,i={commands:t,eventSources:e,context:n,use(s){if(r.has(s.name))lt(`[LokaScriptRegistry] Plugin '${s.name}' is already installed`);else{if(s.commands)for(const e of s.commands)t.register(e);if(s.eventSources)for(const t of s.eventSources)e.register(t.name,t);if(s.contextProviders)for(const{name:t,provide:e,options:r}of s.contextProviders)n.register(t,e,r);s.setup?.(i),r.add(s.name)}},reset(){r.clear()}};return i}()),Cr}class Rr{constructor(t={}){this.contextCache=new WeakMap;const e=Nr();this.options={enableContextProviders:t.enableContextProviders??1,enableEventSources:t.enableEventSources??1,registry:t.registry??{}},this.contextRegistry=this.options.registry.context??e.context,this.eventSourceRegistry=this.options.registry.eventSources??e.eventSources,lt(`[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),lt(`[RegistryIntegration] Enhanced context with ${this.contextRegistry.getProviderNames().length} providers`),e}catch(e){return lt("[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 lt(`[RegistryIntegration] Found event source for '${t}'`),e;const n=this.eventSourceRegistry.findSourceForEvent(t);if(n){const e=this.eventSourceRegistry.get(n);return lt(`[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 lt(`[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,lt("[RegistryIntegration] Destroyed")}}function Or(t){const e=Error(t.type.toUpperCase()+"_EXECUTION");return e["is"+t.type.charAt(0).toUpperCase()+t.type.slice(1)]=1,"returnValue"in t&&(e.returnValue=t.returnValue),e}function Lr(t){return t instanceof Error?null!==Ge(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function jr(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const Mr=new WeakMap;function Ir(t,e=new Set){if(null===t||"object"!=typeof t)return e;if(Array.isArray(t)){for(const n of t)Ir(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&&Ir(n[t],e);return e}class Pr{constructor(t){this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.options={commandTimeout:1e4,enableErrorReporting:1,enableResultPattern:1,enableAutoCleanup:1,...t},this.registry=t.registry,this.expressionRegistry=t.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=en,this.hookRegistry=new Ke,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new Er,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new Rr("object"==typeof t.registryIntegration?t.registryIntegration:{}),lt("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&&lt(`RuntimeBase: Auto-cleaned ${e} resources for removed element`)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:1,subtree:1}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:1,subtree:1})},{once:1}))}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(),lt("RuntimeBase: Destroyed")}hasErrorDiagnostics(t){const e=t.diagnostics;return!!e?.some(t=>"error"===t.severity)}getWarnings(){return this.runtimeWarnings}async execute(t,e){lt(`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 lt("\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(!tn(n)){if("return"===n.error.type){const t=n.error.returnValue;return void 0!==t&&Object.assign(e,{it:t,result:t}),t}throw Or(n.error)}return n.value}try{return await this.processCommand(t,e)}catch(t){const n=Ge(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(!tn(r))throw Or(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(!tn(n))throw Or(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(at(`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 Lr(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=Ge(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(at(`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 Ye(await o.execute(e,{args:r||[],modifiers:i||{},commandName:s,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Qe(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];lt("\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(!tn(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}),Ye(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!tn(t))return t;n=t.value}}return Ye(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await Xn(t,n);return jr(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 Ye(await Xn(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Qe({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Qe({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Qe({type:"break"});if(e.isContinue)return Qe({type:"continue"});if(e.isReturn)return Qe({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!tn(r))return r;const i=r.value;if(jr(i)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:i.command,args:[{type:"literal",value:i.selector}]},e);try{return Ye(await this.executeCommandFromPattern(i.command,i.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Qe(e);throw t}}return Ye(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 u=async t=>{const e=await n.executeCommandSequenceWithResult(t,c);if(!tn(e))throw Ge(e.error);return e.value};if(!s&&!o)return await u(i);try{return await u(i)}catch(t){if(!s||Lr(t))throw t;return a&&c.locals.set(a,t),await u(s)}finally{o&&await u(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(Lr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Lr(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of o)try{n=await this.execute(t,e)}catch(t){if(Lr(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(Lr(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(Lr(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}),lt(`RUNTIME BASE: Registered imperative behavior '${n}'`)):(this.behaviorRegistry.set(n,{name:n,parameters:r,eventHandlers:i,initBlock:s}),lt(`RUNTIME BASE: Registered behavior '${n}'`))}async installBehaviorOnElement(t,e,n){lt("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&&(lt(`BEHAVIOR: Installing imperative behavior '${t}'`),r.install(e,n),lt(`BEHAVIOR: Finished installing imperative behavior '${t}'`)));lt("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:0,returned:0,broke:0,continued:0,async:0},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){lt("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))]),lt("BEHAVIOR: Init block completed for "+t)}catch(e){if(lt(`BEHAVIOR: Init block error for ${t}:`,e),!(e instanceof Error&&Lr(e)))throw e}}if(lt(`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))])}lt("BEHAVIOR: Finished installing "+t)}async executeEventHandler(t,e){const{event:n,events:r,commands:i,target:s,args:o,selector:a,condition:c,attributeName:u,watchTarget:l,modifiers:f,errorSymbol:h,errorHandler:d,finallyHandler:p}=t,m=r&&r.length>0?r:[n];lt(`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);lt(`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 lt(`BEHAVIOR: Target resolution: querying for '${s}'`),y=this.queryElements(s,e)}else y=e.me?[e.me]:[];if(0===y.length&&!g)return void lt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&u)return void this.setupMutationObserver(y,u,i,e);if("change"===n&&l)return void this.setupChangeObserver(l,i,e);const v=t.customEventSource;if(v&&this.registryIntegration){lt(`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);lt(`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);lt(`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=Pr.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:1}: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:0,cancelable:0});if(t.synthetic=1,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=Mr.get(a)??0;if(c>=100)return;if(Mr.set(a,c+1),r&&a.target instanceof Element)try{if(!a.target.matches(r)&&!a.target.closest(r))return}catch{lt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const u=new Map(n.locals),l={...n,locals:u,it:a,event:a};u.has("target")||l.locals.set("target",a.target);const f=t.enhanceContext(l);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 Ir(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 lt("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(Lr(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||Lr(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){lt(`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){ct(`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(Lr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(i,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(i,t),lt("RUNTIME BASE: MutationObserver attached to",i,`for attribute '${e}'`)}}async setupChangeObserver(t,e,n){lt("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))),lt(`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){ct("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(Lr(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing change handler command:",t)}}});r.observe(t,{childList:1,characterData:1,subtree:1,characterDataOldValue:1}),this.cleanupRegistry.registerObserver(t,r),lt("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 lt(`queryElements: invalid CSS selector '${i}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}function qr(...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 Hr(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 Br={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:jn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:jn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:jn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it??t.result,validate:jn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result??t.it,validate:jn},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=>On(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=>On(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=>On(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=>On(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:jn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:jn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:jn},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=>On(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 Hr(i,n)},validate:t=>In(t,1,2,"styleRef","property, optional element")??Rn(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 Hr(i,r)},validate:t=>Nn(t,2,"possessiveStyleRef","possessor, property")??Rn(t,0,"possessiveStyleRef","possessor")??Rn(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 Hr(i,n)},validate:t=>Nn(t,2,"ofStyleRef","property, reference")??Rn(t,0,"ofStyleRef","property")??Rn(t,1,"ofStyleRef","reference")}};function Dr(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const Fr=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Vr;function _r(){return Vr({validate:t=>({success:1,data:t})})}function Ur(t,e){if(Fr)return _r();const n=Vr({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:Dr("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:0,error:Dr("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:0,error:Dr("missing-argument",`Required field "${e}" is missing`,e)};const s=n.validate(t);if(!s.success)return{success:0,error:Dr("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:1,data:i}}});return n.strict=()=>Ur(t,{strict:1}),n}Vr=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:1,data:e.data}:{success:0,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:1,validate:e=>null==e?{success:1,data:void 0}:t(e)};return Vr(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:0,error:Dr("runtime-error",`String must be at least ${t} characters long`)}:r}};return Vr(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:0,error:Dr("runtime-error",`String must be at most ${t} characters long`)}:r}};return Vr(n)}),t.default||(t.default=function(t){const e=this.validate.bind(this),n={...this,i:t,o:1,validate:n=>void 0===n?{success:1,data:t}:e(n)};return Vr(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:0,error:Dr("runtime-error",e||"Refinement validation failed")}:i}};return Vr(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 Wr=t=>function(t={}){return Fr?_r():Vr({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:Dr("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:Dr("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:Dr("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:0,error:Dr("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:Dr("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),zr=t=>Ur(t),Zr=t=>function(t){return Fr?_r():Vr({validate:e=>{if(!Array.isArray(e))return{success:0,error:Dr("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:Dr("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:0,error:Dr("runtime-error",i.error.message,i.error.path?`${r}.${i.error.path}`:""+r)};n.push(i.data)}return{success:1,data:n}}})}(t),Jr=()=>_r();class Xr{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 Kr=new class{constructor(){this.domQueryCache=new Xr(200,3e3),this.exprResultCache=new Xr(500,2e3),this.cssMatchCache=new Xr(100,5e3),this.formValueCache=new Xr(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(()=>{Kr.cleanup()},1e4);const Gr=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=Kr.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 Yr(){Kr.cleanup(),Gr.getMetrics().memoryUsage>52428800&&Gr.reset()}let Qr=null;function ti(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 ti(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 ei(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 ni(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 ri(t){try{return ti(t,"_"),1}catch{return 0}}function ii(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 1;default:return 0}switch(n){case"==":case">":case"<":case">=":case"<=":default:return 0;case"!=":return 1}}(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=ei(t),r=ei(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 si(t,e);case"!=":return!si(t,e);default:return 0}}function si(t,e){if(t===e)return 1;if(typeof t==typeof e)return"string"==typeof t||"number"==typeof t?t===e:0;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?si(t?1:0,e):"boolean"==typeof e?si(t,e?1:0):t+""==e+""}function oi(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function ai(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function ci(t,e,n,r,i,s=1,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 ui(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}"undefined"!=typeof window&&function(t=3e4){Qr&&clearInterval(Qr),Qr=setInterval(Yr,t)}();const li=Zr([Jr(),Jr()]),fi=Zr([Jr(),Wr()]),hi={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return ci(this,t,[e,n],e==n,r)}catch(i){throw ci(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ln(t,"equals"),inputSchema:li,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:1,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:1}],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:0,examples:["5",'"hello"',"true","null"]},{name:"right",type:"unknown",description:"Right operand for comparison",optional:0,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"]}},di={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&&ci(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ln(t,"strictEquals")},pi={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&&ci(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ln(t,"notEquals")},mi={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&&ci(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ln(t,"strictNotEquals")},yi={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=ii(e,n,"<");return r&&ci(this,t,[e,n],s,i),s},validate:t=>Ln(t,"lessThan")},gi={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=ii(e,n,"<=");return r&&ci(this,t,[e,n],s,i),s},validate:t=>Ln(t,"lessThanOrEqual")},vi={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=ii(e,n,">");return r&&ci(this,t,[e,n],s,i),s},validate:t=>Ln(t,"greaterThan")},bi={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=ii(e,n,">=");return r&&ci(this,t,[e,n],s,i),s},validate:t=>Ln(t,"greaterThanOrEqual")},wi={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return ci(this,t,[e,n],e&&n,r)}catch(i){throw ci(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>Ln(t,"and"),inputSchema:li,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:0},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:1,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:0,examples:["true","name","5",'"hello"']},{name:"right",type:"unknown",description:"Right operand (evaluated for truthiness)",optional:0,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"]}},Ei={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&&ci(this,t,[e,n],i,r?Date.now():0),i},validate:t=>Ln(t,"or")},xi={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&ci(this,t,[e],r,n?Date.now():0),r},validate:t=>Nn(t,1,"not","operand")},ki={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?1:yn(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:bn(e)?0===Object.keys(e).length:0,n&&ci(this,t,[e],i,r),i},validate:t=>Nn(t,1,"isEmpty","value")},Si={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||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:(yn(e),0),n&&ci(this,t,[e],i,r),i},validate:t=>Nn(t,1,"no","value")},Ai={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 ki.evaluate(t,e);return n&&ci(this,t,[e],i,r),i},validate:t=>Nn(t,1,"isNotEmpty","value")},Ti={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,i=$i(e);return n&&ci(this,t,[e],i,r),i},validate:t=>Nn(t,1,"exists","value")};function $i(t){return null==t?0:Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList?t.length>0:1}const Ci={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=!$i(e);return n&&ci(this,t,[e],i,r),i},validate:t=>Nn(t,1,"doesNotExist","value")},Ni={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(ui(e)&&ui(n))return s=e.contains(n),r&&ci(this,t,[e,n],s,i),s;if(yn(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&ui(n))return s=o.contains(n),r&&ci(this,t,[e,n],s,i),s;if(o&&yn(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return s=a?o.contains(a):0,r&&ci(this,t,[e,n],s,i),s}}if(yn(n)&&n.match(/^[.#][\w-]+$/)&&ui(e)){const o=document.querySelector(n);return s=o?e.contains(o):0,r&&ci(this,t,[e,n],s,i),s}}if(yn(e)&&yn(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=bn(e)&&yn(n)?n in e:0;return r&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"contains","container, value")},Ri={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 Ni.evaluate(t,e,n);return r&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"doesNotContain","container, value")},Oi={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+""):0;return r&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"startsWith","str, prefix")},Li={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+""):0;return r&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"endsWith","str, suffix")},ji={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&&ci(this,t,[e,n,r],a,i?Date.now():0),a},validate:t=>Nn(t,3,"between","value, min, max")},Mi={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let i;if(e instanceof Element&&yn(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 Kr.matches(t,e)}(e,t)}catch(t){i=0}else i=0}else if(yn(e)&&yn(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=0;return ci(this,t,[e,n],i,r)}catch(i){throw ci(this,t,[e,n],0,r,0,i instanceof Error?i:Error(i+"")),i}},validate:t=>Nn(t,2,"matches","element, selector"),inputSchema:fi,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:1},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:1,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:0,examples:["<div>",'"hello world"',"me","target"]},{name:"selector",type:"string",description:"CSS selector or regex pattern to match against",optional:0,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"]}},Ii={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=0;if(e instanceof Element&&yn(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&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"has","element, selector")},Pi={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 Ii.evaluate(t,e,n);return r&&ci(this,t,[e,n],s,i),s},validate:t=>Nn(t,2,"doesNotHave","element, selector")},qi={equals:hi,strictEquals:di,notEquals:pi,strictNotEquals:mi,lessThan:yi,lessThanOrEqual:gi,greaterThan:vi,greaterThanOrEqual:bi,and:wi,or:Ei,not:xi,no:Si,isEmpty:ki,isNotEmpty:Ai,exists:Ti,doesNotExist:Ci,contains:Ni,doesNotContain:Ri,startsWith:Oi,endsWith:Li,between:ji,matches:Mi,has:Ii,doesNotHave:Pi};class Hi{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 0==t||0===t||0n===t||""===t||null==t||gn(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,n,r,i=[]){return{success:0,error:{name:t,type:e,message:n,code:r,suggestions:i}}}validationSuccess(){return{isValid:1,errors:[],suggestions:[]}}validationFailure(t,e,n=[]){return{isValid:0,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":bn(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":yn(t)?"String":gn(t)?"Number":vn(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):yn(t)?t.split(""):null==t?[]:bn(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(gn(t)&&Number.isFinite(t))return t;if(yn(t)){const e=Number(t);return Number.isFinite(e)?e:null}return vn(t)?t?1:0:null}}const Bi=zr({value:Wr().describe("String literal value")}).strict(),Di=zr({value:function(t={}){return Fr?_r():Vr({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:Dr("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:Dr("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:Dr("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}({}).describe("Number literal value")}).strict(),Fi=zr({value:(Fr?_r():Vr({validate:t=>"boolean"!=typeof t?{success:0,error:Dr("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}})).describe("Boolean literal value")}).strict(),Vi=zr({left:Jr().describe("Left operand"),right:Jr().describe("Right operand")}).strict();const _i={stringLiteral:new class extends Hi{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=Bi,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,0),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,1,i),s}catch(e){return this.trackSimple(t,n,0),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)?(Lt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends Hi{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Di,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,1,e.value),this.success(e.value,"number")):(this.trackSimple(t,n,0),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),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 Hi{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Fi,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,1,e.value),this.success(e.value,"boolean")):(this.trackSimple(t,n,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions))}catch(e){return this.trackSimple(t,n,0),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 Hi{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Vi,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,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ti(e.left,"left operand")+ti(e.right,"right operand");return this.trackSimple(t,n,1,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,0),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 Hi{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=Vi,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,0),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,1,i),this.success(i,"string")}catch(e){return this.trackSimple(t,n,0),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=Vi.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(yn(t))return t;if(gn(t))return""+t;if(vn(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends Hi{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Vi,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,0),this.failure("ValidationError","validation-error",r.errors.map(t=>t.message).join(", "),"VALIDATION_FAILED",r.suggestions);const i=ti(e.left,"left operand")*ti(e.right,"right operand");return this.trackSimple(t,n,1,i),this.success(i,"number")}catch(e){return this.trackSimple(t,n,0),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"])}}}};function Ui(){return qr(Br,qi,_i)}class Wi{constructor(t){this.observer=null,this.initialized=0,this.runtime=t}init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=1,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:1,subtree:1,attributes:1,attributeFilter:["_"]})))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=0}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=cn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function zi(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,u="getter"===c?"get":"setter"===c?"set":"value",l=!e&&t?r.static?t:t.prototype:null,f=e||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),h=0,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[u],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[u]=a)}l&&Object.defineProperty(l,r.name,f),h=1}function Zi(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 Ji(t,e,n){return"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:1,value:n?"".concat(n," ",e):e})}function Xi(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function Ki(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 Gi(t,e){for(const n of t)e(n);return t}function Yi(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function Qi(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 ts(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&&ns(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&&ns(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&ns(n)?[n]:[]}function es(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function ns(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return es(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function rs(t,e){return t.map(t=>{if(es(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+"":(at(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}function is(t){return function(e,n){Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function ss(t){return{...t}}function os(t){return()=>new t}function as(t,e){return e}function cs(t,e,n){if(un(t))return t;if(!t){const t=e.me;if(!t)throw Error(as(0,"No target element \u2014 provide explicit target or ensure context.me is set"));return us(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(as(0,'Context reference "me" is not available'));return us(e.me)}if("it"===n){if(!un(e.it))throw Error(as(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(as(0,'Context reference "you" is not available'));return us(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(as(0,"DOM not available \u2014 cannot resolve element selector"));const i=r.querySelector(n);if(!i)throw Error(as(0,"Element not found with selector: "+n));if(!un(i))throw Error(as(0,"Element found but is not an HTMLElement: "+n));return i}throw Error(as(0,"Invalid target type: "+typeof t))}function us(t){if(un(t))return t;throw Error("Value is not an HTMLElement")}function ls(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(as(0,'No "me" element in context'));if(!un(e.me))throw Error(as(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(as(0,'No "it" value in context'));if(!un(e.it))throw Error(as(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(as(0,'No "you" element in context'));if(!un(e.you))throw Error(as(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(as(0,"Unknown possessive: "+t))}}"function"==typeof SuppressedError&&SuppressedError;const fs=["on","from","to","in","with","at"];async function hs(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?!fs.includes(e.name.toLowerCase()):1})),(!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(!un(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(un(i))a.push(i);else if(ln(i)){const t=Array.from(i).filter(un);a.push(...t)}else if(Array.isArray(i)){const t=i.filter(un);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(un);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(!un(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function ds(t){return"string"==typeof t&&t.trim().startsWith("*")}function ps(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 ms(t,e,n){t.style.setProperty(e,n)}const ys=["dialog","details","summary","select"];function gs(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 vs(t,e,n){return function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"classSelector"!==e)return 0;const n=gs(t);return"string"==typeof n&&n.startsWith(".")}(t)||function(t){if(!t||"object"!=typeof t)return 0;const e=t.type;if("selector"!==e&&"cssSelector"!==e&&"cssProperty"!==e)return 0;const n=gs(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:gs(t),extractedFromNode:1}:function(t){if(!t||"object"!=typeof t)return 0;if("attributeAccess"===t.type)return 1;if("selector"===t.type||"cssSelector"===t.type){const e=gs(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:gs(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class bs{async resolveTargets(t,e,n,r){return hs(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return vs(t,e,n)}parseClassNames(t){return ts(t)}isAttribute(t){return Xi(t.trim())}isCSSProperty(t){return ds(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>un(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 ws=(()=>{let t,e,n=[is({name:"add"})],r=[],i=bs;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=Ki(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=rs(t.classes,e);n.length>0&&Yi(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,Gi(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":Yi(t.targets,Object.entries(t.styles),(t,[e,n])=>{t.style.setProperty(e,n)})}var n,r}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0;if("string"!=typeof t.value)return 0}else if("styles"===e.type){const e=t;if("object"!=typeof e.styles||null===e.styles)return 0;if(Array.isArray(e.styles))return 0;const n=e.styles;if(0===Object.keys(n).length)return 0;if(!Object.values(n).every(t=>"string"==typeof t))return 0}return 1}};return Ji(e,"AddCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;zi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=ss({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"}),Zi(e,r),s=e})();const Es=os(ws),xs={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function ks(t){return t.includes("<")&&t.includes(">")}function Ss(t,e,n){!function(t,e,n){"replace"!==n?un(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').`);ks(e)?t.insertAdjacentHTML(r,e):t.insertAdjacentText(r,e)}(t,e,n):function(t,e){un(e)?(t.innerHTML="",t.appendChild(e)):ks(e)?t.innerHTML=e:t.textContent=e}(t,e)}(t,e,function(t){const e=xs[t];if(void 0===e)throw Error(`Unknown semantic position '${t}'. Valid positions: ${Object.keys(xs).join(", ")}.`);return e}(n))}function As(t){return t.parentNode?(t.remove(),1):0}let Ts=(()=>{let t,e,n=[is({name:"remove"})],r=[],i=bs;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(un(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&un(r[0]))return{type:"element",targets:r.filter(t=>un(t))};if("string"==typeof r){const i=r.trim();if(this.isAttribute(i))return{type:"attribute",name:Ki(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=rs(t.classes,e);n.length>0&&Yi(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,Gi(t.targets,t=>{t.removeAttribute(n)});break;case"styles":Yi(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)As(e)}var n}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;if(!this.validateType(e.type,["classes","attribute","styles","element"]))return 0;if(!this.validateTargets(e.targets))return 0;if("classes"===e.type){if(!this.validateStringArray(t.classes,1))return 0}else if("attribute"===e.type){if("string"!=typeof t.name||0===t.name.length)return 0}else if("styles"===e.type&&!this.validateStringArray(t.properties,1))return 0;return 1}};return Ji(e,"RemoveCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;zi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=ss({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"}),Zi(e,r),s=e})();const $s=os(Ts);function Cs(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 Ns(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Cs(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Rs(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Os(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&Qi(t,n)}}function Ls(t,e,n,r){const i=Os(t,e,n),s=setTimeout(i,r);return()=>{clearTimeout(s)}}function js(t,e,n,r){const i=Os(t,e,n),s=()=>{i(),t.removeEventListener(r,s)};return t.addEventListener(r,s,{once:1}),()=>{t.removeEventListener(r,s)}}function Ms(t,e,n){if(e.startsWith("@")){const r=e.substring(1);return void(0==n?t.removeAttribute(r):t.setAttribute(r,1==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 Is=/^the\s+(.+?)\s+of\s+(.+)$/i,Ps=new Set(["disabled","checked","hidden","readOnly","readonly","required","multiple","selected","autofocus","autoplay","controls","loop","muted","open","reversed","async","defer","noValidate","novalidate","formNoValidate","formnovalidate","draggable","spellcheck","contentEditable"]);function qs(t){return"string"==typeof t&&Is.test(t)}function Hs(t,e){const n=t.match(Is);if(!n)return null;try{return{element:cs(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Bs(t,e,n){if(function(t){return t&&"object"==typeof t?"propertyOfExpression"===t.type&&"object"==typeof t.property&&null!==t.property:0}(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]),un(i)?{element:i,property:r}:null}(t,e,n);if(function(t){return t&&"object"==typeof t?"propertyAccess"!==t.type?0:"string"==typeof t.property||"object"==typeof t.property&&null!==t.property&&"string"==typeof t.property.name:0}(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]),un(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]),!un(s))return null;const o=i?.name||i?.value;return o?{element:s,property:o}:null}return null}function Ds(t,e){const{element:n,property:r}=t;r.startsWith("*")?ms(n,r.substring(1),e+""):Ms(n,r,e)}async function Fs(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=Cs(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}}const Vs=os((()=>{let t,e,n=[is({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=0;if(function(t){if(!t||"asExpression"!==t.type)return 0;const e=t.targetType,n="string"==typeof e?e:e?.name;return"string"==typeof n&&"modal"===n.toLowerCase()}(t.args[0])){r=1;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 Fs(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 u={filterPrepositions:1,fallbackModifierKey:"on"},l=await hs(c,e,n,"toggle",u,t.modifiers);return{type:"classes-between",classA:(o+"").replace(/^\./,""),classB:(a+"").replace(/^\./,""),targets:l,duration:r,untilEvent:i}}const o=await Bs(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 Fs(t.modifiers,e,n),a=ps(r);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:s,untilEvent:o}}}}const o=ps(r);if(o){const{duration:r,untilEvent:i}=await Fs(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await hs(t.args.slice(s),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:i}}}const{duration:a,untilEvent:c}=await Fs(t.modifiers,e,n),{value:u}=await vs(i,e,n);if(qs(u)){const t=Hs(u,n);if(t)return{type:"property",target:t}}const{type:l,expression:f}=function(t,e){const n=e?.name,r=function(t){if(!t||"object"!=typeof t)return 0;if("identifier"!==t.type)return 0;const e=t.name;return"string"==typeof e&&function(t){if("string"!=typeof t)return 0;const e=t.toLowerCase();return ys.includes(e)}(e)}(e);if(un(t)||Array.isArray(t)&&t.every(t=>un(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 0;const e=t.toLowerCase();return ys.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(u,i),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:i}=Ki(f);return{type:"attribute",name:r,value:i,targets:await hs(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:a,untilEvent:c}}case"css-property":{const r=ps(f);if(!r)throw Error("Invalid CSS property: "+f);return{type:"css-property",property:r,targets:await hs(t.args.slice(1),e,n,"toggle",h,t.modifiers)}}case"element":{let s;if(un(u))s=[u];else if(Array.isArray(u)&&u.every(t=>un(t)))s=u;else if(f){const t=document.querySelectorAll(f);s=Array.from(t).filter(t=>un(t))}else s=await hs([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:Rs(s)}:"select"===o?{type:"select",targets:s}:{type:"classes",classes:ts(f),targets:s,duration:a,untilEvent:c}}default:{const r=ts(f||u);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await hs(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=rs(t.classes,e);if(0===n.length)return[...t.targets];if(Yi(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&Ls(e,"class",n[0],t.duration),t.untilEvent&&js(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,Gi(t.targets,t=>{Qi(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&Ls(e,"attribute",t.name,t.duration),t.untilEvent&&js(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return Gi(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)):$n(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Ps.has(r)||Ps.has(r.toLowerCase())){const n=!e;return Ds(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Ds(t,n),n}if("string"==typeof e){const r="__ht_"+n,i=t.element[r];return""===e&&void 0!==i?(Ds(t,i),i):(t.element[r]=e,Ds(t,""),"")}Ds(t,!e)}(t.target),[t.target.element];case"dialog":return Gi(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 Gi(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return Gi(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:1,cancelable:1});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&&Ls(e,"class",t.classA,t.duration),t.untilEvent&&js(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}};return Ji(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})());class _s{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await hs(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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>un(t))?"show"!==e.mode&&"hide"!==e.mode||"show"===e.mode&&"string"!=typeof e.defaultDisplay?0:1:0}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 Us=(()=>{let t,e,n=[is({name:"show"})],r=[],i=_s;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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>un(t))?"string"!=typeof e.defaultDisplay?0:1:0}};return Ji(e,"ShowCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;zi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=ss({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"}),Zi(e,r),s=e})();const Ws=os(Us);let zs=(()=>{let t,e,n=[is({name:"hide"})],r=[],i=_s;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 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>un(t))?1:0}};return Ji(e,"HideCommand"),(()=>{const o="function"==typeof Symbol&&Symbol.metadata?Object.create(i[Symbol.metadata]??null):void 0;zi(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:1,configurable:1,writable:1,value:o})})(),e.metadata=ss({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"}),Zi(e,r),s=e})();const Zs=os(zs),Js=os((()=>{let t,e,n=[is({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 u=await e.evaluate(a,n),l=this.mapPosition(o);let f,h,d=null;if(c){const t=r(c),i=await Bs(c,e,n);if(i)return{value:u,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:u,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&&qs(t)){const e=Hs(t,n);if(e)return{value:u,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=pn(await e.evaluate(c,n));if(r)return{value:u,targets:r,position:l,memberPath:f};h=t}}else{const t=await e.evaluate(c,n),r=pn(t);if(r)return{value:u,targets:r,position:l,memberPath:f};"string"==typeof t&&(this.looksLikeCss(t)?d=t:h=t)}}return h?{value:u,targets:[],position:l,memberPath:f,variableName:h}:{value:u,targets:await this.resolveTargets(d,n),position:l,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)Ss(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||!un(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=>un(t));if(!e.length)throw Error(`No elements: "${t}"`);return e}(t)}parseValue(t){return un(t)?t:null==t?"":t+""}looksLikeCss(t){return t?/^[#.\[]/.test(t)||/[>+~\s]/.test(t)&&t.length>1?1:["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()):0}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 Ji(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})());async function Xs(t,e,n){const r=await e.evaluate(t,n),i=Array.isArray(r)?r[0]:r;return un(i)?i:null}const Ks=os((()=>{let t,e,n=[is({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=St.get(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 Xs(i.right,e,n);if(t)return{elements:[t],name:i.left.attributeName}}if("memberExpression"===i?.type&&"attributeAccess"===i.property?.type){const t=await Xs(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 Bs(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 0;if(un(t)||t instanceof Node)return 0;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(qs(a)){const r=Hs(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&&ds(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&&Xi(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=ls(r[1],n),s=await this.extractValue(t,e,n);return{type:"property",element:i,property:r[2],value:s}}}if(un(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&un(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?an(e,t.name,t.value):"global"===t.scope?hn(t.name,t.value,e,"global"):hn(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 Ms(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return ms(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))Ms(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=ls(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 cs(t?await e.evaluate(t,n):void 0,n)}async resolveTargets(t,e,n){return function(t,e){if(Array.isArray(t))return t.filter(un);if(ln(t))return Array.from(t).filter(un);if(un(t))return[t];if(!t){const t=e.me;return t&&un(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&un(e.me)?[e.me]:[];if("it"===n)return un(e.it)?[e.it]:[];if("you"===n)return e.you&&un(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(un)}}return[]}(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=cs(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 0;const e=t;if(!e.type||"string"!=typeof e.type)return 0;if(!["variable","attribute","property","style","object-literal"].includes(e.type))return 0;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(un)&&"value"in e;case"property":return"string"==typeof e.property&&un(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&un(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 0}}};return Ji(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})());function Gs(t){const e=t.trim();return/^\d+$/.test(e)?parseInt(e,10):/^\d*\.\d+$/.test(e)?parseFloat(e):"true"===e?1:"false"===e?0:"null"===e?null:"undefined"!==e?e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e:void 0}let Ys=(()=>{let t,e,n=[is({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,u;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 l=t.modifiers?.on||t.modifiers?.to;if(l)u=await this.resolveTargets([l],e,n,i);else{const r=t.args.findIndex((t,e)=>{if(0===e)return 0;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);u=await this.resolveTargets(a,e,n,i)}else{if(!n.me)throw Error(i+": no target specified and context.me is null");u=[n.me]}}return{eventName:a,detail:c,targets:u,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:1,cancelable:void 0!==n.cancelable?n.cancelable:1,composed:void 0!==n.composed?n.composed:0})}(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(un(t))i.push(t);else if(t instanceof NodeList)i.push(...Array.from(t).filter(un));else if(Array.isArray(t))i.push(...t.filter(un));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(un));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()]=Gs(n.trim())}}else Object.assign(r,t)}return Object.keys(r).length?r:void 0}async parseEventOptions(t,e,n){const r={bubbles:1,cancelable:1,composed:0},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=1:"nobubbles"===e?r.bubbles=0:"cancelable"===e?r.cancelable=1:"nocancelable"===e?r.cancelable=0:"composed"===e&&(r.composed=1)}}return r}};return Ji(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})();const Qs=os(Ys),to=os((()=>{let t,e,n=[is({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?0:Array.isArray(t.values)}};return Ji(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})());function eo(t,e,n,r){return t?new Promise(n=>{const i=()=>{s({event:null,timedOut:0,cancelled:1})},s=function(n,s){let a=0;return n=>{a||(a=1,t.removeEventListener(e,o),r&&r.removeEventListener("abort",i),s(n))}}(0,n),o=t=>{s({event:t,timedOut:0,cancelled:0})};r?.aborted?n({event:null,timedOut:0,cancelled:1}):(t.addEventListener(e,o),r&&r.addEventListener("abort",i))}):Promise.reject(Error("waitForEvent: no target provided"))}function no(t){return new Promise(e=>setTimeout(e,t))}const ro=os((()=>{let t,e,n=[is({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 no(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,i=(await eo(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:Ns(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:Ns(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:Ns(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?no(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):eo(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 Ji(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;zi(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:1,configurable:1,writable:1,value:s})})(),e.metadata=ss({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"}),Zi(e,r),i=e})()),io=function(t,e){const n=new $r(null);for(const e of t)n.register(e);return new Pr({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([Es(),$s(),Vs(),Ws(),Zs(),Js(),Ks(),Qs(),to(),ro()],{expressionRegistry:Ui()}),so={parse:t=>Xe(t),execute:async(t,e)=>{const n=function(t){if(!t)return cn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=cn(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=Xe(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await io.execute(r.node,n)}},oo=function(t){return new Wi(t)}(so),ao={runtime:so,parse:t=>so.parse(t),execute:async(t,e)=>so.execute(t,e),createContext:cn,attributeProcessor:oo,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>so.execute(t,e),init:()=>{oo.init()}};"undefined"!=typeof window&&(window.hyperfixi=ao,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{oo.init()}):oo.init());const co={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:yn(n)?n.length>0?n[0]:null:bn(n)&&"length"in n&&gn(n.length)&&n.length>0?n[0]:null},validate:t=>Mn(t,1,"first","collection")},uo={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 yn(n)?n.length>0?n[n.length-1]:null:bn(n)&&"length"in n&&gn(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Mn(t,1,"last","collection")},lo={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!gn(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(yn(s)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}if(bn(s)&&"length"in s&&gn(s.length)){const t=0>i?s.length+i:i;return t>=0&&s.length>t?s[t]:null}return null},validate:t=>In(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function fo(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?fo(r,e):null}function ho(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?ho(r,e):null}function po(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 mo(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 yo={first:co,last:uo,at:lo,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?po(s,n,i,1):fo(s,n):s.nextElementSibling:null},validate:t=>Mn(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?po(s,n,i,0):ho(s,n):s.previousElementSibling:null},validate:t=>Mn(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=mo(t);for(const t of r)if(mo(t)>i)return t;return null}(s,n,o):null},validate:t=>In(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=mo(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(i>mo(e))return e}return null}(s,n,o):null},validate:t=>In(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")}};class go{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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ni(ti(t,"left operand")+ti(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[ai("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 oi([ai("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return oi([ai("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"),oi([ai("missing-argument",`Missing ${t.join(" and ")} operand${t.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:1,errors:[],suggestions:[]}}(t);if(!e.isValid)return e;const{left:n,right:r}=t;return ri(n)?ri(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[ai("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[ai("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const vo={addition:new go,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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ni(ti(t,"left operand")-ti(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[ai("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new go).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e;return{success:1,value:ni(ti(t,"left operand")*ti(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[ai("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new go).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=function(t,e,n=1){if(0===e){if(n)return 0===t?NaN:t>0?1/0:-1/0;throw Error("Division by zero")}return t/e}(ti(t,"left operand"),ti(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ai("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new go).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:0,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}(ti(t,"left operand"),ti(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[ai("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 go).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:0,errors:n.errors,suggestions:n.suggestions};try{const{left:t,right:n}=e,r=ti(t,"left operand"),i=ti(n,"right operand");return{success:1,value:ni(Math.pow(r,i),"power"),type:"number"}}catch(t){return{success:0,errors:[ai("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new go).validate(t)}}};var bo=Object.freeze({__proto__:null,conversion:Fn,conversionExpressions:Fn,createCommonRegistry:function(){return qr(Br,qi,_i,Fn,yo)},createCoreRegistry:Ui,createExpressionRegistry:qr,createFullExpressionRegistry:function(){return qr(Br,qi,Fn,yo,Wn,_i,vo)},createFullRegistry:function(){return qr(Br,qi,_i,Fn,yo,Wn)},logical:qi,logicalExpressions:qi,positional:yo,positionalExpressions:yo,properties:Wn,propertiesExpressions:Wn,references:Br,referencesExpressions:Br,special:_i,specialExpressions:_i});return ao}();