@hyperfixi/core 2.3.1 → 2.5.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 (194) hide show
  1. package/dist/api/dom-processor.d.ts +8 -4
  2. package/dist/api/hyperscript-api.d.ts +5 -1
  3. package/dist/ast-utils/index.js +25320 -94
  4. package/dist/ast-utils/index.mjs +25320 -94
  5. package/dist/ast-utils/interchange/types.d.ts +7 -1
  6. package/dist/behaviors/index.js +54 -100
  7. package/dist/behaviors/index.mjs +54 -100
  8. package/dist/bundle-generator/index.js +19 -2
  9. package/dist/bundle-generator/index.mjs +19 -2
  10. package/dist/bundle-generator/parser-templates.d.ts +1 -1
  11. package/dist/bundle-generator/template-capabilities.d.ts +1 -1
  12. package/dist/chunks/bridge-Ce2mO-nk.js +2 -0
  13. package/dist/chunks/browser-modular-D5vPrb2X.js +2 -0
  14. package/dist/chunks/feature-eventsource-BpZvPy_K.js +2 -0
  15. package/dist/chunks/{feature-sockets-ClOH7vk7.js → feature-sockets-CrYvjZ4j.js} +2 -2
  16. package/dist/chunks/feature-webworker-BSYguEIW.js +2 -0
  17. package/dist/chunks/index-DsBHN4zW.js +2 -0
  18. package/dist/commands/advanced/async.d.ts +6 -2
  19. package/dist/commands/advanced/js.d.ts +1 -1
  20. package/dist/commands/animation/start-view-transition.d.ts +24 -0
  21. package/dist/commands/async/fetch.d.ts +6 -1
  22. package/dist/commands/control-flow/repeat.d.ts +2 -0
  23. package/dist/commands/data/clear.d.ts +23 -0
  24. package/dist/commands/data/set.d.ts +6 -0
  25. package/dist/commands/dom/close.d.ts +19 -0
  26. package/dist/commands/dom/empty.d.ts +19 -0
  27. package/dist/commands/dom/open.d.ts +21 -0
  28. package/dist/commands/dom/reset.d.ts +19 -0
  29. package/dist/commands/dom/select.d.ts +19 -0
  30. package/dist/commands/dom/swap.d.ts +7 -4
  31. package/dist/commands/events/trigger.d.ts +1 -1
  32. package/dist/commands/execution/blur.d.ts +19 -0
  33. package/dist/commands/execution/call.d.ts +1 -2
  34. package/dist/commands/execution/focus.d.ts +19 -0
  35. package/dist/commands/helpers/element-resolution.d.ts +2 -2
  36. package/dist/commands/helpers/event-waiting.d.ts +1 -1
  37. package/dist/commands/helpers/numeric-target-parser.d.ts +7 -0
  38. package/dist/commands/index.d.ts +34 -2
  39. package/dist/commands/index.js +19353 -4845
  40. package/dist/commands/index.mjs +19321 -4846
  41. package/dist/commands/navigation/go.d.ts +3 -0
  42. package/dist/commands/navigation/scroll-to.d.ts +26 -0
  43. package/dist/commands/utility/beep.d.ts +2 -2
  44. package/dist/commands/utility/breakpoint.d.ts +19 -0
  45. package/dist/commands/utility/pick.d.ts +11 -2
  46. package/dist/compatibility/browser-bundle-modular.d.ts +2 -2
  47. package/dist/compatibility/browser-bundle-multilingual.d.ts +1 -1
  48. package/dist/compatibility/browser-bundle-semantic-complete.d.ts +3 -3
  49. package/dist/compatibility/browser-bundle.d.ts +13 -6
  50. package/dist/compatibility/browser-modular.d.ts +1 -3
  51. package/dist/core/expression-evaluator.d.ts +4 -4
  52. package/dist/core/expression-registry.d.ts +8 -0
  53. package/dist/expressions/bundles/common-expressions.d.ts +2 -2
  54. package/dist/expressions/bundles/core-expressions.d.ts +2 -2
  55. package/dist/expressions/bundles/full-expressions.d.ts +2 -2
  56. package/dist/expressions/bundles/index.d.ts +3 -3
  57. package/dist/expressions/collection/index.d.ts +35 -0
  58. package/dist/expressions/conversion/impl/index.d.ts +1 -1
  59. package/dist/expressions/index.d.ts +4 -3
  60. package/dist/expressions/index.js +1117 -1590
  61. package/dist/expressions/index.mjs +1113 -1586
  62. package/dist/expressions/logical/index.d.ts +2 -0
  63. package/dist/expressions/mathematical/index.d.ts +11 -0
  64. package/dist/expressions/shared/index.d.ts +1 -1
  65. package/dist/expressions/shared/number-utils.d.ts +1 -0
  66. package/dist/htmx/htmx-attribute-processor.d.ts +37 -1
  67. package/dist/htmx/htmx-translator.d.ts +2 -0
  68. package/dist/htmx/i18n-hooks.d.ts +15 -0
  69. package/dist/htmx/i18n-orchestrator.d.ts +15 -0
  70. package/dist/htmx/lang-resolver.d.ts +3 -0
  71. package/dist/htmx/sse.d.ts +60 -0
  72. package/dist/htmx/ws.d.ts +59 -0
  73. package/dist/hyperfixi-browser-classic-i18n.js +2 -0
  74. package/dist/hyperfixi-browser-minimal.js +1 -0
  75. package/dist/hyperfixi-browser-standard.js +2 -0
  76. package/dist/hyperfixi-browser.js +2 -0
  77. package/dist/hyperfixi-classic-i18n.js +1 -1
  78. package/dist/hyperfixi-hx-v4.js +1 -0
  79. package/dist/hyperfixi-hx.js +1 -1
  80. package/dist/hyperfixi-hybrid-complete.js +1 -1
  81. package/dist/hyperfixi-hybrid-hx.js +1 -0
  82. package/dist/hyperfixi-minimal.js +1 -1
  83. package/dist/hyperfixi-multilingual.js +1 -1
  84. package/dist/hyperfixi-standard.js +1 -1
  85. package/dist/hyperfixi.js +1 -1
  86. package/dist/hyperfixi.mjs +1 -1
  87. package/dist/index.d.ts +2 -0
  88. package/dist/index.js +43592 -45060
  89. package/dist/index.min.js +1 -1
  90. package/dist/index.mjs +43589 -45061
  91. package/dist/lib/index.d.ts +2 -2
  92. package/dist/lib/morph-adapter.d.ts +0 -13
  93. package/dist/lib/swap-executor.d.ts +0 -10
  94. package/dist/lib/view-transitions.d.ts +1 -30
  95. package/dist/lokascript-browser-classic-i18n.js +1 -1
  96. package/dist/lokascript-browser-minimal.js +1 -1
  97. package/dist/lokascript-browser-standard.js +1 -1
  98. package/dist/lokascript-browser.js +1 -1
  99. package/dist/lokascript-hybrid-complete.js +1 -1
  100. package/dist/lokascript-hybrid-hx.js +1 -1
  101. package/dist/lokascript-multilingual.js +1 -1
  102. package/dist/lsp-metadata.d.ts +9 -4
  103. package/dist/lsp-metadata.js +187 -3
  104. package/dist/lsp-metadata.mjs +185 -4
  105. package/dist/metadata.d.ts +1 -1
  106. package/dist/metadata.js +3 -3
  107. package/dist/metadata.mjs +3 -3
  108. package/dist/multilingual/bridge.d.ts +1 -1
  109. package/dist/multilingual/index.js +79 -22
  110. package/dist/multilingual/index.mjs +79 -22
  111. package/dist/parser/command-parsers/animation-commands.d.ts +1 -0
  112. package/dist/parser/command-parsers/utility-commands.d.ts +1 -0
  113. package/dist/parser/extensions.d.ts +51 -0
  114. package/dist/parser/full-parser.js +1223 -897
  115. package/dist/parser/full-parser.mjs +1223 -897
  116. package/dist/parser/helpers/ast-helpers.d.ts +1 -0
  117. package/dist/parser/helpers/parsing-helpers.d.ts +4 -0
  118. package/dist/parser/parser-types.d.ts +8 -28
  119. package/dist/parser/parser.d.ts +3 -7
  120. package/dist/parser/pratt-parser.d.ts +0 -3
  121. package/dist/parser/runtime.d.ts +4 -0
  122. package/dist/parser/semantic-integration.d.ts +17 -0
  123. package/dist/parser/types.d.ts +7 -1
  124. package/dist/reference/index.js +91 -0
  125. package/dist/reference/index.mjs +91 -0
  126. package/dist/registry/index.js +12867 -5876
  127. package/dist/registry/index.mjs +12867 -5876
  128. package/dist/registry/universal-types.d.ts +2 -1
  129. package/dist/runtime/command-adapter.d.ts +23 -16
  130. package/dist/runtime/plugin.d.ts +14 -0
  131. package/dist/runtime/runtime-base.d.ts +32 -7
  132. package/dist/runtime/runtime-factory.d.ts +3 -3
  133. package/dist/runtime/runtime.d.ts +2 -2
  134. package/dist/test-setup.d.ts +1 -0
  135. package/dist/types/base-types.d.ts +3 -0
  136. package/dist/types/feature-types.d.ts +1 -1
  137. package/dist/types/index.d.ts +2 -2
  138. package/package.json +29 -23
  139. package/vocab/htmx/ar.js +60 -0
  140. package/vocab/htmx/bn.js +49 -0
  141. package/vocab/htmx/de.js +60 -0
  142. package/vocab/htmx/en.js +21 -0
  143. package/vocab/htmx/es.js +60 -0
  144. package/vocab/htmx/fr.js +59 -0
  145. package/vocab/htmx/he.js +40 -0
  146. package/vocab/htmx/hi.js +60 -0
  147. package/vocab/htmx/id.js +57 -0
  148. package/vocab/htmx/it.js +58 -0
  149. package/vocab/htmx/ja.js +60 -0
  150. package/vocab/htmx/ko.js +60 -0
  151. package/vocab/htmx/ms.js +35 -0
  152. package/vocab/htmx/pl.js +60 -0
  153. package/vocab/htmx/pt.js +60 -0
  154. package/vocab/htmx/qu.js +60 -0
  155. package/vocab/htmx/ru.js +60 -0
  156. package/vocab/htmx/sw.js +59 -0
  157. package/vocab/htmx/th.js +49 -0
  158. package/vocab/htmx/tl.js +33 -0
  159. package/vocab/htmx/tr.js +60 -0
  160. package/vocab/htmx/uk.js +60 -0
  161. package/vocab/htmx/vi.js +51 -0
  162. package/vocab/htmx/zh.js +60 -0
  163. package/dist/bundles/test-minimal.d.ts +0 -3
  164. package/dist/bundles/test-standard.d.ts +0 -3
  165. package/dist/chunks/bridge-Clbh_xAj.js +0 -2
  166. package/dist/chunks/browser-modular-DIOxQqhV.js +0 -2
  167. package/dist/chunks/feature-eventsource-B5F2-H1r.js +0 -2
  168. package/dist/chunks/feature-webworker-3bAp0ac9.js +0 -2
  169. package/dist/chunks/index-DcxoRUBe.js +0 -2
  170. package/dist/compatibility/browser-bundle-minimal.d.ts +0 -8
  171. package/dist/compatibility/browser-bundle-standard.d.ts +0 -8
  172. package/dist/compatibility/hyperscript-tests/test-adapter.d.ts +0 -13
  173. package/dist/core/base-expression-evaluator.d.ts +0 -74
  174. package/dist/core/binary-expression-evaluator.d.ts +0 -7
  175. package/dist/core/call-expression-evaluator.d.ts +0 -7
  176. package/dist/core/configurable-expression-evaluator.d.ts +0 -5
  177. package/dist/core/lazy-expression-evaluator.d.ts +0 -22
  178. package/dist/core/parser.d.ts +0 -21
  179. package/dist/core/selector-evaluator.d.ts +0 -15
  180. package/dist/core/template-literal-evaluator.d.ts +0 -5
  181. package/dist/expressions/comparison/index.d.ts +0 -80
  182. package/dist/expressions/comparison/utils.d.ts +0 -2
  183. package/dist/expressions/conversion/impl/bridge.d.ts +0 -117
  184. package/dist/expressions/logical/impl/pattern-matching.d.ts +0 -58
  185. package/dist/expressions/positional/impl/bridge.d.ts +0 -95
  186. package/dist/expressions/property/index.d.ts +0 -55
  187. package/dist/expressions/references/impl/bridge.d.ts +0 -54
  188. package/dist/extensions/index.d.ts +0 -3
  189. package/dist/extensions/tailwind.d.ts +0 -22
  190. package/dist/mod.d.ts +0 -63
  191. package/dist/parser/expression-parser.d.ts +0 -6
  192. package/dist/runtime/runtime-experimental.d.ts +0 -18
  193. package/dist/scripts/code-generator.d.ts +0 -64
  194. package/dist/scripts/generate-missing-commands.d.ts +0 -4
@@ -0,0 +1 @@
1
+ var hyperfixi=function(){"use strict";const t="then",e="else",n="end",r="and",s="for",i="while",o="until",a="forever",c="times",l="index",u="in",h="to",f="from",d="with",p="of",m="on",y="event",g="behavior",v="global",b="the",E="start",w=new Set(["add","append","async","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","for","get","go","halt","hide","open","if","increment","install","js","log","make","measure","morph","pick","process","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait"]),x=new Set(["put","trigger","send","remove","take","toggle","set","show","hide","add","halt","measure","js","tell","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"],N=new Set(["if","else","unless","for","while","until","end","and","or","not","in","to","from","into","with","without","as","matches","contains","then","on","when","every","init","def","behavior","the","of","first","last"]),C=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"]),T=new Set(["me","it","you","result","my","its","your"]),O=new Set(["and","or","not","no"]),$=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","ignoring case","sorted by","mapped to","split by","joined by"]),R=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 I;!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"}(I||(I={}));const j=new Set(["+","-","*","/","mod"]),D=new Set(["ms","s","seconds","minutes","hours","days"]);function M(t,e=1){const n=t.position+e;return t.input.length>n?t.input[n]:""}function P(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 B(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;P(t)}}function F(t,e,n,r,s){const i=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:i,end:o,line:V(t,i),column:a};t.tokens.push(c)}function V(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 _(t){const e=t.position;let n="";for(P(t),P(t);t.input.length>t.position&&"\n"!==t.input[t.position];)n+=P(t);F(t,I.COMMENT,"--"+n,e)}function q(t){const e=t.position,n=P(t);let r=n;for(;t.input.length>t.position;){const e=P(t);if(r+=e,e===n)break;"\\"===e&&t.input.length>t.position&&(r+=P(t))}F(t,I.STRING,r,e)}function H(t){const e=t.position;P(t);let n="";for(;t.input.length>t.position;){const e=t.input[t.position];if("`"===e){P(t);break}if("\\"===e){if(P(t),t.input.length>t.position){const e=P(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+=P(t)}if(t.position>=t.input.length&&!t.input.endsWith("`"))throw Error(`Unterminated template literal at line ${t.line}, column ${t.column-n.length}`);F(t,I.TEMPLATE,n,e)}function U(t){const e=t.position;let n=P(t);if(t.input.length>t.position&&"{"===t.input[t.position]){for(n+=P(t);t.input.length>t.position;){const e=t.input[t.position];if(n+=P(t),"}"===e)break}F(t,I.SELECTOR,n,e)}else{for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"-"!==e&&"_"!==e&&":"!==e)break;n+=P(t)}F(t,I.SELECTOR,n,e)}}function W(t){const e=t.position;let n="";for(n+=P(t);t.input.length-1>t.position;){const e=t.input[t.position],r=t.input[t.position+1];if(n+=P(t),"/"===e&&">"===r){n+=P(t);break}}F(t,I.SELECTOR,n,e)}function J(t){const e=t.position;let n=P(t);for(;t.input.length>t.position;){const e=t.input[t.position];if(!K(e)&&"_"!==e&&"-"!==e)break;n+=P(t)}F(t,I.SYMBOL,n,e)}function z(t){const e=t.position;let n="";const r=t.input[t.position];if(("'"===r||"'"===r)&&"s"===M(t,1))return n="'s",P(t),P(t),void F(t,I.OPERATOR,n,e);const s=t.input.substring(t.position,t.position+2),i=t.input.substring(t.position,t.position+3);["===","!=="].includes(i)?(n=i,P(t),P(t),P(t)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(n=s,P(t),P(t)):n=P(t),F(t,I.OPERATOR,n,e)}function Z(t){const e=t.position,n=t.input,r=n.length;let s="";for(;r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}if(r>t.position&&"."===n[t.position]&&(t.position+1>=r||"."!==n[t.position+1]))for(s+=P(t);r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(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]:"",i=r>t.position+2?n[t.position+2]:"";if(e>="0"&&"9">=e||!("+"!==e&&"-"!==e||"0">i||i>"9"))for(s+=P(t),"+"!==n[t.position]&&"-"!==n[t.position]||(s+=P(t));r>t.position;){const e=n[t.position];if("0">e||e>"9")break;s+=P(t)}}}const i=t.position;let o="";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z"))break;o+=P(t)}D.has(o)?F(t,I.TIME,s+o,e):(t.position=i,F(t,I.NUMBER,s,e))}function G(t){const e=t.position,n=t.input,r=n.length;let s="";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;s+=P(t)}const i=function(t,e,n){const r=e.toLowerCase(),s=t.position;if("'s"===e||"'s"===e)return 0;const i=t.tokens[t.tokens.length-1];if(i&&(i.kind===I.IDENTIFIER||i.kind===I.SELECTOR)){const e=t.input.length>t.position?t.input[t.position]:"";if("'"===e||"'"===e)return 0}B(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+=P(t)}if(o){const e=o.toLowerCase(),s=`${r} ${e}`,i=function(t,e,n,r){const s=e.toLowerCase(),i=n.toLowerCase();if("at"===s){const e=t.position;if("the"===i){B(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+=P(t)}const s=n.toLowerCase();if("start"===s||"end"===s){B(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+=P(t)}if("of"===e.toLowerCase())return F(t,I.IDENTIFIER,`at the ${s} of`,r),1}return t.position=e,0}if("start"===i||"end"===i){B(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+=P(t)}return"of"===n.toLowerCase()?(F(t,I.IDENTIFIER,`at ${i} of`,r),1):(t.position=e,0)}}return 0}(t,r,e,n);if(i)return 1;const a=function(t,e,n){const r=t.position;let s=`${e} ${n}`,i=t.position;const o=[e,n];for(;8>o.length&&(B(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+=P(t)}if(!e)break;o.push(e.toLowerCase());const n=o.join(" ");$.has(n)&&(s=n,i=t.position)}return $.has(s)&&s!==`${e} ${n}`?(t.position=i,s):(t.position=r,null)}(t,r,e);if(a)return F(t,I.OPERATOR,a,n),1;if($.has(s))return F(t,I.OPERATOR,s,n),1}return $.has(r)?(t.position=s,F(t,I.OPERATOR,e,n),1):(t.position=s,0)}(t,s,e);if(i)return;const o=function(t){const e=t.toLowerCase();return"include"===e||"includes"===e||O.has(e)||j.has(t)||j.has(e)||$.has(e)?I.OPERATOR:I.IDENTIFIER}(s);F(t,o,s,e)}function X(t){const e=t.position,n=t.input,r=n.length;P(t);let s="$";for(;r>t.position;){const e=n[t.position];if(("a">e||e>"z")&&("A">e||e>"Z")&&("0">e||e>"9")&&"_"!==e)break;s+=P(t)}F(t,I.IDENTIFIER,s,e)}function Y(t){return/[a-zA-Z]/.test(t)}function K(t){return/[a-zA-Z0-9]/.test(t)}function Q(t){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(K(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 tt(t){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(t)}const et=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}(),nt=et,rt=et,st=et,it=et,ot=(...t)=>{nt&&console.log("🔧",...t)},at=(...t)=>{rt&&console.log("🎯",...t)},ct=(...t)=>{st&&console.log("📝",...t)},lt=(...t)=>{it&&console.log("🚀",...t)};let ut=0,ht=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(ut=1,ht=window,console.log("%c[HyperFixi] Semantic debug auto-enabled via URL param","color: #667eea; font-weight: bold"))}catch{}let ft={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};class dt{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(dt.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),s=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 i=r.confidence>=this.confidenceThreshold&&!!r.command,o=!i&&r.confidence>0;if(ut){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:i,fallbackTriggered:o,command:r.command?.name,roles:Object.keys(e).length>0?e:void 0,errors:r.errors,timestamp:Date.now(),duration:s};!function(t){if(!ut)return;const e=t.semanticSuccess?"semantic":t.fallbackTriggered?"fallback":"traditional",n=Math.round(100*t.confidence),r=Math.round(100*t.threshold),s=t.semanticSuccess?"color: #4caf50; font-weight: bold":t.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${e.toUpperCase()} %c${t.input.substring(0,50)}${t.input.length>50?"...":""}`,s,"color: #888"),console.log(`Confidence: ${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,ft.totalParses++,n.semanticSuccess?ft.semanticSuccesses++:n.fallbackTriggered?ft.semanticFallbacks++:ft.traditionalParses++,ft.confidenceHistory.push(n.confidence),ft.confidenceHistory.length>100&&ft.confidenceHistory.shift(),ft.averageConfidence=ft.confidenceHistory.reduce((t,e)=>t+e,0)/ft.confidenceHistory.length}return i?{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=[],r={};for(const[t,s]of e.roles){const i=this.semanticValueToExpression(s);switch(t){case"patient":case"event":n.push(i);break;case"destination":"put"===e.name?r.into=i:"add"===e.name||"append"===e.name||"prepend"===e.name?r.to=i:r.on=i;break;case"source":"fetch"===e.name?n.push(i):r.from=i;break;case"quantity":r.by=i;break;case"duration":r.over=i;break;case"responseType":r.as=i;break;case"method":r.method=i;break;case"style":r.with=i;break;case"condition":r.when=i;break;default:r[t]=i}}return{type:"command",name:e.name,args:n,modifiers:Object.keys(r).length>0?r:void 0,isBlocking:0,start:0,end:0,line:1,column:0}}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 s=t.roles.get("patient");"for"==(r?r.value+"":"")&&s&&e.push({type:"identifier",name:"expression"===s.type&&s.raw||s.value+"",start:0,end:0,line:1,column:0});const i=t.roles.get("event");i&&e.push({type:"string",value:i.value+"",start:0,end:0,line:1,column:0});const o=t.roles.get("source");o&&e.push(this.semanticValueToExpression(o));const a=t.roles.get("quantity");a&&e.push(this.semanticValueToExpression(a));const c=t.roles.get("condition");return c&&(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)},s=()=>{const r=[];if(e++,n(),")"!==t[e])for(r.push(i()),n();","===t[e];)e++,n(),r.push(i()),n();return")"===t[e]&&e++,r},i=()=>{n();const i=r();if(!i)return{type:"identifier",name:t.trim(),start:0,end:0,line:1,column:0};let o={type:"identifier",name:i,start:0,end:0,line:1,column:0};for(;t.length>e;){n();const i=t[e];if("."===i){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("("!==i)break;o={type:"callExpression",callee:o,arguments:s(),start:0,end:0,line:1,column:0}}}return o};return i()}getLanguage(){return this.language}getConfidenceThreshold(){return this.confidenceThreshold}}dt.SKIP_SEMANTIC_COMMANDS=new Set(["swap","morph","js","tell"]);const pt=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),mt=new Set([")","]","}",","]);function yt(t,e){return{infix:{bp:[t,t+1],handler:e??((e,n,r)=>{const s=r.parseExpr(t+1);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}})}}}function gt(t,e){return{infix:{bp:[t+1,t],handler:(e,n,r)=>{const s=r.parseExpr(t);return{type:"binaryExpression",operator:n.value,left:e,right:s,start:e.start,end:s.end??n.end,line:e.line??n.line,column:e.column??n.column}}}}}function vt(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 bt(t){return(e,n,r)=>{const s=r.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${t?"not ":""}a/an', got: <end>`);let i=1;const o=r.peek();return o&&"!"===o.value&&(r.advance(),i=0),{type:"typeCheckExpression",value:e,typeName:s.value,nullOk:i,negated:t,start:e.start,end:s.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",yt(10)],["||",yt(10)],["and",yt(20)],["&&",yt(20)],["==",yt(30)],["!=",yt(30)],["<",yt(30)],[">",yt(30)],["<=",yt(30)],[">=",yt(30)],["is",yt(30)],["matches",yt(30)],["contains",yt(30)],["starts with",yt(30)],["ends with",yt(30)],["does not start with",yt(30)],["does not end with",yt(30)],["is between",yt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:0,start:t.start,end:i.end}})],["is not between",yt(30,(t,e,n)=>{const r=n.parseExpr(31),s=n.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));n.advance();const i=n.parseExpr(31);return{type:"betweenExpression",value:t,min:r,max:i,negated:1,start:t.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(t,e,n)=>(t.ignoringCase=1,t)}}],["where",yt(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",yt(28,(t,e,n)=>{const r=n.parseExpr(29);let s="asc";const i=n.peek();if(i&&"string"==typeof i.value){const t=i.value.toLowerCase();"asc"===t||"ascending"===t?(n.advance(),s="asc"):"desc"!==t&&"descending"!==t||(n.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:t,right:r,order:s,start:t.start,end:r.end}})],["mapped to",yt(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",yt(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",yt(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}})],["+",{...yt(40),...vt(80)}],["-",{...yt(40),...vt(80)}],["*",yt(50)],["/",yt(50)],["%",yt(50)],["mod",yt(50)],["^",gt(60)],["**",gt(60)],["as",yt(70,(t,e,n)=>{const r=n.parseExpr(71),s=n.peek();if(s&&":"===s.value&&r&&"identifier"===r.type){n.advance();const t=n.advance();t&&void 0!==t.value&&(r.name=`${r.name}:${t.value}`,r.end=t.end)}return{type:"asExpression",expression:t,targetType:r,start:t.start,end:r.end??e.end,line:t.line??e.line,column:t.column??e.column}})],["not",vt(80)],["!",vt(80)],["no",vt(80)]]),new Map([["===",yt(30)],["!==",yt(30)],["is not",yt(30)],["am",yt(30)],["is in",yt(30)],["is not in",yt(30)],["precedes",yt(30)],["does not precede",yt(30)],["follows",yt(30)],["does not follow",yt(30)],["is a",yt(30,bt(0))],["is an",yt(30,bt(0))],["is not a",yt(30,bt(1))],["is not an",yt(30,bt(1))],["has",yt(30)],["have",yt(30)],["match",yt(30)],["include",yt(30)],["includes",yt(30)],["equals",yt(30)],["does not contain",yt(30)],["does not include",yt(30)],["is equal to",yt(30)],["is not equal to",yt(30)],["is really equal to",yt(30)],["is not really equal to",yt(30)],["really equals",yt(30)],["is greater than",yt(30)],["is less than",yt(30)],["is greater than or equal to",yt(30)],["is less than or equal to",yt(30)],["in",yt(30)],["of",yt(30)],["really",yt(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",vt(80)]]),new Map([["=",gt(5)]])),wt=new Map,xt=new Map,kt=new Map,St=new Set,At=new Set,Nt=new Set,Ct=new Set;function Tt(t){return wt.get(t.toLowerCase())}function Ot(t,e){if(0!==At.size)for(const n of At)try{n(t,e)}catch(t){void 0!==console&&console.error("[hyperfixi] globalReadHook threw:",t)}}function $t(t,e,n){if(0!==Nt.size)for(const r of Nt)try{r(t,e,n)}catch(t){void 0!==console&&console.error("[hyperfixi] localWriteHook threw:",t)}}function Rt(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 Lt(t,e,n){if(t.globals.set(e,n),0!==St.size)for(const r of St)try{r(e,n,t)}catch(t){void 0!==console&&console.error("[hyperfixi] globalWriteHook threw:",t)}}function It(t){return t.kind!==I.IDENTIFIER?0:w.has(t.value.toLowerCase())}function jt(t){return t.kind!==I.IDENTIFIER?0:L.has(t.value.toLowerCase())}function Dt(t){return t.kind!==I.IDENTIFIER?0:R.has(t.value.toLowerCase())}function Mt(t){return t.kind!==I.IDENTIFIER?0:T.has(t.value.toLowerCase())}function Pt(t){return $.has(t.value.toLowerCase())}function Bt(t){return t.kind===I.IDENTIFIER}function Ft(t){return t.kind===I.SELECTOR}function Vt(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("<")}function _t(t){return t.kind===I.STRING||t.kind===I.NUMBER||t.kind===I.TEMPLATE}function qt(t){return t.kind===I.IDENTIFIER}function Ht(t){return t.kind===I.TIME}function Ut(t){return t.kind===I.SYMBOL}function Wt(t){return t.kind===I.COMMENT}function Jt(t){if(t.kind!==I.IDENTIFIER)return 0;const e=t.value.toLowerCase();return!(w.has(e)||L.has(e)||R.has(e)||T.has(e))}function zt(t){return t.kind===I.STRING}function Zt(t){return t.kind===I.NUMBER}function Gt(t){if(t.kind===I.IDENTIFIER){const e=t.value;return"true"===e||"false"===e||"null"===e||"undefined"===e}return 0}function Xt(t){return t.kind===I.TEMPLATE}function Yt(t){return t.kind===I.SELECTOR&&t.value.startsWith("<")}function Kt(t){return t.kind===I.SELECTOR&&t.value.startsWith("#")}function Qt(t){return t.kind===I.SELECTOR&&t.value.startsWith(".")}function te(t){return t.kind!==I.SELECTOR?0:!t.value.startsWith("#")&&!t.value.startsWith(".")}function ee(t){if(t.kind!==I.OPERATOR)return 0;const e=t.value.toLowerCase();return!O.has(e)&&!$.has(e)}function ne(t){const e=t.value.toLowerCase();return"then"===e||"and"===e||"else"===e||"end"===e||"on"===e}function re(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 ie(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 oe(t,e){return{type:"block",commands:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ae(t,e){return{type:"string",value:t,start:e.start,end:e.end,line:e.line,column:e.column}}function ce(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 ue(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 fe=[{command:"append",keywords:["to"],syntax:"append <value> [to <target>]"},{command:"make",keywords:["a","an"],syntax:"make (a|an) <type>"},{command:"send",keywords:["to"],syntax:"send <event> to <target>"},{command:"throw",keywords:[],syntax:"throw <error>"}];function de(t,e){return t?e.some(e=>t.value===e||t.value.toLowerCase()===e):0}const pe=[t,r,e,n];function me(t,e=[]){if(t.isAtEnd())return 1;for(const e of pe)if(t.check(e))return 1;for(const n of e)if(t.check(n))return 1;return t.checkIsCommand()?1:0}function ye(t,e=[]){if(!me(t,e))return t.parseExpression()}function ge(t,e,n){return t.check(e)?(t.advance(),n.push(t.createIdentifier(e)),1):0}function ve(t,e,n){for(const r of e)if(t.check(r))return t.advance(),n.push(t.createIdentifier(r)),r;return null}function be(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 we{constructor(t){this.args=[],this.isBlocking=0,this.name=t}static from(t){const e=new we(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 we(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 we(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 we(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 xe(t,e){const n=[];let r="";const s=t.peek().start||0,i=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:s,end:t.getPosition().end,line:i,column:o})}else n.push({type:"string",value:r,start:s,end:t.getPosition().end,line:i,column:o})}const a=[...n];for(;!me(t);){if(t.check("on")||t.check("to")){const e=t.advance().value;a.push(t.createIdentifier(e));continue}a.push(t.parsePrimary())}return we.fromIdentifier(e).withArgs(...a).endingAt(t.getPosition()).build()}function ke(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 we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Se(r,s){const i=[];let o=0;const a=r.savePosition();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;r.advance()}r.restorePosition(a);let c=0;if(!o){const t=r.savePosition(),i=s.line,o=100;for(;!r.isAtEnd()&&o>r.current-t;){const t=r.peek(),s=t.value?.toLowerCase();if(s===g||"def"===s||s===m)break;if(s===e||s===n){t.line===i&&(c=1);break}if((r.checkIsCommand()||r.isCommand(s))&&void 0!==t.line&&t.line!==i){c=1;break}r.advance()}r.restorePosition(t)}const l=o||c;let u;if(l)u=r.parseExpression();else{const e=[],n=20;let i=0;for(;!r.isAtEnd()&&!r.checkIsCommand()&&!r.isCommand(r.peek().value)&&!r.check(t)&&n>i;){const t=r.savePosition();e.push(r.parseLogicalAnd()),r.savePosition()===t&&r.advance(),i++}if(0===e.length)throw Error("Expected condition after if/unless");u=1===e.length?e[0]:{type:"expression",tokens:e,start:e[0].start,end:e[e.length-1].end,line:s.line,column:s.column}}if(i.push(u),l){o&&r.advance();const t=[];for(;!r.isAtEnd()&&!r.check(e)&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}if(0===t.length&&r.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");i.push(oe(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}));let a=0;if(r.check(e))if(r.advance(),r.check("if")){const t=r.peek();r.advance();const e=Se(r,t);i.push(oe([e],{start:t.start,end:r.getPosition().end,line:t.line,column:t.column})),a=1}else{const t=[];for(;!r.isAtEnd()&&!r.check(n)&&(r.checkIsCommand()||r.isCommand(r.peek().value));){r.advance();const e=r.parseCommand();e&&t.push(e)}i.push(oe(t,{start:s.start,end:r.getPosition().end,line:s.line,column:s.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();i.push(oe([t],{start:s.start,end:r.getPosition().end,line:s.line,column:s.column}))}}return we.from(s).withArgs(...i).endingAt(r.getPosition()).build()}function Ae(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 s=we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}function Ne(t,e){const n=[],r=ye(t,[f]);r&&n.push(r),ge(t,f,n);const s=ye(t);return s&&n.push(s),we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Ce(t,e){const n=[];if(t.check("between")){t.advance(),n.push(t.createIdentifier("between"));const i=ye(t,[r]);i&&n.push(i),ge(t,r,n);const o=ye(t,[f,m,s]);if(o&&n.push(o),ve(t,[f,m],n)){const e=ye(t);e&&n.push(e)}return we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}const i=ye(t,[f,m]);if(i&&n.push(i),ve(t,[f,m],n)){const e=ye(t);e&&n.push(e)}return we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Te(t,e){const r=t.parseExpression();if(!r)return t.addError("Put command requires content expression"),null;const s=t.peek();if(!s||!A.includes(s.value))return t.addError(`Expected operation keyword (${A.join(", ")}) after put expression, got: ${s?.value}`),null;let i=t.advance().value;const o=i.toLowerCase();"at start of"===o||"at the start of"===o?i=k:"at end of"===o||"at the end of"===o?i=S:"at"===i&&(t.check(E)||t.check(b)?(be(t,b),t.check(E)&&(t.advance(),t.check(p)&&(t.advance(),i=k))):t.check(n)&&(t.advance(),t.check(p)&&(t.advance(),i=S)));const a=t.parseExpression();return a?we.fromIdentifier(e).withArgs(r,t.createIdentifier(i),a).endingAt(t.getPosition()).build():(t.addError("Put command requires target expression after operation keyword"),null)}const Oe=["innerhtml","outerhtml","into","over","delete","morph","morphouter"];function $e(s,i){const o=s.savePosition();let a=null,c=[];try{a=function(t){if(!t.check(":"))return null;if(t.advance(),t.check(":")){t.advance();const e=t.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end}}const e=t.advance();return{type:"identifier",name:e.value,scope:"local",start:e.start-1,end:e.end}}(s)??function(t){if(!t.check(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}}(s)??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 ue(t,e,{start:t.start??0,end:e.end??0,line:t.line??1,column:t.column??1})}return t.check(h)?n:(t.restorePosition(e),null)}(s),a||(a=s.parseExpression())}catch{s.restorePosition(o),a=null}if(!a){const i=function(s){if(s.match(":")){const t=s.advance();return{expression:{type:"identifier",name:t.value,scope:"local",start:t.start,end:t.end},tokens:[]}}const i=[];for(;!(s.isAtEnd()||s.check(h)||s.check(t)||s.check(r)||s.check(e)||s.check(n));)i.push(s.parsePrimary());if(0===i.length)return{expression:null,tokens:[]};if(i.length>=4){const t=(t,e)=>t[e];if(t(i[0],"value")===b&&t(i[2],"value")===p){const e=i[1],n=i[3];return{expression:ue(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:i[0].start??0,end:n.end??0,line:i[0].line??1,column:i[0].column??1}),tokens:[]}}}return 1===i.length?{expression:i[0],tokens:[]}:{expression:null,tokens:i}}(s);a=i.expression,c=i.tokens}if(!s.check(h)){const t=s.isAtEnd()?"end of input":s.peek().value;throw Error("Expected 'to' in set command, found: "+t)}s.advance();const l=s.parseExpression()??s.parsePrimary(),u=[];return a?u.push(a):c.length>0&&u.push(...c),u.push(s.createIdentifier(h)),l&&u.push(l),we.fromIdentifier(i).withArgs(...u).endingAt(s.getPosition()).build()}function Re(t,e){const n=[];for(;!me(t,["catch","finally"])&&(t.checkIdentifierLike()||t.checkSelector()||t.checkLiteral()||t.checkTimeExpression()||t.match("<"));)n.push(t.parsePrimary());return we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}function Le(t){if(t.isAtEnd())return 1;const e=t.peek().value;return["as","with","{","then","end","else","otherwise",")"].includes(e)||me(t)}function Ie(t){if(t.check("{"))return 0;if(!t.checkIdentifierLike())return 0;const e=t.peekAt(1);return null!==e&&":"===e.value}function je(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 s=t.parsePrimary();s&&e.push({key:r,value:s})}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}}class De{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 dt({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}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&&Tt(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("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?Tt(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")){ct("✅ PARSER: Found event handlers after command sequence, parsing as program");const e=[t];ct(`✅ PARSER: Starting with ${e.length} statement(s) from command sequence`);let n=0;for(;!this.isAtEnd()&&this.check("on");){ct(`✅ PARSER: Parsing event handler #${n+1}, current token: ${this.peek().value}`),this.advance();const t=this.parseEventHandler();if(ct("✅ PARSER: parseEventHandler returned:",t?`type=${t.type}, event=${t.event}`:"null"),t&&(e.push(t),n++,ct(`✅ PARSER: Added event handler, now have ${e.length} statements total`)),ct(`✅ 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 ct("⚠️ 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};ct("✅ PARSER: No more event handlers, at end of input");break}}return ct(`✅ 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(),s=De.PRATT_TABLE.get(r.value);let i;if(s?.prefix){const t=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${t.value}' operator`),this.createErrorNode();i=s.prefix.handler(t,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const e=this.peek(),n=De.PRATT_TABLE.get(e.value);if(!n?.infix){if(pt.has(e.value)||mt.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){ct("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}`),i}if("*"===e.value||"/"===e.value||"%"===e.value){const t=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(t&&("*"===t.value||"/"===t.value||"%"===t.value||"+"===t.value||"-"===t.value))return this.addError("*"===e.value&&"*"===t.value?"Unexpected token: "+t.value:`Invalid operator combination: ${e.value}${t.value}`),i}const s=this.advance();if(this.isAtEnd()&&!De.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=n.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(e,{node:i,endPos:this.current}),i}makePrattContext(){const t=this;return{peek:()=>t.tokens.length>t.current?t.tokens[t.current]:void 0,advance:()=>{const e=t.tokens[t.current];return t.current++,e},parseExpr:e=>t.parseExpressionPratt(e),isStopToken:()=>{const e=t.tokens[t.current];return e?pt.has(e.value)||mt.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=>w.has(t.toLowerCase()))(t)}isKeyword(t){return this.keywordResolver?this.keywordResolver.isKeyword(t):(t=>N.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,i){switch(i.name.toLowerCase()){case"put":return Te(s,i);case"trigger":case"send":return xe(s,i);case"remove":return Ne(s,i);case"toggle":return Ce(s,i);case"set":return $e(s,i);case"halt":return ke(s,i);case"measure":return Ae(s,i);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 s=t.peek().start,i=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&&"’"!==t&&"‘"!==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,s);for(;!t.isAtEnd()&&!t.check(n)&&t.peek().start<i;)t.advance();t.consume(n,"Expected end after js code body");const o={type:"literal",value:t.getInputSlice(s,i).trim(),start:e.start,end:t.getPosition().end},a={type:"arrayLiteral",elements:r.map(t=>({type:"literal",value:t,start:e.start,end:e.end})),start:e.start,end:t.getPosition().end};return we.fromIdentifier(e).withArgs(o,a).endingAt(t.getPosition()).build()}(s,i);case"tell":return function(s,i){const o=s.parseExpression();if(!o)throw Error("tell command requires a target expression");const a=[];for(;!s.isAtEnd();){if(s.checkIsCommand()){try{s.advance();const t=s.parseCommand();if(!t)break;a.push(t)}catch{break}if(s.match(r))continue;if(s.check(t)||s.check(e)||s.check(n))break;if(s.checkIsCommand())continue;break}break}if(0===a.length)throw Error("tell command requires at least one command after the target");return we.fromIdentifier(i).withArgs(o,...a).endingAt(s.getPosition()).build()}(s,i);case"pick":return function(t,e){const n=we.fromIdentifier(e);be(t,b);const r=t.peek().value,s=t=>({type:"literal",value:t,start:e.start,end:e.end}),i=()=>{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=i();return n.withArgs(r).withModifier("variant",s("first")).withModifier("count",e).endingAt(t.getPosition()).build()}if("last"===r){t.advance();const e=t.parsePrimary(),r=i();return n.withArgs(r).withModifier("variant",s("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=i(),o=n.withArgs(r).withModifier("variant",s("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")?s("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=i(),l=n.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",e).withModifier("rangeMode",s(a));return o?l.withModifier("rangeEnd",s("end")):r&&l.withModifier("rangeEnd",r),l.endingAt(t.getPosition()).build()}if("match"===r||"matches"===r){t.advance(),t.match("of");const e=t.parsePrimary();let o;t.matchOperator("|")&&(o=t.advance().value);const a=i(),c=n.withArgs(a).withModifier("variant",s("match"===r?"match":"matches")).withModifier("regex",e);return o&&c.withModifier("flags",s(o)),c.endingAt(t.getPosition()).build()}return Re(t,e)}(s,i);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();return we.fromIdentifier(e).withArgs(...r).withModifiers(n).endingAt(t.getPosition()).build()}(s,i);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 s=e.value.toLowerCase();Oe.includes(s)&&(r=s,t.advance(),n.push(t.createIdentifier(r)))}}if("delete"===r){const r=t.parseExpression();return r&&n.push(r),we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}!t.isAtEnd()&&t.check(p)&&(t.advance(),n.push(t.createIdentifier("of")));const s=t.parseExpression();if(s&&n.push(s),!t.isAtEnd()&&t.check(d)){t.advance(),n.push(t.createIdentifier("with"));const e=t.parseExpression();e&&n.push(e)}return we.fromIdentifier(e).withArgs(...n).endingAt(t.getPosition()).build()}(s,i);default:return Re(s,i)}}(this.getContext(),s)}parsePutCommand(t){return Te(this.getContext(),t)}parseSetCommand(t){return $e(this.getContext(),t)}parseHaltCommand(t){return ke(this.getContext(),t)}parseMeasureCommand(t){return Ae(this.getContext(),t)}parseTriggerCommand(t){return xe(this.getContext(),t)}parseCommandListUntilTerminator(t){const e=[],n=()=>this.check("end")||t.some(t=>this.check(t));for(ct("🔄 parseCommandListUntilTerminator: Starting (extraStops:",t.join(","),")");!this.isAtEnd()&&!n();){ct("📍 Loop iteration, current token:",this.peek().value,"kind:",this.peek().kind);let t=0;const r=this.checkIsCommand(),s=!r&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(r||s){ct(r?"✅ Found COMMAND token:":"✅ Found IDENTIFIER that is a command:",this.peek().value),this.advance();const n=this.error;try{const r=this.parseCommand();this.error&&this.error!==n&&(ct("⚠️ parseCommandListUntilTerminator: Command parsing added error, restoring. Error was:",this.error.message),this.error=n),r&&(ct("✅ Parsed command:",r.name),e.push(r),t=1)}catch(t){ct("⚠️ parseCommandListUntilTerminator: Command parsing threw, restoring:",t instanceof Error?t.message:t+""),this.error=n}}else this.checkIdentifier()&&ct("❌ IDENTIFIER is not a command:",this.peek().value);if(!t){ct("❌ No command parsed, breaking. Current token:",this.peek().value);break}for(ct("📍 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(","));)ct("⚠️ Skipping unexpected token:",this.peek().value),this.advance();if(this.match("then","and",","))ct("✅ Found separator, continuing");else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value)){ct("📍 No separator and no command, breaking. Current token:",this.peek().value);break}ct("✅ 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=""),ct("✅ parseCommandListUntilTerminator: parsed",e.length,"commands (terminator:",r,")"),{commands:e,terminator:r}}parseCommandListUntilEnd(){const{commands:t}=this.parseCommandListUntilTerminator([]);if(ct('🔍 After loop, checking for "end". Current token:',this.peek().value),!this.check("end"))throw ct('❌ ERROR: Expected "end" but got:',this.peek().value,"at position:",this.peek().start),Error('Expected "end" to close repeat block');return ct('✅ Found "end", consuming it'),this.advance(),t}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",h=null,p=null,m=null,g=null,v=null,E=null;if(t.check(s)){t.advance(),r=s;const e=t.peek();Bt(e)&&(v=e.value,t.advance()),t.check(u)&&(t.advance(),g=t.parseExpression())}else if(t.check(u))t.advance(),r=s,v="it",g=t.parseExpression();else if(t.check(i))t.advance(),r=i,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(ct("📍 Parsing event name, current token:",{value:e.value,kind:e.kind}),!Bt(e)&&!Dt(e))throw Error('Expected event name after "event"');if(h=e.value,t.advance(),ct("✅ Got event name:",h,"Next token:",t.peek().value),ct('🔍 Checking for "from", current token:',t.peek().value),t.check(f)){ct('✅ Found "from", advancing...'),t.advance(),ct('📍 After consuming "from", current token:',t.peek().value),be(t,b)&&ct('✅ Found "the", advancing...');const e=t.peek();ct("🔍 Before parsePrimary for event target:",{value:e.value,kind:e.kind,position:e.start}),p=t.parsePrimary(),ct("✅ After parsePrimary, eventTarget:",p)}else ct('❌ No "from" found, skipping target parsing')}else m=t.parseExpression();else t.check(a)?(t.advance(),r=a):(E=t.parseExpression(),t.check(c)&&(t.advance(),r=c));let w,x=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),x=l)}else if(t.check(l)){t.advance();const e=t.peek();Bt(e)?(x=e.value,t.advance()):x=l}let k=null,S=0;if(r===a){const e=t.parseRepeatBody();if(w=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();w=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(ae(v,A)),g&&n.push(g),m&&n.push(m),E&&n.push(E),h&&n.push(ae(h,A)),p&&n.push(p),x&&n.push(ae(x,A)),n.push(oe(w,{...A,end:A.end||0})),null!==k&&n.push(oe(k,{...A,end:A.end||0}));const N=we.from(e).withArgs(...n);return S&&N.withModifier("bottomTested",{type:"literal",value:1,...A}),N.endingAt(t.getPosition()).build()}(this.getContext(),t)}parseForCommand(t){return function(t,e){const n=[];let r=null,s=null;t.check("each")&&t.advance();const i=t.peek();if(!Bt(i))throw Error('Expected variable name after "for"');if(r=i.value,t.advance(),!t.check(u))throw Error('Expected "in" after variable name in for loop');if(t.advance(),s=t.parseExpression(),!s)throw Error('Expected collection expression after "in"');let o=null;if(t.check(d)){const e=t.peekAt(1);e&&e.value.toLowerCase()===l&&(t.advance(),t.advance(),o=l)}else if(t.check(l)){t.advance();const e=t.peek();Bt(e)?(o=e.value,t.advance()):o=l}const a=t.parseCommandListUntilEnd();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(ae(r,c)),n.push(s),o&&n.push(ae(o,c)),n.push(oe(a,{...c,end:c.end||0})),we.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")&&!me(t)){const r=t.parseExpression();return n.push(r),we.from(e).withArgs(...n).blocking().endingAt(t.getPosition()).build()}if(t.check("for")){t.advance();const r=[];do{const e=t.peek();if(!Bt(e))throw Error('Expected event name after "for"');const n=e.value;t.advance();const s=[];if(t.check("(")){for(t.advance();!t.isAtEnd()&&!t.check(")");){const e=t.peek();if(!Bt(e))break;s.push(e.value),t.advance(),t.check(",")&&t.advance()}if(!t.check(")"))throw Error('Expected ")" after event parameters');t.advance()}if(r.push({name:n,params:s}),!t.check("or"))break;t.advance()}while(!t.isAtEnd());let s=null;t.check(f)&&(t.advance(),be(t,b),s=t.parsePrimary());const i={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(le(r.map(t=>ce([{key:se("name",i),value:re(t.name,`"${t.name}"`,i)},{key:se("args",i),value:le(t.params.map(t=>re(t,`"${t}"`,i)),i)}],i)),i)),s&&n.push(s)}return we.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,s=t.previous();if(n.push(se(r,{start:s.start,end:s.end,line:s.line,column:s.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 s={start:e.start,end:t.getPosition().end,line:e.line,column:e.column};n.push(ce(r.map(t=>({key:t.name?se(t.name,s):re("_positional","_positional",s),value:t.value})),s))}}return we.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseTransitionCommand(t){return function(t,e){const n=[],r={};let s=null;const i=t.peek();if(Bt(i)||"*"===i.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,s={type:"string",value:e,start:i.start||0,end:t.getPosition().end,line:i.line,column:i.column})}if(!s)throw Error("Transition command requires a CSS property");if(n.push(s),!t.check(h))throw Error('Expected "to" keyword after property in transition command');t.advance();const o=t.parsePrimary();if(r.to=o,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 we.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=ye(t,[h]);e&&n.push(e)}if(t.check(h)){t.advance();const e=ye(t);e&&n.push(e)}return we.from(e).withArgs(...n).endingAt(t.getPosition()).build()}(this.getContext(),t)}parseIfCommand(t){return Se(this.getContext(),t)}parseRemoveCommand(t){return Ne(this.getContext(),t)}parseToggleCommand(t){return Ce(this.getContext(),t)}parseRegularCommand(t){return Re(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):e=Ut(this.peek())&&this.peek().value.startsWith("@")?this.advance().value:this.consumeIdentifier("Expected property name after possessive").value,t=this.createPossessiveExpression(t,this.createIdentifier(e))}}return t}parsePrimary(){if(this.check("*")){const t=this.current;if(this.advance(),!this.isAtEnd()&&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.slice(1,-2).trim(),e=this.createSelector(t);return e.fromQuery=1,e}if(this.matchSelector())return this.createSelector(this.previous().value);if(this.match("<"))return this.parseHyperscriptSelector();if(this.match("(")){if(this.isAtEnd())return this.addError("Expected expression inside parentheses"),this.createErrorNode();const t=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),t}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const t=this.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end,line:t.line,column:t.column}}{const t=this.advance();return{type:"identifier",name:t.value,scope:"local",start:t.start-1,end:t.end,line:t.line,column:t.column}}}if(this.matchBasicOperator()){const t=this.previous();return this.createIdentifier(t.value)}const t=this.peek();if((!t||"end"!==t.value&&"else"!==t.value&&"then"!==t.value)&&(this.matchPredicate(Jt)||this.matchPredicate(jt)||this.matchPredicate(Mt)||this.matchPredicate(It)||this.matchPredicate(Dt))){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(Ut(this.peek())&&this.peek().value.startsWith("@")){const t=this.advance();return{type:"attributeAccess",attributeName:t.value.substring(1),start:t.start,end:t.end,line:t.line,column:t.column}}const e=this.peek();return this.addError(`Unexpected token: ${e.value} at line ${e.line}, column ${e.column}`),this.advance(),this.createErrorNode()}parseDollarExpression(){if(this.checkNumber()){const t=this.advance().value;return this.createLiteral(t,"$"+t)}if(this.checkIdentifier()){const t=this.advance();let e=this.createIdentifier(t.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const t=this.advance();e=this.createMemberExpression(e,this.createIdentifier(t.value),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.matchPredicate(Jt))e=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected property name in object literal"),this.createErrorNode();{const t=this.previous().value,n=t.slice(1,-1);e=this.createLiteral(n,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(Jt))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 s=0,i=0;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const t=this.advance();r.push(t.value),"$"===t.value&&this.check("{")&&(s=1),"{"===t.value&&i++,"}"===t.value&&i--}const o=r.join(""),a=s?{type:"templateLiteral",value:o,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}:this.createLiteral(o,o);if(e.push({key:n,value:a}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseConstructorCall(){const t=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const e=this.advance(),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"]);let s,i,o;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(s=this.advance().value),i=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),o=this.parseCommandBlock(["end"])),this.consume("end","Expected 'end' after function definition"),{type:"def",name:e,params:n,body:r,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==o&&{finallyHandler:o},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseEventNameWithNamespace(t){let e;e=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(t);let 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,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:t,raw:`"${t}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:e.arguments,raw:JSON.stringify(e.arguments)}},...n?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:n,raw:`"${n}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:r}]}],isBlocking:0,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(t,e){const n=t.callee.name,r=this.peek();if(!(De.PSEUDO_COMMAND_PREPOSITIONS.includes(r.value.toLowerCase())||Jt(r)&&!this.isCommand(r.value)||Mt(r)))return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:0};let s,i;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}}),De.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(t,e),isPseudo:0,targetFailed:1}}return{node:this.createPseudoCommandNode(n,t,s,i,e),isPseudo:1,targetFailed:0}}parseCommandWithErrorRecovery(){this.advance();const t=this.error;try{const e=this.parseCommand();return this.error&&this.error!==t&&(ct("⚠️ Command parsing added error, restoring error state. Error was:",this.error.message),this.error=t),e}catch(e){return ct("⚠️ Command parsing threw exception, restoring error state:",e instanceof Error?e.message:e+""),this.error=t,null}}parseEventHandler(){ct("🔧 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,ct("🔧 parseEventHandler: Parsed 'first' as .once alias"))}const n=this.parseEventNameWithNamespace("Expected event name after 'on'");for(t.push(n),ct("🔧 parseEventHandler: Parsed first event name: "+n);this.check("or");){this.advance(),ct("🔧 parseEventHandler: Found 'or', parsing additional event name");const e=this.parseEventNameWithNamespace("Expected event name after 'or'");t.push(e),ct("🔧 parseEventHandler: Parsed additional event name: "+e)}let r;if(ct("🔧 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,ct(`🔧 parseEventHandler: Detected custom event source '${r}' for event '${e}'`)}}const s=[];if(this.match("(")){if(!this.check(")"))do{const t=this.advance();s.push(t.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),ct("🔧 parseEventHandler: Parsed event parameters: "+s.join(", "))}const i={};for(;this.check(".");){this.advance();const t=this.advance().value.toLowerCase();if("once"===t)i.once=1,ct("🔧 parseEventHandler: Parsed modifier '.once'");else if("prevent"===t)i.prevent=1,ct("🔧 parseEventHandler: Parsed modifier '.prevent'");else if("stop"===t)i.stop=1,ct("🔧 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?(i.debounce=n,ct(`🔧 parseEventHandler: Parsed modifier '.debounce(${n})'`)):(i.throttle=n,ct(`🔧 parseEventHandler: Parsed modifier '.throttle(${n})'`)),this.consume(")",`Expected ')' after ${t} delay`)}}else ct(`🔧 parseEventHandler: Warning - unknown modifier '.${t}'`)}if(this.check("debounced")||this.check("throttled")){const t=this.advance().value.toLowerCase(),e="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const n=this.advance(),r=(o=n.value).endsWith("ms")?parseInt(o,10):o.endsWith("seconds")||o.endsWith("s")?1e3*parseFloat(o):o.endsWith("minutes")?6e4*parseFloat(o):o.endsWith("hours")?36e5*parseFloat(o):o.endsWith("days")?864e5*parseFloat(o):parseInt(o,10);i[e]=r,ct(`🔧 parseEventHandler: Parsed '${t} at ${n.value}' (${r}ms)`)}else if(this.matchNumber()){const n=parseInt(this.previous().value,10);i[e]=n,ct(`🔧 parseEventHandler: Parsed '${t} at ${n}'`)}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`)}var o;let a,c,l,u;if(e&&(i.once=1),Object.keys(i).length>0&&ct("🔧 parseEventHandler: Parsed modifiers:",i),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const t=this.advance();c=t.value,ct(`🔧 parseEventHandler: Parsed 'from' target: ${c} (kind: ${t.kind})`)}if(this.match("of")){const t=this.advance();l=t.value.startsWith("@")?t.value.substring(1):t.value,ct("🔧 parseEventHandler: Parsed attribute name: "+l)}this.match("in")&&(ct("🔧 parseEventHandler: Found 'in' keyword, parsing watch target"),u=this.parseExpression(),ct("🔧 parseEventHandler: Parsed watch target expression"));const h=[];for(ct(`✅ parseEventHandler: About to parse commands, current token: ${this.isAtEnd()?"END":this.peek().value}, isAtEnd: ${this.isAtEnd()}`);!this.isAtEnd();){if(ct(`✅ parseEventHandler: Loop iteration, current token: ${this.peek().value}, kind: ${this.peek().kind}`),this.check("on")){ct("✅ parseEventHandler: Stopping command parsing, found next event handler 'on'");break}if(this.checkComment())ct("✅ parseEventHandler: Skipping comment token: "+this.peek().value),this.advance();else{if(this.check("end")){ct("✅ parseEventHandler: Stopping command parsing, found 'end' keyword"),this.advance();break}if(this.checkIsCommand()){const t="("===this.tokens[this.current+1]?.value,e=this.peek().value.toLowerCase();if(t&&"js"!==e&&"tell"!==e){let t;const e=this.error;try{t=this.parseExpression()}catch(t){this.error=e,this.advance();const n=this.parseCommand();h.push(n);continue}if(t&&"callExpression"===t.type){const e=this.tryParsePseudoCommand(t,t);if(h.push(e.node),e.isPseudo||e.targetFailed)continue}}else{const t=this.parseCommandWithErrorRecovery();t&&(h.push(t),ct("✅ 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&&h.push(t)}else{let t;const e=this.error;try{t=this.parseExpression()}catch(t){ct("⚠️ 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(h.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}};h.push(n)}}}}}}for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on"));)this.advance();if(!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}}const f=this.getPosition(),d={type:"eventHandler",event:1===t.length?t[0]:t.join("|"),events:t,commands:h,...s.length>0&&{params:s},...a&&{condition:a},...c&&{target:c},...l&&{attributeName:l},...u&&{watchTarget:u},...r&&{customEventSource:r},...Object.keys(i).length>0&&{modifiers:i},start:f.start,end:f.end,line:f.line,column:f.column};return ct(`🔧 parseEventHandler: Created node with events: ${t.join(", ")}, attributeName: ${l||"none"}, watchTarget: ${u?"yes":"none"}`),d}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),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const t=this.getPosition(),e=this.parseEventNameWithNamespace("Expected event name after 'on'"),n=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const t=this.peek();Jt(t)?(n.push(t.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const t=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const e=this.peek(),n=r.has(e.value);this.checkIsCommand()&&!n||(t.push(e.value),i=e.value,this.advance())}}const o={type:"eventHandler",event:e,commands:this.parseCommandListUntilEnd(),...void 0!==i&&{target:i},...n.length>0&&{args:n},start:t.start,end:this.getPosition().end,line:t.line,column:t.column};s.push(o)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:this.parseCommandBlock(["end"]),start:t.start,end:this.getPosition().end,line:t.line,column:t.column},this.consume("end","Expected 'end' after init block")}return this.consume("end","Expected 'end' to close behavior definition"),{type:"behavior",name:e,parameters:n,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCommandSequence(){const t=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const e=this.error,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")||(ct("⚠️ 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"));)ct("⚠️ parseCommandSequence: Skipping unexpected token:",this.peek().value),this.advance();if(this.check("on")){ct('✅ 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 s=he(n,r,e.value);if(t.push(s),this.synchronizeToCommandBoundary(),this.isAtEnd())break;if(this.match("then"))continue;if(this.check("end")||this.check("on"))break;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}}return 1===t.length?t[0]:function(t){return{type:"CommandSequence",commands:t,start:t[0]?.start||0,end:t[t.length-1]?.end||0,line:t[0]?.line||1,column:t[0]?.column||1}}(t)}getMultiWordPattern(t){return function(t){return fe.find(e=>e.command===t.toLowerCase())||null}(t)}isTokenKeyword(t,e){return de(t,e)}parseMultiWordCommand(t,e){return function(t,e,n){const r=t.getMultiWordPattern(n);if(!r)return null;const s=[],i={};for(;!me(t,["catch","finally",...r.keywords])&&!de(t.peek(),r.keywords);){const e=t.parsePrimary();if(!e)break;if(s.push(e),!t.match(",")&&de(t.peek(),r.keywords))break}for(;!t.isAtEnd()&&de(t.peek(),r.keywords);){const e=t.advance().value,n=t.parseExpression();if(n&&(i[e]=n),!de(t.peek(),r.keywords))break}const o=we.from(e).withArgs(...s).endingAt(t.getPosition());return Object.keys(i).length>0&&o.withModifiers(i),o.build()}(this.getContext(),t,e)}parseCommandBlock(t){const e=[];for(;!this.isAtEnd()&&!t.some(t=>this.check(t));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const t=this.parseCommand();e.push(t)}}return e}trySemanticParse(t){if(!this.semanticAdapter||!this.semanticAdapter.isAvailable())return null;try{const e=this.semanticAdapter.trySemanticParse(t);return e.success&&e.node?(ct(`[Semantic] Successfully parsed with confidence ${e.confidence}:`,e.node.name),e.node):(ct(`[Semantic] Low confidence (${e.confidence}), falling back to traditional parser`),null)}catch(t){return ct("[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(It(e))break;this.advance()}}parseCommand(){const t=this.previous();let e=t.value;if(this.semanticAdapter&&!["install","wait","repeat","for","set","put","increment","decrement","add","toggle","if","unless","make","measure","trigger","halt","remove","exit","return","closest","js","tell"].includes(e.toLowerCase())){const t=this.getRemainingInput(),e=this.trySemanticParse(t);if(e)return this.skipToCommandBoundary(),e}if("beep"===e&&this.check("!")&&(this.advance(),e="beep!"),"fetch"===e)return function(t,e){const n={};let r=null;if(!t.isAtEnd()&&t.check("/")&&(r=function(t){const e=t.savePosition();let n="";for(;!t.isAtEnd()&&!Le(t);)n+=t.advance().value;return n&&"/"!==n?{type:"literal",value:n,raw:n,start:e,end:t.savePosition()}:(t.restorePosition(e),null)}(t)),r||(r=t.parsePrimary()),!r)return t.addError("fetch requires a URL"),we.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=Ie(t)?je(t):t.parsePrimary()}else t.advance(),t.isAtEnd()||be(t,"a")||be(t,"an"),n.as=t.parsePrimary();const s=we.from(e).withArgs(r).endingAt(t.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.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 s=[];if(("increment"===e||"decrement"===e)&&!this.isAtEnd())return function(t,e){const n=e.value,r="increment"===n?"+":"-";let s=0;t.check(v)&&(s=1,t.advance());const i=t.parseExpression();if(!i)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=re(1,"1",{start:e.start,end:t.previous().end,line:e.line,column:e.column});let a=i;s&&"identifier"===i.type&&(a={...i,scope:"global"});const c={start:e.start,end:t.previous().end,line:e.line,column:e.column},l=ie(r,i,o,c),u=[a,se(h,c),l];return we.from(e).withName("set").withArgs(...u).withOriginalCommand(n).endingAt({end:t.previous().end}).build()}(this.getContext(),t);for(;!(this.isAtEnd()||this.check("then")||this.check("and")||this.check("else")||this.check("end")||this.checkIsCommand());){const t=this.parseExpression();if(s.push(t||this.parsePrimary()),this.match(","))continue;const e=["into","from","to","with","by","at","before","after","over"];if(e.some(t=>this.check(t)))continue;const n=s[s.length-1];if(!n||"identifier"!==n.type&&"keyword"!==n.type||!e.includes(n.name??n.value))break}const i=this.getPosition();return{type:"command",name:e,args:s,isBlocking:0,start:i.start,end:i.end,line:i.line,column:i.column}}parseConditional(){const t=this.parseExpression();this.consume("then","Expected 'then' after if condition");const e=this.parseConditionalBranch();let 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())}return this.createCallExpression(this.createIdentifier(t),e)}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const t=this.peek(),e=t.value;return["first","last","next","previous","random","closest"].includes(e)?(this.advance(),this.parseNavigationFunction(e)):(this.advance(),this.check("of")?(this.advance(),{type:"propertyOfExpression",property:{type:"identifier",name:e},target:this.parsePrimary(),line:t.line,column:t.column}):this.createIdentifier(e))}parseContextPropertyAccess(t){if("me"===t&&this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(""),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="computed-"+e;return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(n),0)}{if(Ut(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),0)}const e=this.consumeIdentifier(`Expected property name after '${{me:"my",it:"its",you:"your"}[t]}'`);return this.createMemberExpression(this.createIdentifier(t),this.createIdentifier(e.value),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;C.has(e.toLowerCase())&&ct(`💡 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 re(t,e,this.getPosition())}createIdentifier(t){return se(t,this.getPosition())}createBinaryExpression(t,e,n){return ie(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(ct(`✅ createProgramNode: Called with ${t.length} statements`),0===t.length)return ct("✅ createProgramNode: Returning error node (0 statements)"),{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===t.length)return ct(`✅ 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 ct(`✅ 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 ee(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(Vt)}matchSelector(){return this.matchPredicate(Vt)}checkAnySelector(){return this.checkPredicate(Ft)}checkLiteral(){return this.checkPredicate(_t)}checkIdentifierLike(){return this.checkPredicate(Bt)}checkIsCommand(){return this.checkPredicate(It)}checkCommandTerminator(){return this.checkPredicate(ne)}checkReference(){return this.checkPredicate(qt)}checkTimeExpression(){return this.checkPredicate(Ht)}checkEvent(){return this.checkPredicate(Dt)}checkContextVar(){return this.checkPredicate(Mt)}checkComment(){return this.checkPredicate(Wt)}checkIdentifier(){return this.checkPredicate(Jt)}checkKeyword(){return this.checkPredicate(jt)}checkString(){return this.checkPredicate(zt)}matchString(){return this.matchPredicate(zt)}checkNumber(){return this.checkPredicate(Zt)}matchNumber(){return this.matchPredicate(Zt)}checkBoolean(){return this.checkPredicate(Gt)}matchBoolean(){return this.matchPredicate(Gt)}checkTemplateLiteral(){return this.checkPredicate(Xt)}matchTemplateLiteral(){return this.matchPredicate(Xt)}checkQueryReference(){return this.checkPredicate(Yt)}matchQueryReference(){return this.matchPredicate(Yt)}checkIdSelector(){return this.checkPredicate(Kt)}checkClassSelector(){return this.checkPredicate(Qt)}checkCssSelector(){return this.checkPredicate(te)}checkBasicOperator(){return this.checkPredicate(ee)}matchBasicOperator(){return this.matchPredicate(ee)}matchTimeExpression(){return this.matchPredicate(Ht)}matchIdentifierLike(){return this.matchPredicate(Bt)}matchComparisonOperator(){return this.matchPredicate(Pt)}consumePredicate(t,e){return this.checkPredicate(t)?this.advance():(this.addError(e),this.peek())}consumeIdentifier(t){return this.consumePredicate(Jt,t)}consumeIdentifierLike(t){return this.consumePredicate(Bt,t)}consumeEvent(t){return this.consumePredicate(Dt,t)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(t,e){return this.check(t)?this.advance():(this.addError(e),this.peek())}addError(t){const e=this.peek();let n=e.start||0,r=e.line||1,s=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,s=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,s=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,s=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,s=t.column||1}this.error={message:t,line:Math.max(1,r),column:Math.max(1,s),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;ct("⚠️ 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 s="["+r.join("")+"]";return{type:"literal",value:s,raw:s,start:t,end:this.previous().end,line:e,column:n}}const r=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&r.has(i.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=>{const n=t.current+e;return n>=0&&t.tokens.length>n?t.tokens[n]:null},getInputSlice:(t,e)=>this.originalInput?0>t||t>=this.originalInput.length?"":void 0!==e?this.originalInput.slice(t,e):this.originalInput.slice(t):""};return Object.defineProperty(e,"current",{get:()=>t.current,set:e=>{t.current=e},enumerable:1,configurable:1}),e}}function Me(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&&(B(e),n>e.position);){const n=t[e.position];if("-"!==n||"-"!==M(e,1))if('"'!==n){if("'"===n||"'"===n){const t=M(e,1),n=e.tokens[e.tokens.length-1];if("s"!==t||!n||n.kind!==I.IDENTIFIER&&n.kind!==I.SELECTOR&&"]"!==n.value&&")"!==n.value&&"}"!==n.value)q(e);else{const t=e.position;P(e),P(e),F(e,I.OPERATOR,"'s",t)}continue}if("`"!==n)if("<"!==n)if("#"!==n){if("."===n){if("."===M(e,1)){const t=e.position;P(e),P(e),F(e,I.OPERATOR,"..",t);continue}const t=e.tokens[e.tokens.length-1],n=new Set(["from","to","into","on","in","at","first","last","next","previous","closest","random"]),r=t&&t.kind===I.IDENTIFIER&&w.has(t.value.toLowerCase()),s=t&&t.kind===I.IDENTIFIER&&n.has(t.value.toLowerCase());if((!t||t.kind===I.OPERATOR&&")"!==t.value&&"]"!==t.value||r||s||"("===t.value||"["===t.value||"{"===t.value||","===t.value||";"===t.value)&&(!t||t.end!==e.position)&&(Y(M(e))||"{"===M(e))){U(e);continue}}if("@"!==n)if("{"!==n)if("}"!==n){if("["===n){const t=e.tokens[e.tokens.length-1],n=t&&t.kind===I.IDENTIFIER&&R.has(t.value)&&e.tokens.length>=2&&"on"===e.tokens[e.tokens.length-2]?.value;(!t||t.kind!==I.IDENTIFIER&&")"!==t.value&&"]"!==t.value||n)&&n?(F(e,I.SYMBOL,"["),P(e)):(F(e,I.OPERATOR,"["),P(e));continue}if("]"!==n){if("$"===n){const t=M(e,1);if(t>="a"&&"z">=t||t>="A"&&"Z">=t||"_"===t){X(e);continue}}tt(n)?z(e):"0">n||n>"9"?("a">n||n>"z")&&("A">n||n>"Z")&&"_"!==n?(F(e,I.UNKNOWN,n),P(e)):G(e):Z(e)}else F(e,I.OPERATOR,"]"),P(e)}else F(e,I.OPERATOR,"}"),P(e);else F(e,I.OPERATOR,"{"),P(e);else J(e)}else U(e);else Q(e)?W(e):z(e);else H(e)}else q(e);else _(e)}return e.tokens}(t);return new De(n,e,t).parse()}De.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),De.PRATT_TABLE=Et,De.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];class Pe{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 Be(t){return t instanceof Error&&("isHalt"in t||"isExit"in t||"isBreak"in t||"isContinue"in t||"isReturn"in t)?t:null}function Fe(t){return{ok:1,value:t}}function Ve(t){return{ok:0,error:t}}function _e(t){return 1==t.ok}const qe=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 s=this.inferType(t),i=r.coerceFrom?.[s];if(i){const r=i(t,n);if(this.config.cacheCoercions&&null!==r){const n=`${s}:${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 He(t){const e=qe.get("String");return e?e.isType(t):"string"==typeof t}function Ue(t){const e=qe.get("Number");return e?e.isType(t):"number"==typeof t}function We(t){const e=qe.get("Boolean");return e?e.isType(t):"boolean"==typeof t}function Je(t){const e=qe.get("Object");return e?e.isType(t):"object"==typeof t&&null!==t}function ze(t){const e=qe.get("Function");return e?e.isType(t):"function"==typeof t}function Ze(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"style"in t}const Ge=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Xe(t,e){return Ge.has(e.toLowerCase())?t.hasAttribute(e):t.getAttribute(e)}const Ye={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=>Ze(t)?t.tabIndex:void 0,hidden:t=>Ze(t)?t.hidden:void 0,style:t=>getComputedStyle(t),children:t=>Array.from(t.children),parent:t=>t.parentElement,firstchild:t=>t.firstElementChild,lastchild:t=>t.lastElementChild,nextsibling:t=>t.nextElementSibling,previoussibling:t=>t.previousElementSibling,values:t=>function(t){if(t instanceof HTMLFormElement)return new FormData(t);const e=new FormData;return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t.getAttribute("name");n&&"value"in t&&e.append(n,t.value)}),e}(t)};function Ke(t,e){if(e.startsWith("computed-")){const n=e.slice(9);return function(t){return t instanceof HTMLElement}(t)?getComputedStyle(t).getPropertyValue(n):void 0}if(e.startsWith("@"))return Xe(t,e.slice(1));const n=Ye[e.toLowerCase()];if(n)return n(t);if(function(t,e){return t.hasAttribute(e)}(t,e))return Xe(t,e);const r=t[e];return ze(r)?r.bind(t):r}function Qe(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 tn(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 en(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 nn(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 on(t,e);const n=t;switch(t.type){case"literal":return function(t){return t.value}(n);case"identifier":return on(n,e);case"binaryExpression":return async function(t,e){const n=t.operator,r=t.right,s=t.left;if("has"===n||"have"===n){const n=await nn(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"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===n||"last"===n)&&Array.isArray(s.arguments)){const r=s.arguments[0];if("selector"===r?.type&&"string"==typeof r.value){const s=await nn(t.right,e);if(s&&"function"==typeof s.querySelectorAll){const t=Array.from(s.querySelectorAll(r.value));return 0===t.length?null:"first"===n?t[0]:t[t.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const n=await nn(t.right,e),r=n&&"function"==typeof n.querySelectorAll?n:null;if(r)return Array.from(r.querySelectorAll(s.value))}}const i=await nn(t.left,e);if("and"===n){if(!i)return i;const n=await nn(t.right,e);return tn(e,"and").evaluate(e,i,n)}if("or"===n){if(i)return i;const n=await nn(t.right,e);return tn(e,"or").evaluate(e,i,n)}const o=await nn(t.right,e),a=t=>"string"==typeof t?t.toLowerCase():t,c=t.ignoringCase?a(i):i,l=t.ignoringCase?a(o):o;switch(n){case"+":return"string"==typeof i||"string"==typeof o?(i??"")+""+(o??""):en(await tn(e,"addition").evaluate(e,{left:i,right:o}));case"-":return en(await tn(e,"subtraction").evaluate(e,{left:i,right:o}));case"*":return en(await tn(e,"multiplication").evaluate(e,{left:i,right:o}));case"/":return en(await tn(e,"division").evaluate(e,{left:i,right:o}));case"%":case"mod":return en(await tn(e,"modulo").evaluate(e,{left:i,right:o}));case"^":case"**":return en(await tn(e,"power").evaluate(e,{left:i,right:o}));case">":case"is greater than":return tn(e,"greaterThan").evaluate(e,i,o);case"<":case"is less than":return tn(e,"lessThan").evaluate(e,i,o);case">=":case"is greater than or equal to":return tn(e,"greaterThanOrEqual").evaluate(e,i,o);case"<=":case"is less than or equal to":return tn(e,"lessThanOrEqual").evaluate(e,i,o);case"==":case"is":case"am":case"equals":case"is equal to":return tn(e,"equals").evaluate(e,c,l);case"!=":case"is not":case"is not equal to":return tn(e,"notEquals").evaluate(e,c,l);case"===":case"really equals":case"is really equal to":return tn(e,"strictEquals").evaluate(e,c,l);case"!==":case"is not really equal to":return tn(e,"strictNotEquals").evaluate(e,c,l);case"as":return tn(e,"as").evaluate(e,i,ln(o));case"contains":return tn(e,"contains").evaluate(e,c,l);case"does not contain":case"does not include":return tn(e,"doesNotContain").evaluate(e,c,l);case"starts with":return tn(e,"startsWith").evaluate(e,c,l);case"ends with":return tn(e,"endsWith").evaluate(e,c,l);case"does not start with":return!await tn(e,"startsWith").evaluate(e,c,l);case"does not end with":return!await tn(e,"endsWith").evaluate(e,c,l);case"match":case"matches":return tn(e,"matches").evaluate(e,c,l);case"in":case"is in":return an(i,o);case"is not in":return!an(i,o);case"of":return o&&"object"==typeof o?o[i]:void 0;case"precedes":return cn(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!cn(i,o,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return cn(i,o,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!cn(i,o,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+n)}}(n,e);case"asExpression":return async function(t,e){const n=await nn(t.expression,e),r=ln(t.targetType);return tn(e,"as").evaluate(e,n,r)}(n,e);case"betweenExpression":return async function(t,e){const n=await nn(t.value,e),r=await nn(t.min,e),s=await nn(t.max,e),i=t=>"string"==typeof t?t.toLowerCase():t,[o,a,c]=t.ignoringCase?[i(n),i(r),i(s)]:[n,r,s],l=await tn(e,"between").evaluate(e,o,a,c);return t.negated?!l:l}(n,e);case"typeCheckExpression":return async function(t,e){const n=function(t,e,n){if(null==t&&n)return 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 nn(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 nn(t.collection,e),r=async(t,n)=>nn(t,{...e,it:n});switch(t.operator){case"where":return async function(t,e,n){const r=Qe(t),s=[];for(const t of r)await n(e,t)&&s.push(t);return s}(n,t.right,r);case"sorted by":return async function(t,e,n,r){const s=[...Qe(t)],i=await Promise.all(s.map(t=>r(e,t))),o=s.map((t,e)=>e);o.sort((t,e)=>{const n=i[t],r=i[e];return n===r?0:null==n?1:null==r||r>n?-1:1});const a=o.map(t=>s[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=Qe(t);return Promise.all(r.map(t=>n(e,t)))}(n,t.right,r);case"split by":return i=await nn(t.right,e),null==(s=n)?[]:(s+"").split(null==i?"":i+"");case"joined by":return function(t,e){const n=null==e?"":e+"";return Qe(t).map(t=>null==t?"":t+"").join(n)}(n,await nn(t.right,e));default:throw Error("Unknown collection operator: "+t.operator)}var s,i}(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 nn(n,e);switch(t.operator){case"not":case"!":return tn(e,"not").evaluate(e,r);case"no":return tn(e,"no").evaluate(e,r);case"-":return-r;case"+":return+r;case"exists":case"some":return tn(e,"exists").evaluate(e,r);case"does not exist":return tn(e,"doesNotExist").evaluate(e,r);case"is empty":return tn(e,"isEmpty").evaluate(e,r);case"is not empty":return tn(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 nn(t.object,e);if(t.computed){const r=await nn(t.property,e);return n?.[r]}{const e=t.property.name;if("string"==typeof e&&e.startsWith("@")){const t=e.substring(1);return n&&"function"==typeof n.getAttribute?n.getAttribute(t):void 0}return n instanceof Element&&"string"==typeof e?Ke(n,e):n?.[e]}}(n,e);case"callExpression":return async function(t,e){const n=await nn(t.callee,e);if(t.isConstructor&&"function"==typeof n)return new n(...await Promise.all(t.arguments.map(t=>nn(t,e))));if("identifier"===t.callee.type){const r=t.callee.name,s=await async function(t,e,n){return fn.has(e)?Promise.all(t.map(t=>"identifier"===t.type&&t.name?t.name:"selector"===t.type&&t.value?t.value:nn(t,n))):Promise.all(t.map(t=>nn(t,n)))}(t.arguments,r,e);switch(r){case"closest":return tn(e,"closest").evaluate(e,...s);case"previous":return tn(e,"previous").evaluate(e,...s);case"next":return tn(e,"next").evaluate(e,...s);case"first":return tn(e,"first").evaluate(e,...s);case"last":return tn(e,"last").evaluate(e,...s);default:if("function"==typeof n)return n(...s);throw Error("Cannot call non-function: "+r)}}if("function"==typeof n){const r=await Promise.all(t.arguments.map(t=>nn(t,e)));if("memberExpression"===t.callee.type&&t.callee.object){const s=await nn(t.callee.object,e);return n.apply(s,r)}return n(...r)}throw Error("Cannot call non-function")}(n,e);case"selector":return async function(t,e){const n=t.value,r="string"==typeof n?function(t){return t.replace(dn,"$1\\:")}(n):n,s=await tn(e,"elementWithSelector").evaluate(e,r);return!t.fromQuery&&"string"==typeof n&&n.startsWith("#")&&Array.isArray(s)?s[0]??null:s}(n,e);case"possessiveExpression":return async function(t,e){const n=await nn(t.object,e),r=t.property.name;return tn(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 nn(e,r)}}}(n,e);case"conditionalExpression":return async function(t,e){return await nn(t.test,e)?nn(t.consequent,e):t.alternate?nn(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 nn(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 s;s="identifier"===t.type?t.name:"literal"===t.type&&"string"===t.valueType?t.value:await nn(t,e)+"",n[s]=await nn(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,s=await nn(t.target,e);if(null==s)throw Error(`Cannot access property "${r}" of ${s}`);if(function(t){return t instanceof Element}(s))return Ke(s,r);const i=s[r];return"function"==typeof i?i.bind(s):i}(n,e);case"templateLiteral":return async function(t,e){let n=t.value;return n=await hn(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=un(t[0],e);for(let e=1;t.length>e&&null!=r;e++)r=r[t[e]];return(r??"")+""}return(un(n,e)??"")+""}catch{return""}}),n=await hn(n,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(t,n,r)=>{const s=n||r;try{const t=await async function(t,e){const n=Me(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 sn()};return nn(n.node,r)}(s,e);return t+""}catch{return"undefined"}}),n}(n,e);default:{const n=xt.get(t.type);if(n)return n(t,e);throw Error("Unknown AST node type: "+t.type)}}}let rn=null;async function sn(){if(!rn){const t=await Promise.resolve().then(function(){return Vi});rn=t.createFullExpressionRegistry()}return rn}async function on(t,e){const n=t.name;return"me"===n||"my"===n||"I"===n?tn(e,"me").evaluate(e):"you"===n||"your"===n||"yourself"===n?tn(e,"you").evaluate(e):"it"===n||"its"===n?tn(e,"it").evaluate(e):"window"===n?tn(e,"window").evaluate(e):"document"===n?tn(e,"document").evaluate(e):e.locals&&e.locals.has(n)?(Rt(n,e),e.locals.get(n)):e.globals&&e.globals.has(n)?(n.startsWith("$")&&Ot(n.slice(1),e),e.globals.get(n)):n.startsWith("$")&&e.globals&&e.globals.has(n.slice(1))?(Ot(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 an(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 cn(t,e,n){return t instanceof Node&&e instanceof Node&&0!==(t.compareDocumentPosition(e)&n)}function ln(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 un(t,e){return e.locals?.has(t)?(Rt(t,e),e.locals.get(t)):"me"===t&&e.me?e.me:"you"===t&&e.you?e.you:"it"===t&&e.it?e.it:"result"===t&&e.result?e.result:"undefined"!=typeof window&&"window"===t?window:e.globals?.has(t)?e.globals.get(t):void 0}async function hn(t,e,n){const r=[];let s;for(;null!==(s=e.exec(t));)r.push({index:s.index,length:s[0].length,replacement:await n(s[0],...s.slice(1))});let i=t;for(let t=r.length-1;t>=0;t--){const{index:e,length:n,replacement:s}=r[t];i=i.substring(0,e)+s+i.substring(e+n)}return i}const fn=new Set(["closest","previous","next"]),dn=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");class pn{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,s){this.addCleanup(t,{type:"listener",target:e,eventName:n,cleanup:()=>{e.removeEventListener(n,r,s),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,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":t++;break;case"observer":e++;break;case"interval":n++;break;case"timeout":r++;break;case"custom":s++}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+s,global:this.globalCleanups.length}}setDebugMode(t){this.debugMode=t}}const mn=new Map;function yn(t,e){return{me:t??null,it:null,you:null,result:null,locals:new Map,globals:e||mn,flags:{halted:0,breaking:0,continuing:0,returning:0,async:0}}}class gn{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 s=r.subscribe(e,n);return this.subscriptions.set(s.id,s),s}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 vn{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 s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);if(r.dependencies)for(const t of r.dependencies)await this.resolve(t,e,n);const i=await r.provide(e);return r.cache&&n&&n.set(s,i),i}resolveSync(t,e,n){const r=this.get(t);if(!r)return;const s="__provider_"+r.name;if(r.cache&&n?.has(s))return n.get(s);const i=r.provide(e);if(i instanceof Promise)throw Error(`Context provider '${t}' is async. Use resolve() instead of resolveSync().`);return r.cache&&n&&n.set(s,i),i}enhance(t){const e=this,n=new Map;return new Proxy(t,{get(t,r,s){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,s)},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[s,i]of r)try{n[s]=await this.resolve(s,t,e)}catch(t){lt(`[ContextProviderRegistry] Failed to resolve '${s}':`,t),n[s]=void 0}return n}getProviderNames(){return[...new Set([...this.globalProviders.keys(),...this.providers.keys()])]}clear(){this.providers.clear(),this.globalProviders.clear()}}const bn={evaluate:(t,e)=>nn(t,e)};class En{static toTyped(t){return{me:t.me,it:t.it,you:t.you,result:t.result,...void 0!==t.event&&{event:t.event},variables:t.variables||new Map,locals:t.locals||new Map,globals:t.globals||new Map,...void 0!==t.events&&{events:t.events},meta:t.meta||{},...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 wn{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(ot(`CommandAdapterV2: Executing '${this.name}' with args:`,e),this.hookRegistry&&await this.hookRegistry.runBeforeExecute(r),this.hookRegistry?.shouldIntercept(this.name,r))return void ot(`CommandAdapterV2: '${this.name}' intercepted by hook`);const s=En.toTyped(t);let i,o;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(ot(`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 nn(r,t))return void ot(`CommandAdapterV2: '${this.name}' skipped - when/where condition evaluated to false`);i=await this.impl.parseInput({args:n.args||[],modifiers:e||{},commandName:n.commandName},bn,t)}else i=e;else ot(`CommandAdapterV2: '${this.name}' has no parseInput(), using args as-is`),i=e;if(ot("CommandAdapterV2: Calling execute with parsed input:",i),2===this.impl.execute.length)o=await this.impl.execute(i,s);else{const t=Array.isArray(i)?i:[i];o=await this.impl.execute(s,...t)}return ot("CommandAdapterV2: Command result:",o),Object.assign(t,En.fromTyped(s,t)),this.hookRegistry&&await this.hookRegistry.runAfterExecute(r,o),o}catch(t){if(Cn(t)||ot(`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 xn{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 wn(t,void 0,this.hookRegistry);this.adapters.set(n,r),w.add(n);const s=t.metadata?.aliases;if(s&&Array.isArray(s))for(const e of s){const n=e.toLowerCase();this.implementations.set(n,t),this.adapters.set(n,r),w.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 kn=null;function Sn(){return kn||(kn=function(){const t=new xn,e=new gn,n=new vn,r=new Set,s={commands:t,eventSources:e,context:n,use(i){if(r.has(i.name))lt(`[LokaScriptRegistry] Plugin '${i.name}' is already installed`);else{if(i.commands)for(const e of i.commands)t.register(e);if(i.eventSources)for(const t of i.eventSources)e.register(t.name,t);if(i.contextProviders)for(const{name:t,provide:e,options:r}of i.contextProviders)n.register(t,e,r);i.setup?.(s),r.add(i.name)}},reset(){r.clear()}};return s}()),kn}class An{constructor(t={}){this.contextCache=new WeakMap;const e=Sn();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 Nn(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 Cn(t){return t instanceof Error?null!==Be(t)||"HALT_EXECUTION"===t.message||"EXIT_COMMAND"===t.message||"EXIT_EXECUTION"===t.message:0}function Tn(t){if(void 0===t)return;let e=t;if(e&&"object"==typeof e){const t=e;if("result"in t&&"wasAsync"in t)e=t.result;else if("result"in t&&"executed"in t){if(e=t.result,t.preserveArrayResult)return void 0!==e?e:void 0}else if("lastResult"in t&&"type"in t)e=t.lastResult;else if("conditionResult"in t&&"executedBranch"in t){if(void 0===t.result)return;e=t.result}else"value"in t&&1===Object.keys(t).length||"value"in t&&"target"in t&&"targetType"in t?e=t.value:"data"in t&&"status"in t&&"headers"in t&&(e=t.data)}return Array.isArray(e)&&e.length>0&&(e=e[0]),e}function On(t){return null!==t&&"object"==typeof t&&"command"in t&&"selector"in t}const $n=new WeakMap;class Rn{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=mn,this.hookRegistry=new Pe,t.hooks&&this.hookRegistry.register("default",t.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new pn,this.options.enableAutoCleanup&&this.setupAutoCleanup(),0!=t.registryIntegration&&(this.registryIntegration=new An("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,s){this.cleanupRegistry.registerListener(t,e,n,r,s)}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("⚠️ RUNTIME: Skipping error node: "+(e?.message||"unknown error")),void this.runtimeWarnings.push(e?.message||"Skipped error node")}switch(t.type){case"command":if(this.options.enableResultPattern)try{const n=await this.processCommandWithResult(t,e);if(!_e(n))throw Nn(n.error);return n.value}catch(t){throw t}return await this.processCommand(t,e);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"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(!_e(r))throw Nn(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(!_e(n))throw Nn(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:s}=t,i=n.toLowerCase();if(ot(`RUNTIME BASE: Processing command '${i}'`),this.registry.has(i)){const t=await this.registry.getAdapter(i);if(!t)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return await t.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this})}catch(t){throw Cn(t)||this.logError(`Error executing command '${i}':`,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=Be(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:s}=t,i=n.toLowerCase();if(ot(`RUNTIME BASE (Result): Processing command '${i}'`),!this.registry.has(i)){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(i);if(!o)throw Error(`Command '${i}' is registered but failed to load adapter.`);try{return Fe(await o.execute(e,{args:r||[],modifiers:s||{},commandName:i,runtime:this}))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw this.logError(`Error executing command '${i}':`,t),t}}async executeCommandSequenceWithResult(t,e){let n;for(const r of t){if(this.hasErrorDiagnostics(r)){const t=r.diagnostics?.[0];lt("⚠️ 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(!_e(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}),Fe(n.returnValue)}}n=t.value}else{const t=await this.evaluateExpressionWithResult(r,e);if(!_e(t))return t;n=t.value}}return Fe(n)}async evaluateExpression(t,e){const n=e.registry?e:{...e,registry:this.expressionRegistry},r=await nn(t,n);return On(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 Fe(await nn(t,e))}catch(t){if(t instanceof Error){const e=t;if(e.isHalt||"HALT_EXECUTION"===e.message)return Ve({type:"halt"});if(e.isExit||"EXIT_COMMAND"===e.message)return Ve({type:"exit",returnValue:e.returnValue});if(e.isBreak)return Ve({type:"break"});if(e.isContinue)return Ve({type:"continue"});if(e.isReturn)return Ve({type:"return",returnValue:e.returnValue})}throw t}}(t,n);if(!_e(r))return r;const s=r.value;if(On(s)){if(this.options.enableResultPattern)return this.processCommandWithResult({type:"command",name:s.command,args:[{type:"literal",value:s.selector}]},e);try{return Fe(await this.executeCommandFromPattern(s.command,s.selector,e))}catch(t){const e=this.toSignal(t);if(e)return Ve(e);throw t}}return Fe(s)}async executeCommandFromPattern(t,e,n){return this.processCommand({type:"command",name:t,args:[{type:"literal",value:e}]},n)}async executeProgram(t,e){if(!t.statements||!Array.isArray(t.statements))return;let n;const r=[],s=[],i=[];for(const e of t.statements)"eventHandler"===e.type?r.push(e):"initBlock"===e.type?s.push(e):i.push(e);for(const t of r)try{await this.execute(t,e)}catch(t){if(Cn(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of s)try{n=await this.execute(t,e)}catch(t){if(Cn(t)&&(t.isHalt||t.isExit))break;throw t}for(const t of i)try{n=await this.execute(t,e)}catch(t){if(Cn(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(Cn(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(Cn(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 s=await this.execute(r.value,e);n[t]=s}return n}enhanceContext(t){return this.registryIntegration?this.registryIntegration.enhanceContext(t):t}async executeBehaviorDefinition(t,e){const{name:n,parameters:r=[],eventHandlers:s=[],initBlock:i}=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:s,initBlock:i}),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 s={me: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},i=this.enhanceContext(s);if(r.parameters)for(const t of r.parameters)i.locals.set(t,t in n?n[t]:void 0);for(const[t,e]of Object.entries(n))r.parameters?.includes(t)||i.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,i),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&&Cn(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,i),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:s,target:i,args:o,selector:a,attributeName:c,watchTarget:l,modifiers:u}=t,h=r&&r.length>0?r:[n];lt(`BEHAVIOR: executeEventHandler: event='${n}', target='${i}'`);let f=[],d=null;if(i){const t="string"==typeof i?i.toLowerCase():"";if("window"===t||"the window"===t)d=window;else if("document"===t||"the document"===t||"body"===t)d=document;else if("me"===t||"myself"===t)f=e.me?[e.me]:[];else if("string"==typeof i&&e.locals.has(i)){const t=e.locals.get(i);lt(`BEHAVIOR: Target resolution: found local '${i}', isElement: ${this.isElement(t)}`),this.isElement(t)?f=[t]:Array.isArray(t)?f=t.filter(t=>this.isElement(t)):"string"==typeof t&&(f=this.queryElements(t,e))}else lt(`BEHAVIOR: Target resolution: querying for '${i}'`),f=this.queryElements(i,e)}else f=e.me?[e.me]:[];if(0===f.length&&!d)return void lt(`BEHAVIOR: executeEventHandler - No targets found for event '${n}', returning early`);if("mutation"===n&&c)return void this.setupMutationObserver(f,c,s,e);if("change"===n&&l)return void this.setupChangeObserver(l,s,e);const p=t.customEventSource;if(p&&this.registryIntegration){lt(`BEHAVIOR: executeEventHandler - Using custom event source '${p}' for event '${n}'`);const t=async t=>{const r=new Map(e.locals),i={...e,locals:r,it:t,event:t},o=this.enhanceContext(i);lt(`CUSTOM EVENT: Executing commands for event '${n}'`);try{await this.execute({type:"program",commands:s},o)}catch(t){this.logError(`[HyperFixi] Error executing commands for custom event '${n}':`,t)}};try{const r=this.registryIntegration.subscribeToEventSource(p,{event:n,handler:t,target:i,selector:a},e);lt(`BEHAVIOR: Subscribed to custom event source '${p}' (id: ${r.id})`),this.cleanupRegistry.registerGlobal(()=>r.unsubscribe(),"listener",`Custom event source '${p}' subscription ${r.id}`)}catch(t){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${p}':`,t)}return}const m=Rn.createEventHandler(this,s,e,a,o);let y,g=null;if(u){let t=m;if(u.prevent){const e=t;t=async t=>(t.preventDefault(),e(t))}if(u.stop){const e=t;t=async t=>(t.stopPropagation(),e(t))}if(u.debounce){const e=u.debounce;let n;y=r=>{n&&clearTimeout(n),n=setTimeout(()=>t(r),e)},g=()=>{n&&(clearTimeout(n),n=void 0)}}else if(u.throttle){const e=u.throttle;let n=0;y=r=>{const s=Date.now();e>s-n||(n=s,t(r))}}else y=t}else y=m;const v=u?.once?{once:1}:void 0;if(d){for(const t of h)d.addEventListener(t,y,v),f.length>0?this.cleanupRegistry.registerListener(f[0],d,t,y):this.cleanupRegistry.registerGlobal(()=>d.removeEventListener(t,y),"listener",`Global ${t} listener`);g&&(f.length>0?this.cleanupRegistry.registerCustom(f[0],g,"debounce-timeout"):this.cleanupRegistry.registerGlobal(g,"timeout","debounce-timeout"))}else for(const t of f){for(const e of h){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,y(t),v?.once){e.disconnect();break}}});e.observe(t),this.cleanupRegistry.registerCustom(t,()=>e.disconnect(),"resize-observer");continue}t.addEventListener(e,y,v),this.cleanupRegistry.registerListener(t,t,e,y)}g&&this.cleanupRegistry.registerCustom(t,g,"debounce-timeout")}}static createEventHandler(t,e,n,r,s){return async i=>{const o=$n.get(i)??0;if(o>=100)return;if($n.set(i,o+1),r&&i.target instanceof Element)try{if(!i.target.matches(r)&&!i.target.closest(r))return}catch{lt(`Event delegation: invalid CSS selector '${r}', skipping filter`)}const a=new Map(n.locals),c={...n,locals:a,it:i,event:i};a.has("target")||c.locals.set("target",i.target);const l=t.enhanceContext(c);if(s&&s.length>0){const t=i,e=t.detail;for(const n of s)l.locals.set(n,t[n]??e?.[n]??null)}for(const n of e)try{const e=Tn(await t.execute(n,l));void 0!==e&&Object.assign(l,{it:e,result:e})}catch(e){if(Cn(e)){if(e.isHalt||e.isExit)break;if(e.isReturn){void 0!==e.returnValue&&Object.assign(l,{it:e.returnValue,result:e.returnValue});break}}throw t.logError("COMMAND FAILED:",e),e}}}setupMutationObserver(t,e,n,r){lt(`RUNTIME BASE: Setting up MutationObserver for attribute '${e}' on ${t.length} elements`);for(const s of t){const t=new MutationObserver(async t=>{for(const i of t)if("attributes"===i.type&&i.attributeName===e){at(`MUTATION DETECTED: attribute '${e}' changed on`,s);const t={...r,me:s,it:i,locals:new Map(r.locals)},o=i.oldValue,a=s.getAttribute(e);t.locals.set("oldValue",o),t.locals.set("newValue",a);const c=this.enhanceContext(t);for(const t of n)try{await this.execute(t,c)}catch(t){if(Cn(t)){if(t.isHalt||t.isExit||t.isReturn)break}else this.logError("Error executing mutation handler command:",t)}}});t.observe(s,{attributes:1,attributeOldValue:1,attributeFilter:[e]}),this.cleanupRegistry.registerObserver(s,t),lt("RUNTIME BASE: MutationObserver attached to",s,`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 s=[];this.isElement(r)?s=[r]:Array.isArray(r)&&(s=r.filter(t=>this.isElement(t))),lt(`RUNTIME BASE: Watching ${s.length} target elements for content changes`);for(const t of s){const r=new MutationObserver(async r=>{for(const s of r)if("childList"===s.type||"characterData"===s.type){at("CONTENT CHANGE DETECTED on",t,"mutation type:",s.type);const r={...n,me:n.me,it:s,locals:new Map(n.locals)};r.locals.set("target",t);const i=s.oldValue,o=t.textContent;null!==i&&r.locals.set("oldValue",i),r.locals.set("newValue",o);const a=this.enhanceContext(r);for(const t of e)try{await this.execute(t,a)}catch(t){if(Cn(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 s=t;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(r.querySelectorAll(s))}catch{return lt(`queryElements: invalid CSS selector '${s}'`),[]}}isElement(t){return"undefined"!=typeof HTMLElement&&t instanceof HTMLElement?1:t&&"object"==typeof t?!!t.style&&!!t.classList:0}}function Ln(...t){const e=new Map;for(const n of t)for(const[t,r]of Object.entries(n))e.set(t,r);return e}const In={1:"one",2:"two",3:"three",4:"four",5:"five"};function jn(t,e,n,r){return t.length!==e?`${n} requires exactly ${s=e,In[s]??s+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null;var s}function Dn(t,e,n,r){return"string"!=typeof t[e]?`${n} ${r||"argument "+(e+1)} must be a string`:null}function Mn(t,e,n){return jn(t,1,e,n)??Dn(t,0,e,n)}function Pn(t,e){return jn(t,2,e,"left, right")}function Bn(){return null}function Fn(t,e,n,r){return t.length>e?`${n} expression takes at most ${1===e?"one":e+""} argument${1===e?"":"s"}${r?` (${r})`:""}`:null}function Vn(t,e,n,r,s){return e>t.length||t.length>n?`${r} requires ${e}-${n} arguments${s?` (${s})`:""}`:null}function _n(t,e,n,r=[]){return{type:t,message:e,suggestions:r,...n&&{path:n}}}const qn=("undefined"!=typeof process?1:0)||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let Hn;function Un(){return Hn({validate:t=>({success:1,data:t})})}function Wn(t,e){if(qn)return Un();const n=Hn({validate:n=>{if("object"!=typeof n||null===n||Array.isArray(n))return{success:0,error:_n("type-mismatch","Expected object, received "+typeof n)};const r=n,s={};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:_n("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:_n("missing-argument",`Required field "${e}" is missing`,e)};const i=n.validate(t);if(!i.success)return{success:0,error:_n("validation-error",i.error.message||`Field "${e}" validation failed`,i.error.path?`${e}.${i.error.path}`:e)};void 0!==i.data&&(s[e]=i.data)}return{success:1,data:s}}});return n.strict=()=>Wn(t,{strict:1}),n}Hn=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 Hn(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:_n("runtime-error",`String must be at least ${t} characters long`)}:r}};return Hn(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:_n("runtime-error",`String must be at most ${t} characters long`)}:r}};return Hn(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 Hn(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 s=n(r);return s.success?t(s.data)?s:{success:0,error:_n("runtime-error",e||"Refinement validation failed")}:s}};return Hn(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 Jn=t=>function(t={}){return qn?Un():Hn({validate:e=>t.optional&&null==e?{success:1,data:void 0}:"string"!=typeof e?{success:0,error:_n("type-mismatch","Expected string, received "+typeof e)}:void 0!==t.minLength&&t.minLength>e.length?{success:0,error:_n("runtime-error",`String must be at least ${t.minLength} characters long`)}:void 0!==t.maxLength&&e.length>t.maxLength?{success:0,error:_n("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:_n("runtime-error",`Expected "${t.pattern.source.slice(1,-1)}", received "${e}"`)}:{success:0,error:_n("missing-argument","String does not match required pattern")}:{success:1,data:e},...t.description&&{description:t.description}})}(t||{}),zn=t=>function(t={}){return qn?Un():Hn({validate:e=>{const n=Number(e);return isNaN(n)?{success:0,error:_n("type-mismatch","Expected number, received "+typeof e)}:void 0!==t.min&&t.min>n?{success:0,error:_n("runtime-error","Number must be at least "+t.min)}:void 0!==t.max&&n>t.max?{success:0,error:_n("runtime-error","Number must be at most "+t.max)}:{success:1,data:n}}})}(t||{}),Zn=()=>qn?Un():Hn({validate:t=>"boolean"!=typeof t?{success:0,error:_n("type-mismatch","Expected boolean, received "+typeof t)}:{success:1,data:t}}),Gn=t=>Wn(t),Xn=t=>function(t){return qn?Un():Hn({validate:e=>{if(!Array.isArray(e))return{success:0,error:_n("type-mismatch","Expected array, received "+typeof e)};if(e.length!==t.length)return{success:0,error:_n("runtime-error",`Expected tuple of length ${t.length}, received length ${e.length}`)};const n=[];for(let r=0;t.length>r;r++){const s=t[r].validate(e[r]);if(!s.success)return{success:0,error:_n("runtime-error",s.error.message,s.error.path?`${r}.${s.error.path}`:""+r)};n.push(s.data)}return{success:1,data:n}}})}(t),Yn=()=>Un(),Kn=()=>Un(),Qn=()=>function(t,e="Custom validation failed"){return qn?Un():Hn({validate:n=>t(n)?{success:1,data:n}:{success:0,error:_n("runtime-error",e)}})}(t=>void 0===t,"Expected undefined");class tr{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||Ue(t)&&isNaN(t)?0:1}success(t,e){return{success:1,value:t,type:e}}failure(t,e,n,r,s=[]){return{success:0,error:{name:t,type:e,message:n,code:r,suggestions:s}}}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":Je(t)?"object":typeof t}inferEvaluationType(t){return void 0===t?"Undefined":null===t?"Null":He(t)?"String":Ue(t)?"Number":We(t)?"Boolean":Array.isArray(t)?"Array":this.isElement(t)?"Element":"Object"}normalizeCollection(t){return Array.isArray(t)?t:t instanceof NodeList?Array.from(t):He(t)?t.split(""):null==t?[]:Je(t)&&Symbol.iterator in t?Array.from(t):[]}toNumber(t){if(Ue(t)&&Number.isFinite(t))return t;if(He(t)){const e=Number(t);return Number.isFinite(e)?e:null}return We(t)?t?1:0:null}}const er=Gn({selector:Jn().min(1),single:Zn().optional().default(0)});new class extends tr{constructor(){super(...arguments),this.name="me",this.category="Reference",this.syntax="me",this.description="References the current element in the execution context",this.inputSchema=Qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.me,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("MeExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "me"',"ME_EVALUATION_FAILED",["Ensure element context is properly set",'Check if "me" is available in current scope']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"me" expression takes no arguments',['Use "me" without any parameters']):this.validationSuccess()}},new class extends tr{constructor(){super(...arguments),this.name="you",this.category="Reference",this.syntax="you",this.description="References the target element (usually event target or command target)",this.inputSchema=Qn(),this.outputType="Element",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.you,s=this.isElement(r)?r:null,i=this.success(s,"element");return this.trackPerformance(t,e,i,n),i}catch(r){const s=this.failure("YouExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "you"',"YOU_EVALUATION_FAILED",["Ensure target element is available in context",'Check if "you" is set by event or command']);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"you" expression takes no arguments',['Use "you" without any parameters']):this.validationSuccess()}},new class extends tr{constructor(){super(...arguments),this.name="it",this.category="Reference",this.syntax="it",this.description="References the current context variable (result of previous operation or loop item)",this.inputSchema=Qn(),this.outputType="Any",this.metadata={category:"Reference",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=t.it,s={success:1,value:r,type:this.inferType(r)};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("ItExpressionError","runtime-error",r instanceof Error?r.message:'Failed to evaluate "it"',"IT_EVALUATION_FAILED",['Ensure "it" is set by previous operation',"Check if context variable is available"]);return this.trackPerformance(t,e,s,n),s}}validate(t){return void 0!==t?this.validationFailure("type-mismatch",'"it" expression takes no arguments',['Use "it" without any parameters']):this.validationSuccess()}},new class extends tr{constructor(){super(...arguments),this.name="css-selector",this.category="Reference",this.syntax="<selector/> or <selector/> (single)",this.description="Queries DOM elements using CSS selectors with validation",this.inputSchema=er,this.outputType="ElementList",this.metadata={category:"Reference",complexity:"medium"}}async evaluate(t,e){const n=Date.now();try{if(!this.isValidCSSSelector(e.selector)){const r=this.failure("CSSSelectorError","invalid-argument",`Invalid CSS selector: "${e.selector}"`,"INVALID_CSS_SELECTOR",["Check selector syntax","Use valid CSS selector patterns like .class, #id, tag[attr]","Avoid special characters that need escaping"]);return this.trackPerformance(t,e,r,n),r}let r;if(e.single)r=document.querySelector(e.selector);else{const t=Array.from(document.querySelectorAll(e.selector));r=t.length>0?t:null}const s={success:1,value:r,type:Array.isArray(r)?"element-list":"element"};return this.trackPerformance(t,e,s,n),s}catch(r){const s=this.failure("CSSSelectorError","runtime-error",r instanceof Error?r.message:"CSS selector evaluation failed","CSS_SELECTOR_EVALUATION_FAILED",["Check if selector is valid CSS","Ensure DOM is ready when query executes","Verify elements exist in document"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);if(!e.success)return{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid input: "+t.message,suggestions:this.getValidationSuggestion(t.code??"unknown")}))??[],suggestions:["Provide valid CSS selector string","Check selector syntax"]};const{selector:n}=e.data;return this.isValidCSSSelector(n)?this.validationSuccess():this.validationFailure("syntax-error",`Invalid CSS selector syntax: "${n}"`,["Use .class for class selectors","Use #id for ID selectors","Use tag for element selectors","Use [attr] for attribute selectors"])}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Ensure input matches expected format"])}}isValidCSSSelector(t){try{return document.querySelector(t),1}catch{return 0}}getValidationSuggestion(t){return[{too_small:"CSS selector cannot be empty",invalid_type:"Selector must be a string",required:"CSS selector is required"}[t]||"Check input format and types"]}};const nr={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.me??null,validate:Bn},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async t=>t.you??null,validate:Bn},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Bn},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.it,validate:Bn},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async t=>t.result,validate:Bn},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=>Mn(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=>Mn(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=>Mn(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=>Mn(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:Bn},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async t=>window,validate:Bn},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async t=>document,validate:Bn},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=document.querySelectorAll(n);return Array.from(r)},validate:t=>Mn(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 s=r||t.me;if(s&&s instanceof HTMLElement){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>Vn(t,1,2,"styleRef","property, optional element")??Dn(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 s=null;if("my"===n&&t.me?s=t.me instanceof HTMLElement?t.me:null:"its"===n&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(r.startsWith("computed-")){const t=r.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(r)||void 0}},validate:t=>jn(t,2,"possessiveStyleRef","possessor, property")??Dn(t,0,"possessiveStyleRef","possessor")??Dn(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 s=null;if("me"===r&&t.me?s=t.me instanceof HTMLElement?t.me:null:"it"===r&&t.it&&(s=t.it instanceof HTMLElement?t.it:null),s){if(n.startsWith("computed-")){const t=n.substring(9);return getComputedStyle(s).getPropertyValue(t)||""}return s.style.getPropertyValue(n)||void 0}},validate:t=>jn(t,2,"ofStyleRef","property, reference")??Dn(t,0,"ofStyleRef","property")??Dn(t,1,"ofStyleRef","reference")}};class rr{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 sr=new class{constructor(){this.domQueryCache=new rr(200,3e3),this.exprResultCache=new rr(500,2e3),this.cssMatchCache=new rr(100,5e3),this.formValueCache=new rr(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 s=t.matches(e);return this.cssMatchCache.set(n,s),s}getExpressionResult(t){const e=this.exprResultCache.get(t);if(void 0!==e)return this.hits++,e;this.misses++}setExpressionResult(t,e){this.exprResultCache.set(t,e)}getFormValue(t){const e=this.getElementCacheKey(t),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(()=>{sr.cleanup()},1e4);const ir=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=sr.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 or(){sr.cleanup(),ir.getMetrics().memoryUsage>52428800&&ir.reset()}let ar=null;function cr(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 cr(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 lr(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 ur(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 hr(t){try{return cr(t,"_"),1}catch{return 0}}function fr(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,s]=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=lr(t),r=lr(e);return null!==n&&null!==r?[n,r]:[t+"",e+""]}(t,e);switch(n){case">":return r>s;case"<":return s>r;case">=":return r>=s;case"<=":return s>=r;case"==":return dr(t,e);case"!=":return!dr(t,e);default:return 0}}function dr(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?dr(t?1:0,e):"boolean"==typeof e?dr(t,e?1:0):t+""==e+""}function pr(t,e=[]){return{isValid:0,errors:t,suggestions:e}}function mr(t,e,n=[],r="error"){return{type:t,message:e,suggestions:n,severity:r}}function yr(t,e,n,r,s,i=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:s,duration:Date.now()-s,success:i,...void 0!==o&&{error:o}}),r}"undefined"!=typeof window&&function(t=3e4){ar&&clearInterval(ar),ar=setInterval(or,t)}();const gr=Gn({left:Yn().describe("Left operand value"),right:Yn().describe("Right operand value")}).strict(),vr=Gn({operand:Yn().describe("Operand value to negate")}).strict();function br(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType}new class extends tr{constructor(){super(...arguments),this.name="and",this.category="Logical",this.syntax="left and right",this.description="Logical AND operation with comprehensive boolean type coercion",this.inputSchema=gr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(!s)return this.trackSimple(t,n,1,"boolean"),this.success(0,"boolean");const i=this.toBoolean(e.right),o=s&&i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("AndExpressionError","runtime-error","Logical AND operation failed: "+(e instanceof Error?e.message:e+""),"AND_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid AND operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends tr{constructor(){super(...arguments),this.name="or",this.category="Logical",this.syntax="left or right",this.description="Logical OR operation with comprehensive boolean type coercion",this.inputSchema=gr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.toBoolean(e.left);if(s)return this.trackSimple(t,n,1,"boolean"),this.success(1,"boolean");const i=this.toBoolean(e.right),o=s||i;return this.trackSimple(t,n,1,"boolean"),this.success(o,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("OrExpressionError","runtime-error","Logical OR operation failed: "+(e instanceof Error?e.message:e+""),"OR_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid OR operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide both left and right operands","Ensure operands are valid values"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends tr{constructor(){super(...arguments),this.name="not",this.category="Logical",this.syntax="not operand",this.description="Logical NOT operation with comprehensive boolean type coercion",this.inputSchema=vr,this.outputType="Boolean",this.metadata={category:"Logical",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=!this.toBoolean(e.operand);return this.trackSimple(t,n,1,"boolean"),this.success(s,"boolean")}catch(e){return this.trackSimple(t,n,0),this.failure("NotExpressionError","runtime-error","Logical NOT operation failed: "+(e instanceof Error?e.message:e+""),"NOT_EVALUATION_FAILED")}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid NOT operation input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a single operand","Ensure operand is a valid value"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}};const Er=Xn([Yn(),Yn()]),wr=Xn([Yn(),Jn()]),xr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(t,e,n){const r=Date.now();try{return yr(this,t,[e,n],e==n,r)}catch(s){throw yr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Pn(t,"equals"),inputSchema:Er,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"]}},kr={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e===n;return r&&yr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Pn(t,"strictEquals")},Sr={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,s=e!=n;return r&&yr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Pn(t,"notEquals")},Ar={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],async evaluate(t,e,n){const r=t.evaluationHistory,s=e!==n;return r&&yr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Pn(t,"strictNotEquals")},Nr={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=fr(e,n,"<");return r&&yr(this,t,[e,n],i,s),i},validate:t=>Pn(t,"lessThan")},Cr={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,s=r?Date.now():0,i=fr(e,n,"<=");return r&&yr(this,t,[e,n],i,s),i},validate:t=>Pn(t,"lessThanOrEqual")},Tr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=fr(e,n,">");return r&&yr(this,t,[e,n],i,s),i},validate:t=>Pn(t,"greaterThan")},Or={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,s=r?Date.now():0,i=fr(e,n,">=");return r&&yr(this,t,[e,n],i,s),i},validate:t=>Pn(t,"greaterThanOrEqual")},$r={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(t,e,n){const r=Date.now();try{return yr(this,t,[e,n],e&&n,r)}catch(s){throw yr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>Pn(t,"and"),inputSchema:Er,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"]}},Rr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],async evaluate(t,e,n){const r=t.evaluationHistory,s=e||n;return r&&yr(this,t,[e,n],s,r?Date.now():0),s},validate:t=>Pn(t,"or")},Lr={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],async evaluate(t,e){const n=t.evaluationHistory,r=!e;return n&&yr(this,t,[e],r,n?Date.now():0),r},validate:t=>jn(t,1,"not","operand")},Ir={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e?1:He(e)||Array.isArray(e)||e instanceof NodeList?0===e.length:e instanceof Node||e instanceof Element?0:Je(e)?0===Object.keys(e).length:0,n&&yr(this,t,[e],s,r),s},validate:t=>jn(t,1,"isEmpty","value")},jr={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0;let s;return s=null==e||0==e?1:Array.isArray(e)||e instanceof NodeList?0===e.length:(He(e),0),n&&yr(this,t,[e],s,r),s},validate:t=>jn(t,1,"no","value")},Dr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],async evaluate(t,e){const n=t.evaluationHistory,r=n?Date.now():0,s=!await Ir.evaluate(t,e);return n&&yr(this,t,[e],s,r),s},validate:t=>jn(t,1,"isNotEmpty","value")},Mr={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],async evaluate(t,e){const n=t.evaluationHistory,r=null!=e;return n&&yr(this,t,[e],r,n?Date.now():0),r},validate:t=>jn(t,1,"exists","value")},Pr={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],async evaluate(t,e){const n=t.evaluationHistory,r=null==e;return n&&yr(this,t,[e],r,n?Date.now():0),r},validate:t=>jn(t,1,"doesNotExist","value")},Br={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i;if(e&&n){if(br(e)&&br(n))return i=e.contains(n),r&&yr(this,t,[e,n],i,s),i;if(He(e)&&e.match(/^[.#][\w-]+$/)){const o=document.querySelector(e);if(o&&br(n))return i=o.contains(n),r&&yr(this,t,[e,n],i,s),i;if(o&&He(n)&&n.match(/^[.#][\w-]+$/)){const a=document.querySelector(n);return i=a?o.contains(a):0,r&&yr(this,t,[e,n],i,s),i}}if(He(n)&&n.match(/^[.#][\w-]+$/)&&br(e)){const o=document.querySelector(n);return i=o?e.contains(o):0,r&&yr(this,t,[e,n],i,s),i}}return i=He(e)&&He(n)||Array.isArray(e)?e.includes(n):"undefined"!=typeof NodeList&&e instanceof NodeList?Array.from(e).includes(n):Je(e)&&He(n)?n in e:0,r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"contains","container, value")},Fr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Br.evaluate(t,e,n);return r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"doesNotContain","container, value")},Vr={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=He(e)&&He(n)?e.startsWith(n):0;return r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"startsWith","str, prefix")},_r={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=He(e)&&He(n)?e.endsWith(n):0;return r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"endsWith","str, suffix")},qr={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(t,e,n,r){const s=t.evaluationHistory;let i=n,o=r;if(null!=i&&null!=o&&i>o){const t=i;i=o,o=t}const a=null!=i&&null!=o&&e>=i&&o>=e;return s&&yr(this,t,[e,n,r],a,s?Date.now():0),a},validate:t=>jn(t,3,"between","value, min, max")},Hr={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(t,e,n){const r=Date.now();try{let s;if(e instanceof Element&&He(n)){const t=n;if(t.startsWith(".")||t.startsWith("#")||t.startsWith(":")||t.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(t))try{s=function(t,e){return sr.matches(t,e)}(e,t)}catch(t){s=0}else s=0}else if(He(e)&&He(n)){const t=e,r=n;try{s=(r.startsWith("/")&&r.endsWith("/")?RegExp(r.slice(1,-1)):RegExp(r)).test(t)}catch(e){s=t.includes(r)}}else s=0;return yr(this,t,[e,n],s,r)}catch(s){throw yr(this,t,[e,n],0,r,0,s instanceof Error?s:Error(s+"")),s}},validate:t=>jn(t,2,"matches","element, selector"),inputSchema:wr,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"]}},Ur={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0;let i=0;if(e instanceof Element&&He(n)){const t=n;t.startsWith(".")?i=e.classList.contains(t.slice(1)):t.startsWith("[")&&t.endsWith("]")&&(i=e.hasAttribute(t.slice(1,-1)))}return r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"has","element, selector")},Wr={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],async evaluate(t,e,n){const r=t.evaluationHistory,s=r?Date.now():0,i=!await Ur.evaluate(t,e,n);return r&&yr(this,t,[e,n],i,s),i},validate:t=>jn(t,2,"doesNotHave","element, selector")},Jr={equals:xr,strictEquals:kr,notEquals:Sr,strictNotEquals:Ar,lessThan:Nr,lessThanOrEqual:Cr,greaterThan:Tr,greaterThanOrEqual:Or,and:$r,or:Rr,not:Lr,no:jr,isEmpty:Ir,isNotEmpty:Dr,exists:Mr,doesNotExist:Pr,contains:Br,doesNotContain:Fr,startsWith:Vr,endsWith:_r,between:qr,matches:Hr,has:Ur,doesNotHave:Wr},zr=Gn({value:Jn().describe("String literal value")}).strict(),Zr=Gn({value:zn().describe("Number literal value")}).strict(),Gr=Gn({value:Zn().describe("Boolean literal value")}).strict(),Xr=Gn({left:Yn().describe("Left operand"),right:Yn().describe("Right operand")}).strict(),Yr={stringLiteral:new class extends tr{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=zr,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 s=e.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,t));const i=this.success(s,"string");return this.trackSimple(t,n,1,s),i}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)?(Rt(t,e),e.locals.get(t)):e.globals?.has(t)?e.globals.get(t):void 0}},numberLiteral:new class extends tr{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=Zr,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 tr{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Gr,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 tr{constructor(){super(...arguments),this.name="addition",this.category="Special",this.syntax="left + right",this.description="Addition of two numeric values",this.inputSchema=Xr,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 s=cr(e.left,"left operand")+cr(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"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 tr{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=Xr,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 s=this.convertToString(e.left)+this.convertToString(e.right);return this.trackSimple(t,n,1,s),this.success(s,"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=Xr.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(He(t))return t;if(Ue(t))return""+t;if(We(t))return""+t;if(t instanceof Date)return""+t;try{return t+""}catch{return"[object Object]"}}},multiplication:new class extends tr{constructor(){super(...arguments),this.name="multiplication",this.category="Special",this.syntax="left * right",this.description="Multiplication of two numeric values",this.inputSchema=Xr,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 s=cr(e.left,"left operand")*cr(e.right,"right operand");return this.trackSimple(t,n,1,s),this.success(s,"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 Kr(){return Ln(nr,Jr,Yr)}class Qr{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=yn(t);this.runtime.execute(e,n).catch(n=>{console.error('[HyperFixi] Error executing _="" attribute:',n),console.error("Element:",t),console.error("Code:",e)})}}function ts(t,e,n,r,s,i){function o(t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("Function expected");return t}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!e&&t?r.static?t:t.prototype:null,h=e||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),f=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(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(t||null))};var y=(0,n[d])("accessor"===c?{get:h.get,set:h.set}:h[l],p);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(a=o(y.get))&&(h.get=a),(a=o(y.set))&&(h.set=a),(a=o(y.init))&&s.unshift(a)}else(a=o(y))&&("field"===c?s.unshift(a):h[l]=a)}u&&Object.defineProperty(u,r.name,h),f=1}function es(t,e,n){for(var r=arguments.length>2,s=0;e.length>s;s++)n=r?e[s].call(t,n):e[s].call(t);return r?n:void 0}function ns(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 rs(t){const e=t.trim();return e.startsWith("[@")&&e.endsWith("]")||e.startsWith("@")?1:0}function ss(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 s=t.slice(n+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:r,value:s}}if(e.startsWith("@"))return{name:e.substring(1).trim()};throw Error("Invalid attribute syntax: "+t)}function is(t,e){for(const n of t)e(n);return t}function os(t,e,n){for(const r of t)for(const t of e)n(r,t);return t}function as(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 cs(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&&us(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&&us(t));const e=(t+"").trim(),n=e.startsWith(".")?e.substring(1):e;return n.length>0&&us(n)?[n]:[]}function ls(t){const e=t.trim();return/^\{[^}]+\}$/.test(e)}function us(t){if(!t||0===t.trim().length)return 0;const e=t.trim();return ls(e)?1:/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(e)}function hs(t,e){return t.map(t=>{if(ls(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+"":(ot(`Dynamic class variable '${n}' not found in context`),"")}return t}).filter(t=>t.length>0)}"function"==typeof SuppressedError&&SuppressedError;const fs=Symbol("command:name"),ds=Symbol("command:category"),ps=Symbol("command:metadata");function ms(t){return function(e,n){const r=e;r[fs]=t.name,r[ds]=t.category,Object.defineProperty(e.prototype,"name",{value:t.name,writable:0,enumerable:1})}}function ys(t){return function(e,n){const r=e,s=r[ds];if(!s)throw Error("@meta decorator requires @command decorator to be applied first on "+e.name);const i={description:t.description,syntax:t.syntax,examples:t.examples,category:s,sideEffects:t.sideEffects,deprecated:t.deprecated,deprecationMessage:t.deprecationMessage,aliases:t.aliases,relatedCommands:t.relatedCommands,isBlocking:t.isBlocking??0,hasBody:t.hasBody??0,version:"1.0.0",compatibility:t.compatibility};r[ps]=i,Object.defineProperty(e,"metadata",{value:i,writable:0,enumerable:1,configurable:0}),Object.defineProperty(e.prototype,"metadata",{get:()=>i,enumerable:1,configurable:0})}}function gs(t){return()=>new t}function vs(t){return null!==t&&"object"==typeof t&&"nodeType"in t&&1===t.nodeType&&"tagName"in t&&"string"==typeof t.tagName&&"classList"in t}function bs(t,e){return e}function Es(t,e,n){if(vs(t))return t;if(!t){const t=e.me;if(!t)throw Error(bs(0,"No target element — provide explicit target or ensure context.me is set"));return ws(t)}if("string"==typeof t){const n=t.trim();if("me"===n){if(!e.me)throw Error(bs(0,'Context reference "me" is not available'));return ws(e.me)}if("it"===n){if(!vs(e.it))throw Error(bs(0,'Context reference "it" is not an HTMLElement'));return e.it}if("you"===n){if(!e.you)throw Error(bs(0,'Context reference "you" is not available'));return ws(e.you)}const r=e.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!r)throw Error(bs(0,"DOM not available — cannot resolve element selector"));const s=r.querySelector(n);if(!s)throw Error(bs(0,"Element not found with selector: "+n));if(!vs(s))throw Error(bs(0,"Element found but is not an HTMLElement: "+n));return s}throw Error(bs(0,"Invalid target type: "+typeof t))}function ws(t){if(vs(t))return t;throw Error("Value is not an HTMLElement")}function xs(t,e,n){switch(t.toLowerCase()){case"my":case"me":if(!e.me)throw Error(bs(0,'No "me" element in context'));if(!vs(e.me))throw Error(bs(0,"context.me is not an HTMLElement"));return e.me;case"its":case"it":if(!e.it)throw Error(bs(0,'No "it" value in context'));if(!vs(e.it))throw Error(bs(0,"context.it is not an HTMLElement"));return e.it;case"your":case"you":if(!e.you)throw Error(bs(0,'No "you" element in context'));if(!vs(e.you))throw Error(bs(0,"context.you is not an HTMLElement"));return e.you;default:throw Error(bs(0,"Unknown possessive: "+t))}}const ks=["on","from","to","in","with","at"];async function Ss(t,e,n,r,s={},i){let o=t;if(s.filterPrepositions&&t&&(o=t.filter(t=>{const e=t;return"identifier"===e?.type&&"string"==typeof e.name?!ks.includes(e.name.toLowerCase()):1})),(!o||0===o.length)&&s.fallbackModifierKey&&i){const t=i[s.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(!vs(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}const a=[];for(const t of o){const s=await e.evaluate(t,n);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(vs(s))a.push(s);else if(s instanceof NodeList){const t=Array.from(s).filter(vs);a.push(...t)}else if(Array.isArray(s)){const t=s.filter(vs);a.push(...t)}else{if("string"!=typeof s)throw Error(`Invalid ${r} target: expected HTMLElement or CSS selector, got ${typeof s}`);try{let t=s;t.startsWith("<")&&t.endsWith("/>")&&(t=t.slice(1,-2).trim());const e=n.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!e)throw Error("DOM not available - cannot resolve element selector");const r=e.querySelectorAll(t),i=Array.from(r).filter(vs);a.push(...i)}catch(t){throw Error(`Invalid CSS selector: "${s}" - ${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(!vs(n.me))throw Error(r+" command: context.me must be an HTMLElement");return[n.me]}return a}function As(t){return"string"==typeof t&&t.trim().startsWith("*")}function Ns(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 Cs(t,e,n){t.style.setProperty(e,n)}const Ts=["dialog","details","summary","select"];function Os(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 $s(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=Os(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=Os(t);return"string"==typeof n&&n.startsWith("*")}(t)?{value:Os(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=Os(t);return"string"==typeof e&&e.startsWith("@")}return 0}(t)?{value:(r=t,"attributeAccess"===r.type?"@"+r.attributeName:Os(r)),extractedFromNode:1}:{value:await e.evaluate(t,n),extractedFromNode:0};var r}class Rs{async resolveTargets(t,e,n,r){return Ss(t,e,n,this.mode,{filterPrepositions:1,fallbackModifierKey:this.preposition},r)}async evaluateFirst(t,e,n){return $s(t,e,n)}parseClassNames(t){return cs(t)}isAttribute(t){return rs(t.trim())}isCSSProperty(t){return As(t.trim())}validateTargets(t){return Array.isArray(t)&&function(t){return Array.isArray(t)&&t.length>0&&t.every(t=>vs(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 Ls=(()=>{let t,e,n=[ys({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"]}),ms({name:"add",category:"dom"})],r=[],s=Rs;return e=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}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 s=r.trim();if(this.isAttribute(s)){const{name:r,value:i}=function(t){const e=ss(t);return{name:e.name,value:e.value??""}}(s);return{type:"attribute",name:r,value:i,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}if(this.isCSSProperty(s)){const r=s.substring(1).trim();if(2>t.args.length)throw Error("add *property requires a value argument");const i=await e.evaluate(t.args[1],n);return{type:"styles",styles:{[r]:i+""},targets:await this.resolveTargets(t.args.slice(2),e,n,t.modifiers)}}}const s=this.parseClassNames(r);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}async execute(t,e){switch(t.type){case"classes":{const n=hs(t.classes,e);n.length>0&&os(t.targets,n,(t,e)=>{t.classList.contains(e)||t.classList.add(e)});break}case"attribute":n=t.name,r=t.value,is(t.targets,t=>{t.setAttribute(n,r)});break;case"styles":os(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}},ns(e,"AddCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),es(e,r)})(),e})();const Is=gs(Ls);function js(t){return t.parentNode?(t.remove(),1):0}let Ds=(()=>{let t,e,n=[ys({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"]}),ms({name:"remove",category:"dom"})],r=[],s=Rs;return e=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}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(vs(r))return{type:"element",targets:[r]};if(Array.isArray(r)&&r.length>0&&vs(r[0]))return{type:"element",targets:r.filter(t=>vs(t))};if("string"==typeof r){const s=r.trim();if(this.isAttribute(s))return{type:"attribute",name:ss(s).name,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)};if(this.isCSSProperty(s))return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}const s=this.parseClassNames(r);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t.args.slice(1),e,n,t.modifiers)}}execute(t,e){switch(t.type){case"classes":{const n=hs(t.classes,e);n.length>0&&os(t.targets,n,(t,e)=>{t.classList.remove(e)});break}case"attribute":n=t.name,is(t.targets,t=>{t.removeAttribute(n)});break;case"styles":os(t.targets,t.properties,(t,e)=>{t.style.removeProperty(e)});break;case"element":for(const e of t.targets)js(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}},ns(e,"RemoveCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),es(e,r)})(),e})();const Ms=gs(Ds);function Ps(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 Bs(t){if("number"==typeof t){if(0>t)throw Error("Duration must be >= 0");return Math.floor(t)}if("string"==typeof t){const e=Ps(t);if(!e)throw Error(`Invalid duration format: "${t}"`);return e.milliseconds}throw Error("Invalid duration type: "+typeof t)}function Fs(t){return 0===t.length?[]:"SUMMARY"===t[0].tagName?t.map(t=>t.closest("details")).filter(t=>null!==t):t}function Vs(t,e,n){return()=>{"class"===e?t.classList.toggle(n):"attribute"===e&&as(t,n)}}function _s(t,e,n,r){const s=Vs(t,e,n),i=setTimeout(s,r);return()=>{clearTimeout(i)}}function qs(t,e,n,r){const s=Vs(t,e,n),i=()=>{s(),t.removeEventListener(r,i)};return t.addEventListener(r,i,{once:1}),()=>{t.removeEventListener(r,i)}}function Hs(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 s=t;for(let t=0;r.length-1>t;t++)if(s=s[r[t]],null==s)return;return void(s[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 Us=/^the\s+(.+?)\s+of\s+(.+)$/i,Ws=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 Js(t){return"string"==typeof t&&Us.test(t)}function zs(t,e){const n=t.match(Us);if(!n)return null;try{return{element:Es(n[2].trim(),e),property:n[1].trim()}}catch{return null}}async function Zs(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 s=await e.evaluate(t.target,n);return Array.isArray(s)&&(s=s[0]),vs(s)?{element:s,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 s=await e.evaluate(t.object,n);return Array.isArray(s)&&(s=s[0]),vs(s)?{element:s,property:r}:null}(t,e,n);const r=t;if("possessiveExpression"===r?.type||"memberExpression"===r?.type){const t=r.object,s=r.property;let i=await e.evaluate(t,n);if(Array.isArray(i)&&(i=i[0]),!vs(i))return null;const o=s?.name||s?.value;return o?{element:i,property:o}:null}return null}function Gs(t,e){const{element:n,property:r}=t;r.startsWith("*")?Cs(n,r.substring(1),e+""):Hs(n,r,e)}async function Xs(t,e,n){let r,s;if(t?.for){const s=await e.evaluate(t.for,n);r="number"==typeof s?s:"string"==typeof s?function(t,e=300){if("number"==typeof t)return Math.max(0,Math.floor(t));if("string"==typeof t){const n=Ps(t);return n?n.milliseconds:e}return e}(s):void 0}if(t?.until){const r=await e.evaluate(t.until,n);"string"==typeof r&&(s=r)}return{duration:r,untilEvent:s}}const Ys=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"toggle",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("toggle command requires an argument");const r=t.args[0],s=r?.name;if("between"===s&&t.args.length>=4){const{duration:r,untilEvent:s}=await Xs(t.modifiers,e,n),i=await e.evaluate(t.args[1],n),o=await e.evaluate(t.args[3],n),a=[];for(let e=4;t.args.length>e;e++){const n=t.args[e]?.name;"on"!==n&&"from"!==n&&a.push(t.args[e])}const c={filterPrepositions:1,fallbackModifierKey:"on"},l=await Ss(a,e,n,"toggle",c,t.modifiers);return{type:"classes-between",classA:(i+"").replace(/^\./,""),classB:(o+"").replace(/^\./,""),targets:l,duration:r,untilEvent:s}}const i=await Zs(r,e,n);if(i)return{type:"property",target:i};if("selector"===r.type&&"string"==typeof r.value&&r.value.startsWith("*")){let s=r.value,i=1;if("*"===s&&t.args.length>1&&"identifier"===t.args[1].type&&(s="*"+t.args[1].name,i=2),"*"===s&&t.modifiers?.on){const r=t.modifiers.on?.name;if(r&&["display","visibility","opacity"].includes(r)){s="*"+r;const{duration:i,untilEvent:o}=await Xs(t.modifiers,e,n),a=Ns(s);if(a){const t=n.me;return{type:"css-property",property:a,targets:t?[t]:[],duration:i,untilEvent:o}}}}const o=Ns(s);if(o){const{duration:r,untilEvent:s}=await Xs(t.modifiers,e,n),a={filterPrepositions:1,fallbackModifierKey:"on"};return{type:"css-property",property:o,targets:await Ss(t.args.slice(i),e,n,"toggle",a,t.modifiers),duration:r,untilEvent:s}}}const{duration:o,untilEvent:a}=await Xs(t.modifiers,e,n),{value:c}=await $s(r,e,n);if(Js(c)){const t=zs(c,n);if(t)return{type:"property",target:t}}const{type:l,expression:u}=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 Ts.includes(e)}(e)}(e);if(vs(t)||Array.isArray(t)&&t.every(t=>vs(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 Ts.some(t=>e.includes(t))}(e)?{type:"element",expression:e}:{type:"class",expression:e}}return{type:"class",expression:""}}(c,r),h={filterPrepositions:1,fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:r,value:s}=ss(u);return{type:"attribute",name:r,value:s,targets:await Ss(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:o,untilEvent:a}}case"css-property":{const r=Ns(u);if(!r)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:r,targets:await Ss(t.args.slice(1),e,n,"toggle",h,t.modifiers)}}case"element":{let s;if(vs(c))s=[c];else if(Array.isArray(c)&&c.every(t=>vs(t)))s=c;else if(u){const t=document.querySelectorAll(u);s=Array.from(t).filter(t=>vs(t))}else s=await Ss([r],e,n,"toggle",h,t.modifiers);const i=function(t){if(0===t.length)return null;const e=t[0].tagName;if(!t.every(t=>t.tagName===e))return null;switch(e){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return t.map(t=>t.closest("details")).filter(t=>null!==t).length>0?"details":null;default:return null}}(s);if("dialog"===i){const r=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 s=e.toLowerCase();if("modal"===s||"as modal"===s)return"modal";if("as"===s&&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:r,targets:s}}return"details"===i?{type:"details",targets:Fs(s)}:"select"===i?{type:"select",targets:s}:{type:"classes",classes:cs(u),targets:s,duration:o,untilEvent:a}}default:{const r=cs(u||c);if(!r.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:r,targets:await Ss(t.args.slice(1),e,n,"toggle",h,t.modifiers),duration:o,untilEvent:a}}}}async execute(t,e){switch(t.type){case"classes":{const n=hs(t.classes,e);if(0===n.length)return[...t.targets];if(os(t.targets,n,(t,e)=>{t.classList.toggle(e)}),(t.duration||t.untilEvent)&&n.length)for(const e of t.targets)t.duration&&_s(e,"class",n[0],t.duration),t.untilEvent&&qs(e,"class",n[0],t.untilEvent);return[...t.targets]}case"attribute":if(n=t.name,r=t.value,is(t.targets,t=>{as(t,n,r)}),t.duration||t.untilEvent)for(const e of t.targets)t.duration&&_s(e,"attribute",t.name,t.duration),t.untilEvent&&qs(e,"attribute",t.name,t.untilEvent);return[...t.targets];case"css-property":return is(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)):Ke(e,n)}(t),n=t.property,r=n.startsWith("@")?n.substring(1):n;if("boolean"==typeof e||Ws.has(r)||Ws.has(r.toLowerCase())){const n=!e;return Gs(t,n),n}if("number"==typeof e){const n=0===e?1:0;return Gs(t,n),n}if("string"==typeof e){const r="__ht_"+n,s=t.element[r];return""===e&&void 0!==s?(Gs(t,s),s):(t.element[r]=e,Gs(t,""),"")}Gs(t,!e)}(t.target),[t.target.element];case"dialog":return is(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 is(t.targets,t=>{var e;(e=t).open=!e.open});case"select":return is(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&&_s(e,"class",t.classA,t.duration),t.untilEvent&&qs(e,"class",t.classA,t.untilEvent);return[...t.targets]}var n,r}},ns(e,"ToggleCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})());class Ks{async parseInput(t,e,n){const{targets:r}=await async function(t,e,n,r){return{targets:await Ss(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=>vs(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 Qs=(()=>{let t,e,n=[ys({description:"Show elements by restoring display property",syntax:"show [<target>]",examples:["show me","show #modal","show .hidden","show <button/>"],sideEffects:["dom-mutation"]}),ms({name:"show",category:"dom"})],r=[],s=Ks;return e=class extends s{constructor(){super(...arguments),this.mode="show"}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=>vs(t))?"string"!=typeof e.defaultDisplay?0:1:0}},ns(e,"ShowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),es(e,r)})(),e})();const ti=gs(Qs);let ei=(()=>{let t,e,n=[ys({description:"Hide elements by setting display to none",syntax:"hide [<target>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>"],sideEffects:["dom-mutation"]}),ms({name:"hide",category:"dom"})],r=[],s=Ks;return e=class extends s{constructor(){super(...arguments),this.mode="hide"}async execute(t,e){for(const e of t.targets)this.hideElement(e)}validate(t){if("object"!=typeof t||null===t)return 0;const e=t;return Array.isArray(e.targets)&&e.targets.every(t=>vs(t))?1:0}},ns(e,"HideCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:i},null,r),e=t.value,i&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:i}),es(e,r)})(),e})();const ni=gs(ei),ri=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"put",category:"dom"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("put requires arguments");const r=t=>t?.type||"unknown",s=["into","before","after","at","at start of","at end of"];let i=-1,o=null;for(let e=0;t.args.length>e;e++){const n=t.args[e],a=r(n),c="literal"===a?n.value:n.name;if(("literal"===a||"identifier"===a)&&s.includes(c)){i=e,o=c;break}}let a=null,c=null;if(-1===i)if(t.modifiers.into||t.modifiers.before||t.modifiers.after){const e=t.modifiers.into?"into":t.modifiers.before?"before":"after";a=t.args[0],o=e,c=t.modifiers[e]}else if(3>t.args.length){if(2>t.args.length)throw Error("put requires content and position");a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||"into"}else a=t.args[0],o=t.args[1]?.value||t.args[1]?.name||null,c=t.args[2];else a=t.args.slice(0,i)[0]||null,c=t.args.slice(i+1)[0]||null;if(!a)throw Error("put requires content");if(!o)throw Error("put requires position keyword");const l=await e.evaluate(a,n),u=this.mapPosition(o);let h,f,d=null;if(c){const t=r(c),s=await Zs(c,e,n);if(s)return{value:l,targets:[s.element],position:"replace",memberPath:s.property};if("memberExpression"===t){const t=c.object,r=c.property;if("selector"===t?.type)d=t.value;else if("identifier"===t?.type){const s=t.name;if("my"===s||"me"===s||"I"===s){if(n.me&&r?.name)return{value:l,targets:[n.me],position:"replace",memberPath:r.name}}else if("its"===s||"it"===s){const t=await e.evaluate(c,n);"string"==typeof t&&(d=t)}else d=s}if(d&&r?.name)h=r.name;else if(!d&&!h){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&&Js(t)){const e=zs(t,n);if(e)return{value:l,targets:[e.element],position:"replace",memberPath:e.property}}"string"==typeof t&&this.looksLikeCss(t)?d=t:f=t+""}else if("identifier"===t){const t=c.name;if(this.looksLikeCss(t))d=t;else{const r=await e.evaluate(c,n),s=this.resolveEvaluatedAsElements(r);if(s)return{value:l,targets:s,position:u,memberPath:h};f=t}}else{const t=await e.evaluate(c,n),r=this.resolveEvaluatedAsElements(t);if(r)return{value:l,targets:r,position:u,memberPath:h};"string"==typeof t&&(this.looksLikeCss(t)?d=t:f=t)}}return f?{value:l,targets:[],position:u,memberPath:h,variableName:f}:{value:l,targets:await this.resolveTargets(d,n),position:u,memberPath:h}}async execute(t,e){const{value:n,targets:r,position:s,memberPath:i,variableName:o}=t;if(o)return e.locals&&e.locals.set(o,n),e[o]=n,void Object.assign(e,{it:n});if(i)for(const t of r)this.setProperty(t,i,n);else for(const t of r){const e=this.parseValue(n);this.insertContent(t,e,s)}return r}mapPosition(t){switch(t){case"into":return"replace";case"before":return"beforebegin";case"after":return"afterend";case"at start of":return"afterbegin";case"at end of":return"beforeend";default:throw Error("Invalid position: "+t)}}async resolveTargets(t,e){if(!t||"me"===t){if(!e.me||!vs(e.me))throw Error("put: no target and context.me is null");return[e.me]}const n=Array.from(document.querySelectorAll(t)).filter(t=>vs(t));if(!n.length)throw Error(`No elements: "${t}"`);return n}parseValue(t){return vs(t)?t:null==t?"":t+""}insertContent(t,e,n){if("replace"!==n)if(vs(e)){const r=e;switch(n){case"beforebegin":t.parentElement?.insertBefore(r,t);break;case"afterbegin":t.insertBefore(r,t.firstChild);break;case"beforeend":t.appendChild(r);break;case"afterend":t.parentElement?.insertBefore(r,t.nextSibling)}}else e.includes("<")&&e.includes(">")?t.insertAdjacentHTML(n,e):t.insertAdjacentText(n,e);else vs(e)?(t.innerHTML="",t.appendChild(e)):e.includes("<")&&e.includes(">")?t.innerHTML=e:t.textContent=e}resolveEvaluatedAsElements(t){if(vs(t))return[t];if(Array.isArray(t)){const e=t.filter(vs);return e.length>0?e:null}if("undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t).filter(vs);return e.length>0?e:null}return null}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 s=t;for(let t=0;r.length-1>t;t++){if(!s[r[t]])throw Error(`Property path "${e}" does not exist`);s=s[r[t]]}s[r[r.length-1]]=n}},ns(e,"PutCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})()),si=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"set",category:"data"})],r=[];return e=class{async parseInput(t,e,n){if(!t.args?.length)throw Error("set command requires a target");const r=t.args[0],s=r?.name||r?.value,i=r?.type;if(i){const s=kt.get(i);if(s)return{type:"node-write",node:r,value:await this.extractValue(t,e,n),writer:s}}const o=await Zs(r,e,n);if(o){const r=await this.extractValue(t,e,n);if(o.property.startsWith("*")){const t=o.property.substring(1);return{type:"style",element:o.element,property:t,value:r+""}}return{type:"property",element:o.element,property:o.property,value:r}}if("memberExpression"===r?.type||"propertyAccess"===r?.type){const s=await this.tryParseMemberExpression(r,t,e,n);if(s)return s}let a;if(a="identifier"!==r?.type&&"variable"!==r?.type||"string"!=typeof s?await e.evaluate(r,n):s,function(t){if("object"!=typeof t||null===t||Array.isArray(t))return 0;if(vs(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(Js(a)){const r=zs(a,n);if(r){const s=await this.extractValue(t,e,n);return{type:"property",element:r.element,property:r.property,value:s}}return this.parseTheXofY(a,t,e,n)}if("string"==typeof a&&As(a)){const r=a.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"style",element:await this.resolveElement(t.modifiers.on,e,n),property:r,value:s+""}}if("string"==typeof a&&rs(a)){const r=a.substring(1).trim(),s=await this.extractValue(t,e,n);return{type:"attribute",element:await this.resolveElement(t.modifiers.on,e,n),name:r,value:s}}if("string"==typeof a){const r=a.match(/^(my|me|its?|your?)\s+(.+)$/i);if(r){const s=xs(r[1],n),i=await this.extractValue(t,e,n);return{type:"property",element:s,property:r[2],value:i}}}if(vs(a))return{type:"property",element:a,property:"textContent",value:await this.extractValue(t,e,n)};if(Array.isArray(a)&&a.length>0&&vs(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} — check that all intermediate objects exist)`:""));return{type:"variable",name:a,value:await this.extractValue(t,e,n)}}async execute(t,e){switch(t.type){case"variable":return function(t,e,n){if(t.startsWith("$"))Lt(n,t.slice(1),e);else{if(n.locals&&n.locals.has(t))return n.locals.set(t,e),void $t(t,e,n);if(n.globals&&n.globals.has(t))return Lt(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 Lt(n,t,e);n.locals.set(t,e),$t(t,e,n)}}}(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":return t.element.setAttribute(t.name,t.value+""),Object.assign(e,{it:t.value}),{target:"@"+t.name,value:t.value,targetType:"attribute"};case"property":return Hs(t.element,t.property,t.value),Object.assign(e,{it:t.value}),{target:t.element,value:t.value,targetType:"property"};case"style":return Cs(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))Hs(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 s=t.object,i=t.property;if(s?.name&&i?.name){const t=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(t)){const s=xs(t,r),o=await this.extractValue(e,n,r);return{type:"property",element:s,property:i.name,value:o}}}const o=t.object,a=t.computed;if(o){const s=await n.evaluate(o,r);if(null!=s&&"object"==typeof s){const o=a?await n.evaluate(t.property,r)+"":i?.name||"";if(o)return{type:"member-assignment",container:s,property:o,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 Es(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(vs);if(t instanceof NodeList)return Array.from(t).filter(vs);if(vs(t))return[t];if(!t){const t=e.me;return t&&vs(t)?[t]:[]}if("string"==typeof t){const n=t.trim();if("me"===n)return e.me&&vs(e.me)?[e.me]:[];if("it"===n)return vs(e.it)?[e.it]:[];if("you"===n)return e.you&&vs(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(vs)}}return[]}(t?await e.evaluate(t,n):void 0,n)}async parseTheXofY(t,e,n,r){const s=t.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,o]=s,a=Es(o,r),c=await this.extractValue(e,n,r);return{type:"property",element:a,property:i.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&&vs(e.element)&&"value"in e;case"property":return"string"==typeof e.property&&vs(e.element)&&"value"in e;case"style":return"string"==typeof e.property&&""!==e.property&&vs(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}}},ns(e,"SetCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})());function ii(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}const oi=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"trigger",category:"event"})],r=[];return e=class{async parseInput(t,e,n){const r="send"===t.commandName?.toLowerCase()?"send":"trigger",s=r;if(!t.args?.length)throw Error(s+" command requires an event name");const i=t=>t?.type||"unknown",o=t.args[0];let a,c,l;if("functionCall"===i(o)||"callExpression"===i(o)){a=o.name||o.callee?.name;const t=o.args||o.arguments;t?.length&&(c=await this.parseEventDetail(t,e,n))}else if("identifier"===i(o)||"keyword"===i(o))a=o.name;else{const t=await e.evaluate(o,n);a="string"==typeof t?t:t+""}const u=t.modifiers?.on||t.modifiers?.to;if(u)l=await this.resolveTargets([u],e,n,s);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 i=t.args.slice(r+1),o=i.findIndex(t=>"with"===(t.name||t.value)),a=-1===o?i:i.slice(0,o);l=await this.resolveTargets(a,e,n,s)}else{if(!n.me)throw Error(s+": no target specified and context.me is null");l=[n.me]}}return{eventName:a,detail:c,targets:l,options:await this.parseEventOptions(t.args,e,n),mode:r}}async execute(t,e){const n=function(t,e,n={}){return new CustomEvent(t,{detail:void 0!==e?e:{},bubbles:void 0!==n.bubbles?n.bubbles: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 s=[];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)s.push(n.me);else if("you"===t&&n.you)s.push(n.you);else if("it"===t&&n.it)s.push(n.it);else if(vs(t))s.push(t);else if(t instanceof NodeList)s.push(...Array.from(t).filter(vs));else if(Array.isArray(t))s.push(...t.filter(vs));else{if("string"==typeof t){const e=document.querySelectorAll(t);if(0===e.length)throw Error(`No elements found: "${t}"`);s.push(...Array.from(e).filter(vs));continue}if(!t||"object"!=typeof t||!("addEventListener"in t))throw Error("Invalid target: "+typeof t);s.push(t)}else s.push(document);else s.push(window)}if(!s.length)throw Error(r+": no valid targets");return s}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 s of t){const t=await e.evaluate(s,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()]=ii(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},s=t.findIndex(t=>"with"===(t.name||t.value));if(-1===s)return r;for(const i of t.slice(s+1)){const t=await e.evaluate(i,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}},ns(e,"EventDispatchCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})()),ai=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"log",category:"utility"})],r=[];return e=class{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)}},ns(e,"LogCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})());function ci(t,e,n,r){return t?new Promise(n=>{const s=()=>{i({event:null,timedOut:0,cancelled:1})},i=function(n,i){let a=0;return n=>{a||(a=1,t.removeEventListener(e,o),r&&r.removeEventListener("abort",s),i(n))}}(0,n),o=t=>{i({event:t,timedOut:0,cancelled:0})};r?.aborted?n({event:null,timedOut:0,cancelled:1}):(t.addEventListener(e,o),r&&r.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function li(t){return new Promise(e=>setTimeout(e,t))}const ui=gs((()=>{let t,e,n=[ys({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"]}),ms({name:"wait",category:"async"})],r=[];return e=class{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 li(t.milliseconds),{type:"time",result:t.milliseconds,duration:Date.now()-n};if("event"===t.type){const r=t.target??e.me??document,s=(await ci(r,t.eventName)).event;if(Object.assign(e,{it:s}),t.destructure)for(const n of t.destructure)n in s&&e.locals.set(n,s[n]);return{type:"event",result:s,duration:Date.now()-n}}const{result:r,winningCondition:s}=await this.executeRace(t.conditions,e);if(Object.assign(e,{it:r}),r instanceof Event&&"event"===s?.type&&s.destructure)for(const t of s.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:Bs(await e.evaluate(t,n))}}async parseEventWait(t,e,n,r){const s=await n.evaluate(t,r);if("string"!=typeof s)throw Error("wait for: event name must be a string");const i=s.match(/^(\w+)\(([^)]+)\)$/),o=i?i[1]:s,a=i?i[2].split(",").map(t=>t.trim()):void 0;let c;if(e){const t=await 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){const s=[];for(const e of t){const t=e;if("objectLiteral"===t.type&&t.properties){let e="",n=[];for(const r of t.properties){const t=r.key?.name||r.key?.value;"name"===t&&r.value?e=r.value.value||"":"args"===t&&r.value?.elements&&(n=r.value.elements.map(t=>t.value||t.name||""))}e&&s.push({name:e,params:n})}}let i;if(e){const t=await n.evaluate(e,r);t&&"object"==typeof t&&"addEventListener"in t&&(i=t)}return i||(i=r.me??void 0),1===s.length?{type:"event",eventName:s[0].name,target:i,destructure:s[0].params.length>0?s[0].params:void 0}:{type:"race",conditions:s.map(t=>({type:"event",eventName:t.name,target:i,destructure:t.params.length>0?t.params:void 0}))}}async parseRaceCondition(t,e,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 s=await e.evaluate(t.modifiers.or,n),i=Array.isArray(s)?s:[s];for(const t of i)try{r.push({type:"time",milliseconds:Bs(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,s=t.map(t=>"time"===t.type?li(t.milliseconds).then(()=>({result:t.milliseconds,winningCondition:t})):ci(t.target??e.me??document,t.eventName,0,r).then(e=>({result:e.event,winningCondition:t})));try{return await Promise.race(s)}finally{n.abort()}}},ns(e,"WaitCommand"),(()=>{const s="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;ts(null,t={value:e},n,{kind:"class",name:e.name,metadata:s},null,r),e=t.value,s&&Object.defineProperty(e,Symbol.metadata,{enumerable:1,configurable:1,writable:1,value:s}),es(e,r)})(),e})()),hi=function(t,e){const n=new xn(null);for(const e of t)n.register(e);return new Rn({registry:n,expressionRegistry:e.expressionRegistry,enableAsyncCommands:e.enableAsyncCommands??1,commandTimeout:e.commandTimeout??1e4,enableErrorReporting:e.enableErrorReporting??1,enableResultPattern:e.enableResultPattern??1})}([Is(),Ms(),Ys(),ti(),ni(),ri(),si(),oi(),ai(),ui()],{expressionRegistry:Kr()}),fi={parse:t=>Me(t),execute:async(t,e)=>{const n=function(t){if(!t)return yn();if(t.locals instanceof Map&&t.globals instanceof Map&&t.flags)return t;const e=yn(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=Me(t);if(!r.success||!r.node)throw Error(r.error?.message||"Parse failed");return await hi.execute(r.node,n)}},di=function(t){return new Qr(t)}(fi),pi={runtime:fi,parse:t=>fi.parse(t),execute:async(t,e)=>fi.execute(t,e),createContext:yn,attributeProcessor:di,version:"1.1.0-minimal-v2-tree-shakeable",commands:["add","remove","toggle","show","hide","put","set","send","log","wait"],eval:async(t,e)=>fi.execute(t,e),init:()=>{di.init()}};function mi(t,e,n,r,s="runtime-error"){return{success:0,error:{name:t+"ConversionError",type:s,message:n,code:e,suggestions:r}}}function yi(t,e){return{success:1,value:t,type:e}}function gi(t,e){return`${t}: ${e instanceof Error?e.message:e+""}`}"undefined"!=typeof window&&(window.hyperfixi=pi,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{di.init()}):di.init());const vi={Array:(t,e)=>{try{return Array.isArray(t)?yi(t,"array"):t instanceof NodeList?yi(Array.from(t),"array"):yi(null==t?[]:[t],"array")}catch(t){return mi("Array","ARRAY_CONVERSION_FAILED",gi("Failed to convert value to Array",t),["Check if value is iterable","Ensure value is not circular reference"])}},String:(t,e)=>{try{return null==t?yi("","string"):He(t)?yi(t,"string"):Je(t)?yi(JSON.stringify(t),"string"):yi(t+"","string")}catch(t){return mi("String","STRING_CONVERSION_FAILED",gi("Failed to convert value to String",t),["Check if object has circular references","Ensure value is serializable"])}},Boolean:(t,e)=>{try{if(We(t))return yi(t,"boolean");if(null==t)return yi(0,"boolean");if(He(t)){const e=t.toLowerCase().trim();return yi("false"!==e&&"0"!==e&&""!==e,"boolean")}return Ue(t)?yi(0!==t&&!isNaN(t),"boolean"):yi(!!t,"boolean")}catch(t){return mi("Boolean","BOOLEAN_CONVERSION_FAILED",gi("Failed to convert value to Boolean",t),["Use explicit true/false values","Check for unexpected data types"])}},Number:(t,e)=>{try{if(Ue(t))return yi(t,"number");if(null==t)return yi(0,"number");const e=Number(t);return isNaN(e)?mi("Number","INVALID_NUMBER",`Cannot convert "${t}" to a valid number`,["Check if value contains non-numeric characters","Use a valid numeric format"],"invalid-argument"):yi(e,"number")}catch(t){return mi("Number","NUMBER_CONVERSION_FAILED",gi("Failed to convert value to Number",t),["Ensure value is convertible to number","Check for special characters"])}},Int:(t,e)=>{const n=vi.Number(t,e);return n.success?yi(Math.trunc(n.value),"number"):n},Float:(t,e)=>{const n=vi.Number(t,e);return n.success?yi(parseFloat(""+n.value),"number"):n},Date:(t,e)=>{try{if(t instanceof Date)return yi(t,"object");if(null==t)return yi(new Date(""),"object");if(He(t)&&/^\d{4}-\d{2}-\d{2}$/.test(t)){const[e,n,r]=t.split("-").map(Number);return yi(new Date(e,n-1,r),"object")}const e=new Date(t);return isNaN(e.getTime())?mi("Date","INVALID_DATE",`Cannot convert "${t}" to a valid date`,["Use ISO 8601 format (YYYY-MM-DD)","Check date string format","Ensure date values are valid"],"invalid-argument"):yi(e,"object")}catch(t){return mi("Date","DATE_CONVERSION_FAILED",gi("Failed to convert value to Date",t),["Check date format","Ensure value is a valid date string or timestamp"])}},JSON:(t,e)=>{if(!He(t))return yi(t,"object");try{return yi(JSON.parse(t),"object")}catch(t){return mi("JSON","JSON_PARSE_FAILED",gi("Failed to parse value as JSON",t),["Check JSON syntax and escaping","Use `as JSONString` to stringify a value instead"],"syntax-error")}},JSONString:(t,e)=>{try{return yi(JSON.stringify(t),"string")}catch(t){return mi("JSONString","JSON_STRINGIFY_FAILED",gi("Failed to stringify value as JSON",t),["Check for circular references","Ensure all properties are serializable","Remove functions and undefined values"])}},Object:(t,e)=>{try{if(Je(t))return yi(t,"object");if(He(t))try{return yi(JSON.parse(t),"object")}catch(t){return mi("Object","JSON_PARSE_FAILED",gi("Cannot parse JSON string",t),["Check JSON syntax","Ensure proper escaping of quotes","Validate JSON format"],"syntax-error")}return yi({},"object")}catch(t){return mi("Object","OBJECT_CONVERSION_FAILED",gi("Failed to convert value to Object",t),["Ensure value is valid JSON string or object","Check for syntax errors"])}},Values:(t,e)=>{try{if(t instanceof HTMLFormElement)return yi(xi(t),"object");if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{const e=t;if(e.name){const t=ki(e);void 0!==t&&(n[e.name]=t)}}),yi(n,"object")}return yi({},"object")}catch(t){return mi("FormValues","FORM_VALUES_EXTRACTION_FAILED",gi("Failed to extract form values",t),["Ensure element is a form or contains form inputs","Check form structure","Verify input names are set"])}},FormEncoded:(t,e)=>{try{let n=t;if(t instanceof HTMLElement){const r=vi.Values(t,e);if(!r.success)return r;n=r.value}if(!Je(n))return yi("","string");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 yi(""+r,"string")}catch(t){return mi("FormEncoded","FORM_ENCODE_FAILED",gi("Failed to URL-encode values",t),["Ensure input is a form element or plain object of scalar/array values"])}}},bi=Gn({value:Kn(),type:Jn().min(1)}),Ei=Gn({value:Kn(),type:Jn().min(1)});new class extends tr{constructor(){super(...arguments),this.name="as",this.category="Conversion",this.syntax="value as Type",this.description='Converts values between different types using the "as" keyword',this.outputType="Any",this.inputSchema=bi,this.metadata={category:"Conversion",complexity:"medium",sideEffects:[],dependencies:[],returnTypes:["Any"],examples:[{input:'"123" as Int',description:"Convert string to integer",expectedOutput:123},{input:"form as Values",description:"Extract form values as object",expectedOutput:{name:"John",age:"25"}},{input:"[1,2,3] as JSONString",description:"Convert array to JSON string (upstream 0.9.90: use JSONString, not JSON)",expectedOutput:"[1,2,3]"},{input:"'{\"a\":1}' as JSON",description:"Parse a JSON string (upstream 0.9.90: as JSON now parses)",expectedOutput:{a:1}},{input:'"2023-12-25" as Date',description:"Parse date string",expectedOutput:new Date(2023,11,25)}],relatedExpressions:["is","Object","Array"],performance:{averageTime:1,complexity:"O(n)"}},this.documentation={summary:'Converts values between different types using the "as" keyword with comprehensive type safety',parameters:[{name:"value",type:"object",description:"The value to convert",optional:0,examples:['"123"',"form","[1,2,3]","true","null"]},{name:"type",type:"string",description:"Target conversion type",optional:0,examples:["Int","String","Boolean","Array","JSON","Object","Date","Values","HTML","Fragment"]}],returns:{type:"object",description:"Structured result with converted value or detailed error information",examples:['{ success: true, value: 123, type: "number" }',"{ success: false, error: { ... } }"]},examples:[{title:"String to number conversion",code:"if my.value as Int > 100",explanation:"Convert form input to integer for comparison",output:"Boolean result"},{title:"Form data extraction",code:"put closest <form /> as Values into result",explanation:"Extract all form values as structured object",output:'{ name: "John", age: "25", ... }'},{title:"Array to JSON serialization",code:"put items as JSONString into storage",explanation:"Convert array to JSON string for storage (upstream 0.9.90: use `as JSONString`)",output:'"[1,2,3]"'},{title:"Date parsing with validation",code:"put my.dateInput as Date into event.detail.date",explanation:"Parse date input with automatic validation",output:"Date object or validation error"},{title:"Boolean conversion with smart parsing",code:'if "false" as Boolean then hide else show',explanation:"Parse string boolean values correctly",output:"false (not true like naive conversion)"}],seeAlso:["is","Values","JSON","Array","Object"],tags:["conversion","types","validation","forms","json","parsing"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"AsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e;if(i.startsWith("Fixed")){const r=i.match(/^Fixed:(\d+)$/),o=r?parseInt(r[1],10):2,a=vi.Number(s,t);if(!a.success)return a;const c={success:1,value:a.value.toFixed(o),type:"string"};return this.trackPerformance(t,e,c,n),c}let o=vi[i];if(o){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const a={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[i.toLowerCase()];if(a&&(o=vi[a],o)){const r=o(s,t);return this.trackPerformance(t,e,r,n),r}const c={success:0,error:{name:"UnknownConversionTypeError",type:"validation-error",message:"Unknown conversion type: "+i,code:"UNKNOWN_CONVERSION_TYPE",suggestions:["Use supported types: String, Number, Boolean, Array, Object, Date, JSON, Values","Check type spelling and capitalization","See documentation for complete list of conversion types"]}};return this.trackPerformance(t,e,c,n),c}catch(r){const s={success:0,error:{name:"AsExpressionError",type:"runtime-error",message:"Conversion failed: "+(r instanceof Error?r.message:r+""),code:"CONVERSION_FAILED",suggestions:["Check value and type compatibility","Ensure value is convertible to target type"]}};return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}},new class extends tr{constructor(){super(...arguments),this.name="is",this.category="Conversion",this.syntax="value is Type",this.description="Checks if a value is of a specific type",this.outputType="Boolean",this.inputSchema=Ei,this.metadata={category:"Conversion",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"42 is number",description:"Check if value is a number",expectedOutput:1},{input:"null is empty",description:"Check if value is empty/null",expectedOutput:1},{input:"element is Element",description:"Check if value is DOM element",expectedOutput:1,context:{element:"<div>...</div>"}}],relatedExpressions:["as","empty","exists"],performance:{averageTime:.1,complexity:"O(1)"}},this.documentation={summary:"Checks if a value is of a specific type with comprehensive type detection",parameters:[{name:"value",type:"object",description:"The value to check",optional:0,examples:["42","null","element",'"text"',"[]"]},{name:"type",type:"string",description:"Type name to check against",optional:0,examples:["number","string","boolean","array","object","element","empty","null"]}],returns:{type:"object",description:"Boolean result indicating type match",examples:['{ success: true, value: true, type: "boolean" }']},examples:[{title:"Number validation",code:"if my.age is number then proceed",explanation:"Check if form input is valid number",output:"Boolean result"},{title:"Empty check",code:"if result is empty then show message",explanation:"Check if result is null, undefined, or empty",output:"Boolean result"},{title:"Element validation",code:"if target is element then addClass",explanation:"Ensure target is valid DOM element before manipulation",output:"Boolean result"}],seeAlso:["as","empty","exists","null"],tags:["validation","types","checking","guards"]}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:{name:"IsExpressionValidationError",type:"validation-error",message:r.errors[0]?.message||"Invalid input",code:"VALIDATION_FAILED",suggestions:r.suggestions}};const{value:s,type:i}=e,o=i.toLowerCase();let a;switch(o){case"null":a=null===s;break;case"undefined":a=void 0===s;break;case"string":a=He(s);break;case"number":a=Ue(s)&&!isNaN(s);break;case"boolean":a=We(s);break;case"object":a=Je(s);break;case"array":a=Array.isArray(s);break;case"function":a=ze(s);break;case"date":a=s instanceof Date;break;case"element":a=s instanceof Element;break;case"node":a=s instanceof Node;break;case"node-list":a=s instanceof NodeList;break;case"empty":a=null==s||""===s||Array.isArray(s)&&0===s.length||Je(s)&&0===Object.keys(s).length;break;default:a=s?.constructor?.name?.toLowerCase()===o}const c=this.success(a,"boolean");return this.trackPerformance(t,e,c,n),c}catch(r){const s=this.failure("IsExpressionError","type-mismatch","Type check failed: "+(r instanceof Error?r.message:r+""),"TYPE_CHECK_FAILED",["Check type name spelling","Ensure value is accessible"]);return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:t.message,suggestions:["Expected valid input structure, got: "+t.code]}))??[],suggestions:["Provide both value and type parameters","Ensure type is a non-empty string","Check parameter structure: { value: any, type: string }"]}}catch(t){return this.validationFailure("runtime-error","Validation failed",["Check input structure"])}}};const wi={Array:t=>Array.isArray(t)?t:t instanceof NodeList?Array.from(t):null==t?[]:[t],String:t=>null==t?"":He(t)?t:Je(t)?JSON.stringify(t):t+"",Boolean:t=>{if(We(t))return t;if(null==t)return 0;if(He(t)){const e=t.toLowerCase().trim();return"false"===e||"0"===e||""===e?0:1}return Ue(t)?0!==t&&!isNaN(t):!!t},Number:t=>{if(Ue(t))return t;if(null==t)return 0;const e=Number(t);return isNaN(e)?0:e},Math:t=>{if(Ue(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(!Ue(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=wi.Number(t);return Math.trunc(e)},Float:t=>{const e=wi.Number(t);return parseFloat(""+e)},Date:t=>{if(t instanceof Date)return t;if(null==t)return new Date(NaN);if(He(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(!He(t))return t;try{return JSON.parse(t)}catch{return t}},JSONString:t=>{try{return JSON.stringify(t)}catch{return"{}"}},Object:t=>{if(Je(t))return t;if(He(t))try{return JSON.parse(t)}catch(t){return{}}return{}},Fragment:t=>{He(t)||(t=wi.String(t));const e=document.createElement("template");return e.innerHTML=t+"",e.content},HTML:t=>He(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:wi.String(t)).join(""):t instanceof Element?t.outerHTML:wi.String(t),Values:(t,e)=>{if(t instanceof HTMLFormElement)return xi(t);if(t instanceof HTMLElement){const e=t.querySelectorAll("input, select, textarea"),n={};return e.forEach(t=>{t.name&&(n[t.name]=ki(t))}),n}return{}},FormEncoded:(t,e)=>{const n=t instanceof HTMLElement?wi.Values(t,e):t;if(!Je(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},"Values:Form":(t,e)=>{const n=wi.Values(t,e);return wi.FormEncoded(n,e)},"Values:JSON":(t,e)=>{const n=wi.Values(t,e);return JSON.stringify(n)}};function xi(t){const e={};return t.querySelectorAll("input, select, textarea").forEach(t=>{const n=t;if(n.name){const t=ki(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}function ki(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 Si={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(t,...e){const[n,r]=e;if("string"!=typeof r)throw Error("Conversion type must be a string");if(r.startsWith("Fixed")){const{precision:t}=function(t){const e=t.match(/^Fixed(?::(\d+))?$/);return e?{precision:e[1]?parseInt(e[1],10):2}:{}}(r);return wi.Number(n).toFixed(t||2)}let s=wi[r];if(s)return s(n,t);const i={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"}[r.toLowerCase()];return i&&(s=wi[i],s)?s(n,t):(console.warn("Unknown conversion type: "+r),n)},validate:t=>jn(t,2,"as","value, type")??Dn(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(!He(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 He(n);case"number":return Ue(n)&&!isNaN(n);case"boolean":return We(n);case"object":return Je(n);case"array":return Array.isArray(n);case"function":return ze(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||Je(n)&&0===Object.keys(n).length;default:return n?.constructor?.name?.toLowerCase()===r.toLowerCase()}},validate:t=>jn(t,2,"is","value, type")??Dn(t,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(t,e)=>e,validate:t=>jn(t,1,"async","expression")}},Ai={String:"string",Number:"number",Boolean:"boolean",Element:"element",ElementList:"element-list",Array:"array",Object:"object",Promise:"promise",Context:"object",Null:"null",Undefined:"undefined",Any:"object"},Ni=Gn({collection:Yn().describe("Collection to operate on (array, NodeList, or string)")}).strict(),Ci=Gn({collection:Yn().describe("Collection to access"),index:zn().describe("Index position to access")}).strict(),Ti=Gn({collection:Yn().describe("Collection to select random item from")}).strict();new class extends tr{constructor(){super(...arguments),this.name="first",this.category="Positional",this.syntax="first in collection",this.description="Gets the first element from a collection",this.inputSchema=Ni,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[0]:void 0,o={success:1,value:i,type:Ai[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("FirstExpressionError","runtime-error","First operation failed: "+(r instanceof Error?r.message:r+""),"FIRST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid first input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends tr{constructor(){super(...arguments),this.name="last",this.category="Positional",this.syntax="last in collection",this.description="Gets the last element from a collection",this.inputSchema=Ni,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=s.length>0?s[s.length-1]:void 0,o={success:1,value:i,type:Ai[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("LastExpressionError","runtime-error","Last operation failed: "+(r instanceof Error?r.message:r+""),"LAST_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid last input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}},new class extends tr{constructor(){super(...arguments),this.name="at",this.category="Positional",this.syntax="collection[index] or collection at index",this.description="Gets element at specific index from a collection",this.inputSchema=Ci,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection),i=this.normalizeIndex(e.index,s.length),o=i>=0&&s.length>i?s[i]:void 0,a={success:1,value:o,type:Ai[this.inferEvaluationType(o)]};return this.trackPerformance(t,e,a,n),a}catch(r){const s=this.failure("AtExpressionError","runtime-error","At operation failed: "+(r instanceof Error?r.message:r+""),"AT_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid at input: "+t.message,suggestions:[]}))??[],suggestions:["Provide collection and index parameters","Ensure index is a number"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}normalizeIndex(t,e){return 0>t?e+t:t}},new class extends tr{constructor(){super(...arguments),this.name="random",this.category="Positional",this.syntax="random in collection",this.description="Gets a random element from a collection",this.inputSchema=Ti,this.outputType="Any",this.metadata={category:"Positional",complexity:"simple"}}async evaluate(t,e){const n=Date.now();try{const r=this.validate(e);if(!r.isValid)return{success:0,error:r.errors[0]};const s=this.normalizeCollection(e.collection);if(0===s.length){const r={success:1,value:void 0,type:"undefined"};return this.trackPerformance(t,e,r,n),r}const i=s[this.getSecureRandomIndex(s.length)],o={success:1,value:i,type:Ai[this.inferEvaluationType(i)]};return this.trackPerformance(t,e,o,n),o}catch(r){const s=this.failure("RandomExpressionError","runtime-error","Random operation failed: "+(r instanceof Error?r.message:r+""),"RANDOM_OPERATION_FAILED");return this.trackPerformance(t,e,s,n),s}}validate(t){try{const e=this.inputSchema.safeParse(t);return e.success?this.validationSuccess():{isValid:0,errors:e.error?.errors.map(t=>({type:"type-mismatch",message:"Invalid random input: "+t.message,suggestions:[]}))??[],suggestions:["Provide a collection parameter","Ensure collection is array, NodeList, or string"]}}catch(t){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}getSecureRandomIndex(t){if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]%t}return Math.floor(Math.random()*t)}};const Oi={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:He(n)?n.length>0?n[0]:null:Je(n)&&"length"in n&&Ue(n.length)&&n.length>0?n[0]:null},validate:t=>Fn(t,1,"first","collection")},$i={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 He(n)?n.length>0?n[n.length-1]:null:Je(n)&&"length"in n&&Ue(n.length)&&n.length>0?n[n.length-1]:null},validate:t=>Fn(t,1,"last","collection")},Ri={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(t,...e){const[n,r]=e;if(!Ue(n))throw Error("Index must be a number");const s=n,i=void 0!==r?r:t.it;if(null==i)return null;if(Array.isArray(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(i instanceof Element){const t=i.children,e=0>s?t.length+s:s;return e>=0&&t.length>e?t[e]:null}if(He(i)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}if(Je(i)&&"length"in i&&Ue(i.length)){const t=0>s?i.length+s:s;return t>=0&&i.length>t?i[t]:null}return null},validate:t=>Vn(t,1,2,"at","index, optional collection")??function(t){return"number"!=typeof t[0]?"at index must be a number":null}(t)};function Li(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?Li(r,e):null}function Ii(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?Ii(r,e):null}function ji(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 Di={first:Oi,last:$i,at:Ri,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(t,...e){const[n,r]=e,s=r||t.me;return s&&s instanceof Element?n?Li(s,n):s.nextElementSibling:null},validate:t=>Fn(t,2,"next","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},previous:{name:"previous",category:"Reference",evaluatesTo:"Element",operators:["previous","prev"],async evaluate(t,...e){const[n,r]=e,s=r||t.me;return s&&s instanceof Element?n?Ii(s,n):s.previousElementSibling:null},validate:t=>Fn(t,2,"previous","optional selector, optional fromElement")||(1>t.length||null==t[0]||"string"==typeof t[0]?2>t.length||null==t[1]||t[1]instanceof Element?null:"fromElement must be an Element":"selector must be a string")},nextWithin:{name:"nextWithin",category:"Reference",evaluatesTo:"Element",operators:["next within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=ji(t);for(const t of r)if(ji(t)>s)return t;return null}(i,n,o):null},validate:t=>Vn(t,2,3,"nextWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(t,...e){const[n,r,s]=e,i=s||t.me;if(!(i&&i instanceof Element))return null;const o=i.closest(r);return o?function(t,e,n){const r=Array.from(n.querySelectorAll(e)),s=ji(t);for(let t=r.length-1;t>=0;t--){const e=r[t];if(s>ji(e))return e}return null}(i,n,o):null},validate:t=>Vn(t,2,3,"previousWithin","selector, withinSelector, optional fromElement")||("string"!=typeof t[0]?"selector must be a string":"string"!=typeof t[1]?"withinSelector must be a string":3>t.length||null==t[2]||t[2]instanceof Element?null:"fromElement must be an Element")}},Mi=new Set(["__proto__","constructor","prototype"]),Pi={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");if(n instanceof Element)return Ke(n,r);if(Je(n)){if(Mi.has(r))return;return n[r]}return n[r]}},validate:t=>jn(t,2,"possessive","element, property")??Dn(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 Ke(t.me,n);if(Je(t.me)){if(Mi.has(n))return;return t.me[n]}return t.me[n]}},validate:t=>Mn(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 Ke(r,n);if(Je(r)){if(Mi.has(n))return;return r[n]}return r[n]},validate:t=>Mn(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 Ke(t.you,n);if(Je(t.you)){if(Mi.has(n))return;return t.you[n]}return t.you[n]}},validate:t=>Mn(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 Ke(r,n);if(Je(r)){if(Mi.has(n))return;return r[n]}return r[n]}},validate:t=>jn(t,2,"of","property, object")??Dn(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 s=r||t.me;return s&&s instanceof Element?s.getAttribute(n):null},validate:t=>Vn(t,1,2,"attribute","attributeName, optional element")??Dn(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,s]=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 i=s||t.me;return i&&i instanceof Element?i.getAttribute(n)===r:0},validate:t=>Vn(t,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Dn(t,0,"attributeWithValue","attribute name")??Dn(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,s=document.getElementsByClassName(r);return Array.from(s)},validate:t=>Mn(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=>Mn(t,"idReference","idValue")}};class Bi{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:ur(cr(t,"left operand")+cr(n,"right operand"),"addition"),type:"number"}}catch(t){return{success:0,errors:[mr("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 pr([mr("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof t)return pr([mr("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"),pr([mr("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 hr(n)?hr(r)?{isValid:1,errors:[],suggestions:[]}:{isValid:0,errors:[mr("type-mismatch","Right operand cannot be converted to number: "+r)],suggestions:["Provide a numeric value for right operand"]}:{isValid:0,errors:[mr("type-mismatch","Left operand cannot be converted to number: "+n)],suggestions:["Provide a numeric value for left operand"]}}}const Fi={addition:new Bi,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:ur(cr(t,"left operand")-cr(n,"right operand"),"subtraction"),type:"number"}}catch(t){return{success:0,errors:[mr("runtime-error","Subtraction failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Bi).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:ur(cr(t,"left operand")*cr(n,"right operand"),"multiplication"),type:"number"}}catch(t){return{success:0,errors:[mr("runtime-error","Multiplication failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Bi).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}(cr(t,"left operand"),cr(n,"right operand"),1);return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[mr("runtime-error","Division failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Bi).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}(cr(t,"left operand"),cr(n,"right operand"));return{success:1,value:r,type:"number"}}catch(t){return{success:0,errors:[mr("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 Bi).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=cr(t,"left operand"),s=cr(n,"right operand");return{success:1,value:ur(Math.pow(r,s),"power"),type:"number"}}catch(t){return{success:0,errors:[mr("runtime-error","Power failed: "+(t instanceof Error?t.message:t+""))],suggestions:["Ensure both operands are numeric"]}}}validate(t){return(new Bi).validate(t)}}};var Vi=Object.freeze({__proto__:null,conversion:Si,conversionExpressions:Si,createCommonRegistry:function(){return Ln(nr,Jr,Yr,Si,Di)},createCoreRegistry:Kr,createExpressionRegistry:Ln,createFullExpressionRegistry:function(){return Ln(nr,Jr,Si,Di,Pi,Yr,Fi)},createFullRegistry:function(){return Ln(nr,Jr,Yr,Si,Di,Pi)},logical:Jr,logicalExpressions:Jr,positional:Di,positionalExpressions:Di,properties:Pi,propertiesExpressions:Pi,references:nr,referencesExpressions:nr,special:Yr,specialExpressions:Yr});return pi}();