@hyperfixi/core 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/api/hyperscript-api.d.ts +2 -0
  2. package/dist/ast-utils/{index.js → index.cjs} +1 -1
  3. package/dist/behaviors/{index.js → index.cjs} +1 -1
  4. package/dist/bundle-generator/{index.js → index.cjs} +1 -1
  5. package/dist/chunks/bridge-D7qrHhV0.js +2 -0
  6. package/dist/chunks/browser-modular-C4LFxfoS.js +2 -0
  7. package/dist/chunks/index-C7lqD4mo.js +2 -0
  8. package/dist/commands/{index.js → index.cjs} +39 -1
  9. package/dist/commands/index.mjs +38 -0
  10. package/dist/dom/attribute-processor.d.ts +35 -1
  11. package/dist/dom/detect-language.d.ts +3 -0
  12. package/dist/expressions/{index.js → index.cjs} +1 -1
  13. package/dist/hyperfixi-browser-classic-i18n.js +1 -1
  14. package/dist/hyperfixi-browser.js +1 -1
  15. package/dist/hyperfixi-classic-i18n.js +1 -1
  16. package/dist/hyperfixi-hx-v4.js +1 -1
  17. package/dist/hyperfixi-multilingual.js +1 -1
  18. package/dist/hyperfixi.js +1 -1
  19. package/dist/hyperfixi.mjs +1 -1
  20. package/dist/index.cjs +28495 -0
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.min.js +1 -1
  23. package/dist/index.mjs +630 -57829
  24. package/dist/lokascript-browser-classic-i18n.js +1 -1
  25. package/dist/lokascript-browser.js +1 -1
  26. package/dist/lokascript-multilingual.js +1 -1
  27. package/dist/lse/{index.js → index.cjs} +1 -1
  28. package/dist/{lsp-metadata.js → lsp-metadata.cjs} +1 -1
  29. package/dist/{metadata.js → metadata.cjs} +2 -2
  30. package/dist/metadata.d.ts +1 -1
  31. package/dist/metadata.mjs +1 -1
  32. package/dist/multilingual/bridge.d.ts +2 -0
  33. package/dist/multilingual/{index.js → index.cjs} +3 -105
  34. package/dist/multilingual/index.mjs +1 -103
  35. package/dist/parser/{full-parser.js → full-parser.cjs} +39 -1
  36. package/dist/parser/full-parser.mjs +38 -0
  37. package/dist/parser/hybrid/{aliases.js → aliases.cjs} +1 -1
  38. package/dist/parser/hybrid/ast-types.cjs +3 -0
  39. package/dist/parser/hybrid/{index.js → index.cjs} +1 -1
  40. package/dist/parser/hybrid/{parser-core.js → parser-core.cjs} +1 -1
  41. package/dist/parser/hybrid/{tokenizer.js → tokenizer.cjs} +1 -1
  42. package/dist/parser/{hybrid-parser.js → hybrid-parser.cjs} +1 -1
  43. package/dist/parser/{regex-parser.js → regex-parser.cjs} +1 -1
  44. package/dist/parser/semantic-integration.d.ts +15 -0
  45. package/dist/reference/{index.js → index.cjs} +1 -1
  46. package/dist/registry/{browser-types.js → browser-types.cjs} +1 -1
  47. package/dist/registry/{environment.js → environment.cjs} +1 -1
  48. package/dist/registry/{index.js → index.cjs} +39 -1
  49. package/dist/registry/index.mjs +38 -0
  50. package/dist/registry/{universal-types.js → universal-types.cjs} +1 -1
  51. package/dist/runtime/runtime-base.d.ts +1 -0
  52. package/dist/runtime/runtime.d.ts +1 -0
  53. package/dist/version.d.ts +1 -1
  54. package/package.json +28 -28
  55. package/dist/api/dom-processor.d.ts +0 -21
  56. package/dist/chunks/bridge-8SRzBI2K.js +0 -2
  57. package/dist/chunks/browser-modular-L1qgqF_N.js +0 -2
  58. package/dist/chunks/index-SorDzXmq.js +0 -2
  59. package/dist/index.js +0 -85694
  60. package/dist/parser/hybrid/ast-types.js +0 -3
@@ -1,2 +0,0 @@
1
- function e(e){return{ok:!0,value:e}}function t(e){return{ok:!1,error:e}}function r(e){return!0===e.ok}const n=[{name:"add",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"append",category:"content",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"beep",category:"utility",tier:"full",upstreamOrExtension:"extension",multiword:!1},{name:"blur",category:"execution",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"break",category:"control-flow",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"breakpoint",category:"utility",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"call",category:"execution",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"clear",category:"data",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"close",category:"dom",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"continue",category:"control-flow",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"copy",category:"utility",tier:"full",upstreamOrExtension:"extension",multiword:!1},{name:"decrement",category:"data",tier:"lite-plus",upstreamOrExtension:"upstream",consolidationAliasOf:"increment",multiword:!1},{name:"default",category:"data",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"empty",category:"dom",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"exit",category:"control-flow",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"fetch",category:"async",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"focus",category:"execution",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"get",category:"data",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"go",category:"navigation",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!0},{name:"halt",category:"control-flow",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"hide",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"if",category:"control-flow",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"increment",category:"data",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"install",category:"behaviors",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"js",category:"advanced",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"log",category:"utility",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1},{name:"make",category:"dom",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"measure",category:"animation",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"morph",category:"dom",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"open",category:"dom",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"pick",category:"utility",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"prepend",category:"content",tier:"hybrid",upstreamOrExtension:"extension",multiword:!1},{name:"process",category:"dom",tier:"full",upstreamOrExtension:"extension",multiword:!0},{name:"pseudo-command",category:"execution",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"push",category:"navigation",tier:"hybrid",upstreamOrExtension:"extension",multiword:!0},{name:"put",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"remove",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"render",category:"templates",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"repeat",category:"control-flow",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!1},{name:"replace",category:"navigation",tier:"hybrid",upstreamOrExtension:"extension",consolidationAliasOf:"push",multiword:!0},{name:"reset",category:"dom",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"return",category:"control-flow",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"scroll",category:"navigation",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"select",category:"dom",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"send",category:"event",tier:"hybrid",upstreamOrExtension:"upstream",consolidationAliasOf:"trigger",multiword:!0},{name:"set",category:"data",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"settle",category:"animation",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"show",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"start",category:"animation",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"swap",category:"dom",tier:"hybrid",upstreamOrExtension:"upstream",multiword:!0},{name:"take",category:"animation",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"tell",category:"utility",tier:"full",upstreamOrExtension:"upstream",multiword:!0},{name:"throw",category:"control-flow",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"toggle",category:"dom",tier:"lite",upstreamOrExtension:"upstream",multiword:!0},{name:"transition",category:"animation",tier:"full",upstreamOrExtension:"upstream",multiword:!1},{name:"trigger",category:"event",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!0},{name:"unless",category:"control-flow",tier:"full",upstreamOrExtension:"extension",consolidationAliasOf:"if",multiword:!1},{name:"wait",category:"async",tier:"lite-plus",upstreamOrExtension:"upstream",multiword:!1}],s="then",i="else",a="end",o="and",c="if",l="for",u="while",d="until",m="forever",p="times",h="each",f="index",y="in",g="to",v="from",b="with",w="of",E="by",k="between",x="on",C="when",A="event",S="def",T="behavior",L="global",O="local",N="the",P="start",I=[s,o,i,a,x],j=new Set(["add","append","beep","blur","break","breakpoint","call","clear","close","continue","copy","decrement","default","empty","exit","fetch","focus","get","go","halt","hide","if","increment","install","js","log","make","measure","morph","open","pick","prepend","process","pseudo-command","push","put","remove","render","repeat","replace","reset","return","scroll","select","send","set","settle","show","start","swap","take","tell","throw","toggle","transition","trigger","unless","wait","for"]),R=new Set(["if","unless","repeat","wait","for","while"]),M="at",$="at start of",H="at end of",q=["into","before","after",M,$,H,"at the start of","at the end of"],W=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"]),V={isCommand:e=>j.has(e.toLowerCase()),isControlFlowCommand:e=>R.has(e.toLowerCase()),isKeyword:e=>W.has(e.toLowerCase()),isTerminator:e=>I.includes(e),isPutOperation:e=>q.includes(e),isCSSFunction:e=>D.has(e.toLowerCase())},D=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"]),B=new Set(["me","it","you","result","my","its","your"]),F=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","am in","am not in","am between","am not between","is really","is not really","is equal","is not equal","contain","do not contain","does not contains","do not match","does not match","ignoring case","sorted by","mapped to","split by","joined by"]),U=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"]),z=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","no","start","of","the","new","global","local","equal","equals","greater","less","than","really","catch","finally","throw","return"]),K=new Set(["then","end","to","into","on","with","from","in","by","for","while","until","unless","else","catch","finally"]),Z=new Set([")","]","}",","]);function G(e,t){return{infix:{bp:[e,e+1],handler:t??((t,r,n)=>{const s=n.parseExpr(e+1);return{type:"binaryExpression",operator:r.value,left:t,right:s,start:t.start,end:s.end??r.end,line:t.line??r.line,column:t.column??r.column}})}}}function Q(e,t){return{infix:{bp:[e+1,e],handler:(t,r,n)=>{const s=n.parseExpr(e);return{type:"binaryExpression",operator:r.value,left:t,right:s,start:t.start,end:s.end??r.end,line:t.line??r.line,column:t.column??r.column}}}}}function J(e,t){return{prefix:{bp:e,handler:t??((t,r)=>{const n=r.parseExpr(e);return{type:"unaryExpression",operator:t.value,operand:n,argument:n,prefix:!0,start:t.start,end:n.end??t.end,line:t.line,column:t.column}})}}}const Y=new Map([["or",G(10)],["||",G(10)],["and",G(20)],["&&",G(20)],["==",G(30)],["!=",G(30)],["<",G(30)],[">",G(30)],["<=",G(30)],[">=",G(30)],["is",G(30)],["matches",G(30)],["contains",G(30)],["starts with",G(30)],["ends with",G(30)],["does not start with",G(30)],["does not end with",G(30)],["is between",G(30,(e,t,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!1,start:e.start,end:i.end}})],["is not between",G(30,(e,t,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!0,start:e.start,end:i.end}})],["am between",G(30,(e,t,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!1,start:e.start,end:i.end}})],["am not between",G(30,(e,t,r)=>{const n=r.parseExpr(31),s=r.peek();if(!s||"and"!==s.value.toLowerCase())throw Error("between requires 'and' between min and max operands, got: "+(s?.value??"<end>"));r.advance();const i=r.parseExpr(31);return{type:"betweenExpression",value:e,min:n,max:i,negated:!0,start:e.start,end:i.end}})],["ignoring case",{infix:{bp:[25,26],handler:(e,t,r)=>(e.ignoringCase=!0,e)}}],["where",G(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"where",collection:e,right:n,start:e.start,end:n.end}})],["sorted by",G(28,(e,t,r)=>{const n=r.parseExpr(29);let s="asc";const i=r.peek();if(i&&"string"==typeof i.value){const e=i.value.toLowerCase();"asc"===e||"ascending"===e?(r.advance(),s="asc"):"desc"!==e&&"descending"!==e||(r.advance(),s="desc")}return{type:"collectionExpression",operator:"sorted by",collection:e,right:n,order:s,start:e.start,end:n.end}})],["mapped to",G(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"mapped to",collection:e,right:n,start:e.start,end:n.end}})],["split by",G(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"split by",collection:e,right:n,start:e.start,end:n.end}})],["joined by",G(28,(e,t,r)=>{const n=r.parseExpr(29);return{type:"collectionExpression",operator:"joined by",collection:e,right:n,start:e.start,end:n.end}})],["+",{...G(40),...J(80)}],["-",{...G(40),...J(80)}],["*",G(50)],["/",G(50)],["%",G(50)],["mod",G(50)],["^",Q(60)],["**",Q(60)],["as",G(70,(e,t,r)=>{const n=()=>{const e=r.peek();!e||"a"!==e.value&&"an"!==e.value||r.advance();const t=r.parseExpr(71),n=r.peek();if(n&&":"===n.value&&t&&"identifier"===t.type){r.advance();const e=r.advance();if(e&&void 0!==e.value)return{...t,name:`${t.name+""}:${e.value}`,end:e.end}}return t};let s=n(),i={type:"asExpression",expression:e,targetType:s,start:e.start,end:s.end??t.end,line:e.line??t.line,column:e.column??t.column};for(;r.peek()&&"|"===r.peek().value;){r.advance();const e=n();i={type:"asExpression",expression:i,targetType:e,start:i.start,end:e.end??i.end,line:i.line,column:i.column}}return i})],["not",J(80)],["!",J(80)],["no",J(27)]]);function X(e){return(t,r,n)=>{const s=n.advance();if(!s||!s.value)throw Error(`Type check requires a type name after 'is ${e?"not ":""}a/an', got: <end>`);let i=!0;const a=n.peek();return a&&"!"===a.value&&(n.advance(),i=!1),{type:"typeCheckExpression",value:t,typeName:s.value,nullOk:i,negated:e,start:t.start,end:s.end}}}const ee=function(...e){const t=new Map;for(const r of e)for(const[e,n]of r){const r=t.get(e);t.set(e,r?{prefix:n.prefix??r.prefix,infix:n.infix??r.infix}:{...n})}return t}(Y,new Map([["===",G(30)],["!==",G(30)],["is not",G(30)],["am",G(30)],["is in",G(30)],["is not in",G(30)],["precedes",G(30)],["does not precede",G(30)],["follows",G(30)],["does not follow",G(30)],["is a",G(30,X(!1))],["is an",G(30,X(!1))],["is not a",G(30,X(!0))],["is not an",G(30,X(!0))],["has",G(30)],["have",G(30)],["match",G(30)],["include",G(30)],["includes",G(30)],["equals",G(30)],["does not contain",G(30)],["does not include",G(30)],["am in",G(30)],["am not in",G(30)],["is really",G(30)],["is not really",G(30)],["is equal",G(30)],["is not equal",G(30)],["contain",G(30)],["do not contain",G(30)],["does not contains",G(30)],["do not match",G(30)],["does not match",G(30)],["is equal to",G(30)],["is not equal to",G(30)],["is really equal to",G(30)],["is not really equal to",G(30)],["really equals",G(30)],["is greater than",G(30)],["is less than",G(30)],["is greater than or equal to",G(30)],["is less than or equal to",G(30)],["in",G(30)],["of",Q(30)],["really",G(30)],["exists",{prefix:{bp:80,handler:(e,t)=>({type:"unaryExpression",operator:e.value,operand:t.parseExpr(80),start:e.start})},infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["does not exist",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["is not empty",{infix:{bp:[30,31],handler:(e,t)=>({type:"unaryExpression",operator:t.value,operand:e,prefix:!1,start:e.start})}}],["some",J(80)]]),new Map([["=",Q(5)]])),te=new Set,re=new Set,ne=new Set,se=new Set;function ie(e,t){void 0!==console&&console.error(`[hyperfixi] ${e} threw:`,t)}function ae(e,t){if(0!==re.size)for(const r of re)try{r(e,t)}catch(e){ie("globalReadHook",e)}}function oe(e,t,r){if(0!==ne.size)for(const n of ne)try{n(e,t,r)}catch(e){ie("localWriteHook",e)}}function ce(e,t){if(0!==se.size)for(const r of se)try{r(e,t)}catch(e){ie("localReadHook",e)}}function le(e,t,r){if(e.globals.set(t,r),0!==te.size)for(const n of te)try{n(t,r,e)}catch(e){ie("globalWriteHook",e)}}const ue=new Map,de=new Map,me=new Map;function pe(e){return ue.get(e.toLowerCase())}function he(e){return me.get(e)}const fe=new Map,ye=new WeakMap;function ge(e){let t=ye.get(e);return t||(t=new Map,ye.set(e,t)),t}function ve(e){const t=e.owner;return t||(e.me instanceof Element?e.me:null)}function be(e,t){const r=ve(e);if(r)return ce(t,e),ge(r).get(t)}function we(e,t,r){const n=ve(e);n&&(ge(n).set(t,r),oe(t,r,e))}function Ee(e,t){return{me:e??null,owner:e??null,it:null,you:null,result:null,locals:new Map,globals:fe}}function ke(){return fe}function xe(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName&&"classList"in e}function Ce(e){if(null===e||"object"!=typeof e)return!1;const t=e.nodeType;return 1===t||3===t||11===t}function Ae(e){return null!==e&&"object"==typeof e&&"length"in e&&"number"==typeof e.length&&(Symbol.iterator in e||"function"==typeof e.item)}function Se(e){if(null==e)return 0;if("number"==typeof e)return isFinite(e)?e:0;if("string"==typeof e){return parseFloat(e)}if("boolean"==typeof e)return e?1:0;if(Array.isArray(e))return e.length;if("object"==typeof e){if("length"in e&&"number"==typeof e.length)return e.length;if("function"==typeof e.valueOf){const t=e.valueOf();if("number"==typeof t)return t}return NaN}return 0}function Te(e,t,r){return"element"===r?be(t,e):"global"===r&&t.globals&&t.globals.has(e)?t.globals.get(e):"global"!==r&&t.locals&&t.locals.has(e)?(ce(e,t),t.locals.get(e)):t.globals&&t.globals.has(e)?t.globals.get(e):t.variables&&t.variables.has(e)?t.variables.get(e):"global"===r&&t.locals&&t.locals.has(e)?(ce(e,t),t.locals.get(e)):"undefined"!=typeof window&&e in window?window[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}function Le(e,t,r,n){if("element"!==n){if("global"===n)return le(r,e,t),void("undefined"!=typeof window&&(window[e]=t));if(e.startsWith("$")){return void le(r,e.slice(1),t)}if(r.locals&&r.locals.has(e))return r.locals.set(e,t),void oe(e,t,r);if(r.globals&&r.globals.has(e))return le(r,e,t),void("undefined"!=typeof window&&e in window&&(window[e]=t));if(r.variables&&r.variables.has(e))r.variables.set(e,t);else{if("undefined"!=typeof window&&e in window)return window[e]=t,void le(r,e,t);r.locals.set(e,t),oe(e,t,r)}}else we(r,e,t)}function Oe(e,t){return"me"===e?t.me:"it"===e?t.it:"you"===e?t.you:Te(e,t)}function Ne(e,t,r,n){if("number"==typeof e)return e;if(xe(e)){const r=e;if(t){if(t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)){return Se(r.getAttribute(t))}return Se(r[t])}return Se(r.value||r.textContent)}if("string"==typeof e){if("element"===r)return Se(Te(e,n,"element"));if("global"===r){return Se(Te(e,n,"global"))}if(e.includes("."))return function(e,t){const r=e.split("."),n=r[1],s=Oe(r[0],t);return s?Se(s[n]):0}(e,n);if("me"===e&&n.me)return Se(n.me.value||0);if("it"===e)return Se(n.it||0);if("you"===e&&n.you)return Se(n.you.value||0);return Se(Te(e,n))}return Se(e)}function Pe(e,t,r,n,s){if(xe(e)){const r=e;return void(t?t.startsWith("data-")||["id","class","title","alt","src","href"].includes(t)?r.setAttribute(t,n+""):r[t]=n:"value"in r&&void 0!==r.value?r.value=n+"":r.textContent=n+"")}if("string"==typeof e){if("element"===r)return void Le(e,n,s,"element");if("global"===r)return void Le(e,n,s,"global");if(e.includes("."))return void function(e,t,r){const n=e.split("."),s=n[1],i=Oe(n[0],r);i&&(i[s]=t)}(e,n,s);if("me"===e&&s.me)return void(s.me.value=n);if("it"===e)return void Object.assign(s,{it:n});if("you"===e&&s.you)return void(s.you.value=n);Le(e,n,s)}}function Ie(e,t,r){return r||"string"!=typeof t||!t.startsWith("#")?e:Array.isArray(e)?e[0]??null:e}function je(e){if("undefined"==typeof document)throw Error("DOM not available");const t=Array.from(document.querySelectorAll(e)).filter(e=>xe(e));if(!t.length)throw Error(`No elements: "${e}"`);return t}function Re(e){if(xe(e))return[e];if(Array.isArray(e)){const t=e.filter(xe);return t.length>0?t:null}if("undefined"!=typeof NodeList&&e instanceof NodeList){const t=Array.from(e).filter(xe);return t.length>0?t:null}return null}const Me=new class{constructor(e={}){this.types=new Map,this.coercionCache=new Map,this.config={strictMode:!1,cacheCoercions:!0,...e},this.registerBuiltinTypes()}register(e){this.types.has(e.name)&&console.warn(`ExpressionTypeRegistry: Overwriting existing type '${e.name}'`),this.types.set(e.name,e)}get(e){return this.types.get(e)}has(e){return this.types.has(e)}getTypeNames(){return Array.from(this.types.keys())}inferType(e){for(const[t,r]of this.types)if(r.isType(e))return t;return"Unknown"}getHyperScriptType(e){const t=this.inferType(e),r=this.types.get(t);return r?.hyperscriptType??"unknown"}coerce(e,t,r){const n=this.types.get(t);if(!n){if(this.config.strictMode)throw Error("Unknown target type: "+t);return null}if(n.isType(e))return e;if(this.config.cacheCoercions){const r=`${this.inferType(e)}:${t}:${JSON.stringify(e)}`;if(this.coercionCache.has(r))return this.coercionCache.get(r)}const s=this.inferType(e),i=n.coerceFrom?.[s];if(i){const n=i(e,r);if(this.config.cacheCoercions&&null!==n){const r=`${s}:${t}:${JSON.stringify(e)}`;this.coercionCache.set(r,n)}return n}return n.defaultValue}canCoerce(e,t){const r=this.types.get(t);if(!r)return!1;if(r.isType(e))return!0;const n=this.inferType(e);return void 0!==r.coerceFrom?.[n]}getCoercionInfo(e,t){const r=this.types.get(t);return r&&(e===t||r.coerceFrom?.[e])?{possible:!0,direct:!0}:{possible:!1,direct:!1}}clearCache(){this.coercionCache.clear()}getStats(){return{typeCount:this.types.size,cacheSize:this.coercionCache.size,typeNames:this.getTypeNames()}}registerBuiltinTypes(){this.register({name:"String",hyperscriptType:"string",tsType:"string",isType:e=>"string"==typeof e,defaultValue:"",description:"Text string value",examples:["hello","world",""],coerceFrom:{Number:e=>e+"",Boolean:e=>e+"",Null:()=>"",Undefined:()=>"",Array:e=>Array.isArray(e)?e.join(", "):null,Object:e=>{try{return JSON.stringify(e)}catch{return e+""}},Element:e=>e instanceof Element?e.textContent??e.outerHTML:null}}),this.register({name:"Number",hyperscriptType:"number",tsType:"number",isType:e=>"number"==typeof e&&!isNaN(e),defaultValue:0,description:"Numeric value (integer or float)",examples:[0,1,3.14,-42],coerceFrom:{String:e=>{const t=parseFloat(e);return isNaN(t)?null:t},Boolean:e=>e?1:0,Null:()=>0,Undefined:()=>null}}),this.register({name:"Boolean",hyperscriptType:"boolean",tsType:"boolean",isType:e=>"boolean"==typeof e,defaultValue:!1,description:"True or false value",examples:[!0,!1],coerceFrom:{String:e=>{const t=e.toLowerCase().trim();return"true"===t||"yes"===t||"1"===t||"false"!==t&&"no"!==t&&"0"!==t&&""!==t&&t.length>0},Number:e=>0!==e,Null:()=>!1,Undefined:()=>!1,Array:e=>!!Array.isArray(e)&&e.length>0,Element:e=>e instanceof Element,ElementList:e=>Array.isArray(e)&&e.length>0}}),this.register({name:"Element",hyperscriptType:"element",tsType:"Element | HTMLElement",isType:e=>e instanceof Element,defaultValue:null,description:"DOM Element",coerceFrom:{String:(e,t)=>{const r=e;if(r.startsWith("#")||r.startsWith(".")||r.match(/^[\w-]+$/))try{return document.querySelector(r)}catch{return null}return null},ElementList:e=>Array.isArray(e)&&e.length>0?e[0]:null,NodeList:e=>e.length>0?e[0]:null}}),this.register({name:"ElementList",hyperscriptType:"element-list",tsType:"Element[]",isType:e=>Array.isArray(e)&&e.length>0&&e.every(e=>e instanceof Element),defaultValue:[],description:"Array of DOM Elements",coerceFrom:{Element:e=>e instanceof Element?[e]:[],NodeList:e=>Array.from(e),String:e=>{try{return Array.from(document.querySelectorAll(e))}catch{return[]}},Array:e=>{const t=e;return t.every(e=>e instanceof Element)?t:[]}}}),this.register({name:"Array",hyperscriptType:"array",tsType:"unknown[]",isType:e=>Array.isArray(e),defaultValue:[],description:"Array of values",coerceFrom:{String:e=>{const t=e;try{const e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t.split(",").map(e=>e.trim())},ElementList:e=>e,NodeList:e=>Array.from(e),Object:e=>Object.values(e)}}),this.register({name:"Object",hyperscriptType:"object",tsType:"Record<string, unknown>",isType:e=>!("object"!=typeof e||null===e||Array.isArray(e)||e instanceof Element),defaultValue:{},description:"Plain JavaScript object",coerceFrom:{String:e=>{try{const t=JSON.parse(e);if("object"==typeof t&&null!==t&&!Array.isArray(t))return t}catch{}return null},Array:e=>{const t={};return e.forEach((e,r)=>{t[r+""]=e}),t}}}),this.register({name:"Null",hyperscriptType:"null",tsType:"null",isType:e=>null===e,defaultValue:null,description:"Null value"}),this.register({name:"Undefined",hyperscriptType:"undefined",tsType:"undefined",isType:e=>void 0===e,defaultValue:void 0,description:"Undefined value"}),this.register({name:"Function",hyperscriptType:"function",tsType:"Function",isType:e=>"function"==typeof e,defaultValue:null,description:"JavaScript function"}),this.register({name:"Event",hyperscriptType:"event",tsType:"Event",isType:e=>e instanceof Event,defaultValue:null,description:"DOM Event"}),this.register({name:"NodeList",hyperscriptType:"element-list",tsType:"NodeList",isType:e=>e instanceof NodeList,defaultValue:null,description:"DOM NodeList (typically from querySelectorAll)",coerceFrom:{Array:e=>null}}),this.register({name:"Unknown",hyperscriptType:"unknown",tsType:"unknown",isType:e=>!0,defaultValue:null,description:"Unknown/any value type"})}};function $e(e){const t=Me.get("String");return t?t.isType(e):"string"==typeof e}function He(e){const t=Me.get("Number");return t?t.isType(e):"number"==typeof e}function qe(e){const t=Me.get("Boolean");return t?t.isType(e):"boolean"==typeof e}function We(e){const t=Me.get("Object");return t?t.isType(e):"object"==typeof e&&null!==e}function Ve(e){const t=Me.get("Function");return t?t.isType(e):"function"==typeof e}function De(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"style"in e}function Be(e){return e instanceof Element}function Fe(e){return e instanceof HTMLElement}const _e=new Set(["disabled","readonly","required","checked","selected","hidden","open","autofocus","autoplay","controls","loop","muted","multiple","reversed","defer","async","novalidate","formnovalidate","ismap"]);function Ue(e,t){return _e.has(t.toLowerCase())?e.hasAttribute(t):e.getAttribute(t)}const ze={id:e=>e.id,classname:e=>e.className,class:e=>e.className,tagname:e=>e.tagName.toLowerCase(),innertext:e=>e.textContent?.trim(),innerHTML:e=>e.innerHTML,outerhtml:e=>e.outerHTML,value:e=>function(e){if(null===e||"object"!=typeof e||!("tagName"in e))return!1;const t=e.tagName;return"INPUT"===t||"SELECT"===t||"TEXTAREA"===t}(e)?e.value:void 0,checked:e=>function(e){return null!==e&&"object"==typeof e&&"tagName"in e&&"INPUT"===e.tagName}(e)?e.checked:void 0,disabled:e=>"disabled"in e?e.disabled:void 0,selected:e=>function(e){return null!=e&&"object"==typeof e&&"tagName"in e&&"OPTION"===e.tagName}(e)?e.selected:void 0,tabindex:e=>De(e)?e.tabIndex:void 0,hidden:e=>De(e)?e.hidden:void 0,style:e=>getComputedStyle(e),children:e=>Array.from(e.children),parent:e=>e.parentElement,firstchild:e=>e.firstElementChild,lastchild:e=>e.lastElementChild,nextsibling:e=>e.nextElementSibling,previoussibling:e=>e.previousElementSibling,next:e=>e.nextElementSibling,previous:e=>e.previousElementSibling,values:e=>function(e){if(e instanceof HTMLFormElement)return new FormData(e);const t=new FormData;return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e.getAttribute("name");r&&"value"in e&&t.append(r,e.value)}),t}(e)};function Ke(e,t){if(t.startsWith("*"))return function(e,t){if(!Fe(e))return;if(t.startsWith("computed-"))return getComputedStyle(e).getPropertyValue(t.slice(9))||"";const r=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[r]}(e,t.slice(1));if(t.startsWith("computed-")){const r=t.slice(9);if(Fe(e)){return getComputedStyle(e).getPropertyValue(r)}return}if(t.startsWith("@")){return Ue(e,t.slice(1))}const r=ze[t.toLowerCase()];if(r)return r(e);if(function(e,t){return e.hasAttribute(t)}(e,t))return Ue(e,t);const n=e[t];return Ve(n)?n.bind(e):n}const Ze={1:"one",2:"two",3:"three",4:"four",5:"five"};function Ge(e,t,r,n){if(e.length!==t){const e=n?` (${n})`:"";return`${r} requires exactly ${s=t,Ze[s]??s+""} argument${1===t?"":"s"}${e}`}var s;return null}function Qe(e,t,r,n){if("string"!=typeof e[t]){return`${r} ${n||"argument "+(t+1)} must be a string`}return null}function Je(e,t,r){return Ge(e,1,t,r)??Qe(e,0,t,r)}function Ye(e,t){return Ge(e,2,t,"left, right")}function Xe(){return null}function et(e,t,r,n){if(e.length>t){return`${r} expression takes at most ${1===t?"one":t+""} argument${1===t?"":"s"}${n?` (${n})`:""}`}return null}function tt(e,t,r,n,s){if(t>e.length||e.length>r){return`${n} requires ${t}-${r} arguments${s?` (${s})`:""}`}return null}const rt={conversions:{dynamicResolvers:[]}},nt={Array:e=>Array.isArray(e)?e:e instanceof NodeList?Array.from(e):null==e?[]:[e],String:e=>null==e?"":$e(e)?e:We(e)?JSON.stringify(e):e+"",Boolean:e=>{if(qe(e))return e;if(null==e)return!1;if($e(e)){const t=e.toLowerCase().trim();return"false"!==t&&"0"!==t&&""!==t}return He(e)?0!==e&&!isNaN(e):!!e},Number:e=>{if(He(e))return e;if(null==e)return 0;const t=Number(e);return isNaN(t)?0:t},Math:e=>{if(He(e))return e;if(null==e)return 0;const t=(e+"").trim();if(!t)return 0;try{return function(e){if(e=e.replace(/\s/g,""),!/^[0-9+\-*/().]+$/.test(e))throw Error("Invalid characters in math expression");try{const t=Function(`"use strict"; return (${e})`)();if(!He(t)||!isFinite(t))throw Error("Expression did not evaluate to a finite number");return t}catch(e){throw Error("Math expression evaluation failed: "+(e instanceof Error?e.message:e+""))}}(t)}catch(e){return console.warn("Math conversion failed:",e),0}},Int:e=>{const t=nt.Number(e);return Math.trunc(t)},Float:e=>{const t=nt.Number(e);return parseFloat(""+t)},Date:e=>{if(e instanceof Date)return e;if(null==e)return new Date(NaN);if($e(e)&&/^\d{4}-\d{2}-\d{2}$/.test(e)){const[t,r,n]=e.split("-").map(Number);return new Date(t,r-1,n)}return new Date(e)},JSON:e=>{if(!$e(e))return e;try{return JSON.parse(e)}catch{return e}},JSONString:e=>{try{return JSON.stringify(e)}catch{return"{}"}},Object:e=>{if(We(e))return e;if($e(e))try{return JSON.parse(e)}catch(e){return{}}return{}},Fragment:e=>{const t=document.createDocumentFragment(),r=Array.isArray(e)||e instanceof NodeList?Array.from(e):[e];for(const e of r)if(e instanceof Node)t.append(e);else{const r=document.createElement("template");r.innerHTML=null==e?"":e+"",t.append(r.content)}return t},HTML:e=>$e(e)?e:e instanceof NodeList?Array.from(e).map(e=>e instanceof Element?e.outerHTML:e.textContent||"").join(""):Array.isArray(e)?e.map(e=>e instanceof Element?e.outerHTML:nt.String(e)).join(""):e instanceof Element?e.outerHTML:nt.String(e),Values:(e,t)=>{if(e instanceof HTMLFormElement)return function(e){const t={};return e.querySelectorAll("input, select, textarea").forEach(e=>{const r=e;if(r.name){const e=st(r);void 0!==e&&(void 0!==t[r.name]?(Array.isArray(t[r.name])||(t[r.name]=[t[r.name]]),t[r.name].push(e)):t[r.name]=e)}}),t}(e);if(e instanceof HTMLElement){const t=e.querySelectorAll("input, select, textarea"),r={};return t.forEach(e=>{e.name&&(r[e.name]=st(e))}),r}return{}},FormEncoded:(e,t)=>{const r=e instanceof HTMLElement?nt.Values(e,t):e;if(!We(r))return"";const n=new URLSearchParams;for(const[e,t]of Object.entries(r))if(null!=t)if(Array.isArray(t))for(const r of t)n.append(e,r+"");else n.append(e,t+"");return""+n},Set:e=>new Set(e),Map:e=>new Map(Object.entries(e??{})),Keys:e=>e instanceof Map?Array.from(e.keys()):Object.keys(e??{}),Entries:e=>e instanceof Map?Array.from(e.entries()):Object.entries(e??{}),Reversed:e=>Array.from(e).reverse(),Unique:e=>[...new Set(e)],Flat:e=>Array.from(e).flat(),"Values:Form":(e,t)=>{const r=nt.Values(e,t);return nt.FormEncoded(r,t)},"Values:JSON":(e,t)=>{const r=nt.Values(e,t);return JSON.stringify(r)}};function st(e){if(e instanceof HTMLInputElement)switch(e.type){case"checkbox":return e.checked;case"radio":return e.checked?e.value:void 0;case"number":case"range":return e.valueAsNumber;case"date":case"datetime-local":return e.valueAsDate;case"file":return e.files;default:return e.value}return e instanceof HTMLSelectElement&&e.multiple?Array.from(e.selectedOptions).map(e=>e.value):e.value}const it={boolean:"Boolean",bool:"Boolean",string:"String",str:"String",number:"Number",num:"Number",int:"Int",integer:"Int",float:"Float",array:"Array",object:"Object",obj:"Object",date:"Date",json:"JSON",jsonstring:"JSONString",formencoded:"FormEncoded"};function at(e,t,r){if("string"!=typeof t)throw Error("Conversion type must be a string");if(t.startsWith("Fixed")){const{precision:r}=function(e){const t=e.match(/^Fixed(?::(\d+))?$/);return t?{precision:t[1]?parseInt(t[1],10):0}:{}}(t);return nt.Number(e).toFixed(r??0)}if(null==e)return e;let n=nt[t];if(n)return n(e,r);const s=it[t.toLowerCase()];if(s&&(n=nt[s],n))return n(e,r);const i=rt.conversions[t];if("function"==typeof i)return i(e,r);for(const r of rt.conversions.dynamicResolvers){const n=r(t,e);if(void 0!==n)return n}return console.warn("Unknown conversion type: "+t),e}const ot={as:{name:"as",category:"Conversion",evaluatesTo:"Any",precedence:20,associativity:"Left",operators:["as"],async evaluate(e,...t){const[r,n]=t;return at(r,n,e)},validate:e=>Ge(e,2,"as","value, type")??Qe(e,1,"as","conversion type")},is:{name:"is",category:"Conversion",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is a","is an"],async evaluate(e,...t){const[r,n]=t;if(!$e(n))throw Error("Type check requires a string type");switch(n.toLowerCase()){case"null":return null===r;case"undefined":return void 0===r;case"string":return $e(r);case"number":return He(r)&&!isNaN(r);case"boolean":return qe(r);case"object":return We(r);case"array":return Array.isArray(r);case"function":return Ve(r);case"date":return r instanceof Date;case"element":return r instanceof Element;case"node":return r instanceof Node;case"nodelist":return r instanceof NodeList;case"empty":return null==r||""===r||Array.isArray(r)&&0===r.length||We(r)&&0===Object.keys(r).length;default:return r?.constructor?.name?.toLowerCase()===n.toLowerCase()}},validate:e=>Ge(e,2,"is","value, type")??Qe(e,1,"is","type")},async:{name:"async",category:"Conversion",evaluatesTo:"Any",precedence:25,associativity:"Right",operators:["async"],evaluate:async(e,t)=>t,validate:e=>Ge(e,1,"async","expression")}};function ct(e,t){if(t.startsWith("computed-")){const r=t.substring(9);return getComputedStyle(e).getPropertyValue(r)||""}const r=t.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());return e.style[r]}const lt={me:{name:"me",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me??null,validate:Xe},you:{name:"you",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.you??null,validate:Xe},it:{name:"it",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:Xe},its:{name:"its",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.it??e.result,validate:Xe},result:{name:"result",category:"Reference",evaluatesTo:"Any",evaluate:async e=>e.result??e.it,validate:Xe},querySelector:{name:"querySelector",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("querySelector requires a string selector");return document.querySelector(r)},validate:e=>Je(e,"querySelector","selector")},querySelectorAll:{name:"querySelectorAll",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("querySelectorAll requires a string selector");const n=document.querySelectorAll(r);return Array.from(n)},validate:e=>Je(e,"querySelectorAll","selector")},getElementById:{name:"getElementById",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementById requires a string ID");return document.getElementById(r)},validate:e=>Je(e,"getElementById","ID")},getElementsByClassName:{name:"getElementsByClassName",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("getElementsByClassName requires a string class name");const n=document.getElementsByClassName(r);return Array.from(n)},validate:e=>Je(e,"getElementsByClassName","className")},closest:{name:"closest",category:"Reference",evaluatesTo:"Element",async evaluate(e,...t){let r=t[0];if(r&&"object"==typeof r&&"type"in r){const e=r;"identifier"===e.type&&e.name?r=e.name:"literal"===e.type&&"string"==typeof e.value&&(r=e.value)}if("string"!=typeof r)throw Error("closest requires a string selector");return e.me?e.me.closest(r):null},validate(e){if(1!==e.length)return"closest requires exactly 1 argument (selector)";const t=e[0];if("string"==typeof t)return null;if(t&&"object"==typeof t&&"type"in t){if("identifier"===t.type||"literal"===t.type)return null}return"closest selector must be a string or identifier"}},parent:{name:"parent",category:"Reference",evaluatesTo:"Element",evaluate:async e=>e.me?e.me.parentElement:null,validate:Xe},window:{name:"window",category:"Reference",evaluatesTo:"Object",evaluate:async e=>window,validate:Xe},document:{name:"document",category:"Reference",evaluatesTo:"Object",evaluate:async e=>document,validate:Xe},elementWithSelector:{name:"elementWithSelector",category:"Reference",evaluatesTo:"Array",async evaluate(e,...t){const r=t[0];if("string"!=typeof r)throw Error("Selector must be a string");const n=e?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!n)throw Error("DOM not available - cannot resolve element selector");const s=n.querySelectorAll(r);return Array.from(s)},validate:e=>Je(e,"elementWithSelector","selector")},styleRef:{name:"styleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r)throw Error("StyleRef requires a string property name");const s=n||e.me;if(s&&s instanceof HTMLElement)return ct(s,r)},validate:e=>tt(e,1,2,"styleRef","property, optional element")??Qe(e,0,"styleRef","property")??(2===e.length&&e[1]&&"object"!=typeof e[1]?"styleRef element must be an HTMLElement":null)},possessiveStyleRef:{name:"possessiveStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Possessive styleRef requires possessor and property strings");let s=null;if("my"===r&&e.me?s=e.me instanceof HTMLElement?e.me:null:"its"===r&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return ct(s,n)},validate:e=>Ge(e,2,"possessiveStyleRef","possessor, property")??Qe(e,0,"possessiveStyleRef","possessor")??Qe(e,1,"possessiveStyleRef","property")},ofStyleRef:{name:"ofStyleRef",category:"Reference",evaluatesTo:"String",async evaluate(e,...t){const r=t[0],n=t[1];if("string"!=typeof r||"string"!=typeof n)throw Error("Of styleRef requires property and reference strings");let s=null;if("me"===n&&e.me?s=e.me instanceof HTMLElement?e.me:null:"it"===n&&e.it&&(s=e.it instanceof HTMLElement?e.it:null),s)return ct(s,r)},validate:e=>Ge(e,2,"ofStyleRef","property, reference")??Qe(e,0,"ofStyleRef","property")??Qe(e,1,"ofStyleRef","reference")}};function ut(e,t,r,n=[]){return{type:e,message:t,suggestions:n,...r&&{path:r}}}const dt="undefined"!=typeof process&&"production"===process.env.NODE_ENV||"undefined"!=typeof process&&"true"===process.env.HYPERFIXI_SKIP_VALIDATION||"undefined"!=typeof globalThis&&"true"===globalThis.HYPERFIXI_SKIP_VALIDATION;let mt;function pt(){return mt({validate:e=>({success:!0,data:e})})}function ht(e,t){if(dt)return pt();const r=mt({validate:r=>{if("object"!=typeof r||null===r||Array.isArray(r))return{success:!1,error:ut("type-mismatch","Expected object, received "+typeof r)};const n=r,s={};if(t?.strict){const t=Object.keys(e),r=Object.keys(n).filter(e=>!t.includes(e));if(r.length>0)return{success:!1,error:ut("runtime-error","Unexpected properties: "+r.join(", "))}}for(const[t,r]of Object.entries(e)){const e=n[t];if(!(t in n)&&!r._isOptional)return{success:!1,error:ut("missing-argument",`Required field "${t}" is missing`,t)};const i=r.validate(e);if(!i.success){return{success:!1,error:ut("validation-error",i.error.message||`Field "${t}" validation failed`,i.error.path?`${t}.${i.error.path}`:t)}}void 0!==i.data&&(s[t]=i.data)}return{success:!0,data:s}}});return r.strict=()=>ht(e,{strict:!0}),r}mt=function(e){return e.describe||(e.describe=function(e){return this.description=e,this}),e.safeParse||(e.safeParse=function(e){const t=this.validate(e);return t.success?{success:!0,data:t.data}:{success:!1,error:{errors:t.error?[t.error]:[]}}}),e.parse||(e.parse=function(e){const t=this.validate(e);if(t.success&&void 0!==t.data)return t.data;throw Error(t.error?.message||"Validation failed")}),e.optional||(e.optional=function(){const e=this.validate.bind(this),t={...this,_isOptional:!0,validate:t=>null==t?{success:!0,data:void 0}:e(t)};return mt(t)}),e.min||(e.min=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&e>n.data.length?{success:!1,error:ut("runtime-error",`String must be at least ${e} characters long`)}:n}};return mt(r)}),e.max||(e.max=function(e){const t=this.validate.bind(this),r={...this,validate:r=>{const n=t(r);return n.success&&"string"==typeof n.data&&n.data.length>e?{success:!1,error:ut("runtime-error",`String must be at most ${e} characters long`)}:n}};return mt(r)}),e.default||(e.default=function(e){const t=this.validate.bind(this),r={...this,_defaultValue:e,_hasDefault:!0,validate:r=>void 0===r?{success:!0,data:e}:t(r)};return mt(r)}),e.rest||(e.rest=function(e){return this}),e.refine||(e.refine=function(e,t){const r=this.validate.bind(this),n={...this,validate:n=>{const s=r(n);return s.success?e(s.data)?s:{success:!1,error:ut("runtime-error",t||"Refinement validation failed")}:s}};return mt(n)}),new Proxy(e,{get:(e,t,r)=>t in e||"string"!=typeof t||t.startsWith("_")||"constructor"===t||"validate"===t||"then"===t?Reflect.get(e,t,r):function(...e){return r}})};const ft=e=>function(e={}){return dt?pt():mt({validate:t=>e.optional&&null==t?{success:!0,data:void 0}:"string"!=typeof t?{success:!1,error:ut("type-mismatch","Expected string, received "+typeof t)}:void 0!==e.minLength&&e.minLength>t.length?{success:!1,error:ut("runtime-error",`String must be at least ${e.minLength} characters long`)}:void 0!==e.maxLength&&t.length>e.maxLength?{success:!1,error:ut("runtime-error",`String must be at most ${e.maxLength} characters long`)}:e.pattern&&!e.pattern.test(t)?e.pattern.source.startsWith("^")&&e.pattern.source.endsWith("$")?{success:!1,error:ut("runtime-error",`Expected "${e.pattern.source.slice(1,-1)}", received "${t}"`)}:{success:!1,error:ut("missing-argument","String does not match required pattern")}:{success:!0,data:t},...e.description&&{description:e.description}})}(e||{}),yt=e=>function(e={}){return dt?pt():mt({validate:t=>{const r=Number(t);return isNaN(r)?{success:!1,error:ut("type-mismatch","Expected number, received "+typeof t)}:void 0!==e.min&&e.min>r?{success:!1,error:ut("runtime-error","Number must be at least "+e.min)}:void 0!==e.max&&r>e.max?{success:!1,error:ut("runtime-error","Number must be at most "+e.max)}:{success:!0,data:r}}})}(e||{}),gt=()=>dt?pt():mt({validate:e=>"boolean"!=typeof e?{success:!1,error:ut("type-mismatch","Expected boolean, received "+typeof e)}:{success:!0,data:e}}),vt=e=>ht(e),bt=e=>function(e){return dt?pt():mt({validate:t=>{if(!Array.isArray(t))return{success:!1,error:ut("type-mismatch","Expected array, received "+typeof t)};if(t.length!==e.length)return{success:!1,error:ut("runtime-error",`Expected tuple of length ${e.length}, received length ${t.length}`)};const r=[];for(let n=0;e.length>n;n++){const s=e[n].validate(t[n]);if(!s.success)return{success:!1,error:ut("runtime-error",s.error.message,s.error.path?`${n}.${s.error.path}`:""+n)};r.push(s.data)}return{success:!0,data:r}}})}(e),wt=()=>pt();class Et{constructor(e=100,t=5e3){this.maxSize=e,this.ttl=t,this.cache=new Map,this.accessOrder=new Map,this.accessCounter=0}get(e){const t=this.cache.get(e);if(t){if(this.ttl>=Date.now()-t.timestamp)return t.accessCount++,this.accessOrder.set(e,++this.accessCounter),t.result;this.delete(e)}}set(e,t){this.maxSize>this.cache.size||this.cache.has(e)||this.evictLRU();this.cache.set(e,{result:t,timestamp:Date.now(),accessCount:1}),this.accessOrder.set(e,++this.accessCounter)}delete(e){return this.accessOrder.delete(e),this.cache.delete(e)}clear(){this.cache.clear(),this.accessOrder.clear(),this.accessCounter=0}size(){return this.cache.size}evictLRU(){let e,t=1/0;for(const[r,n]of this.accessOrder)t>n&&(t=n,e=r);void 0!==e&&this.delete(e)}getStats(){const e=Array.from(this.cache.values()),t=Date.now();return{size:this.cache.size,maxSize:this.maxSize,hitRate:e.length>0?e.filter(e=>e.accessCount>1).length/e.length:0,avgAge:e.length>0?e.reduce((e,r)=>e+(t-r.timestamp),0)/e.length:0,totalAccesses:e.reduce((e,t)=>e+t.accessCount,0)}}}const kt=new class{constructor(){this.domQueryCache=new Et(200,3e3),this.exprResultCache=new Et(500,2e3),this.cssMatchCache=new Et(100,5e3),this.formValueCache=new Et(50,1e3),this.hits=0,this.misses=0}querySelector(e){const t="querySelector:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.querySelector(e);return this.domQueryCache.set(t,n),n}querySelectorAll(e){const t="querySelectorAll:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.querySelectorAll(e));return this.domQueryCache.set(t,n),n}getElementById(e){const t="getElementById:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=document.getElementById(e);return this.domQueryCache.set(t,n),n}getElementsByClassName(e){const t="getElementsByClassName:"+e,r=this.domQueryCache.get(t);if(void 0!==r)return this.hits++,r;this.misses++;const n=Array.from(document.getElementsByClassName(e));return this.domQueryCache.set(t,n),n}matches(e,t){const r=`matches:${this.getElementCacheKey(e)}:${t}`,n=this.cssMatchCache.get(r);if(void 0!==n)return this.hits++,n;this.misses++;const s=e.matches(t);return this.cssMatchCache.set(r,s),s}getExpressionResult(e){const t=this.exprResultCache.get(e);if(void 0!==t)return this.hits++,t;this.misses++}setExpressionResult(e,t){this.exprResultCache.set(e,t)}getFormValue(e){const t=this.getElementCacheKey(e),r=this.formValueCache.get("formValue:"+t);if(void 0!==r)return this.hits++,r;this.misses++}setFormValue(e,t){const r=this.getElementCacheKey(e);this.formValueCache.set("formValue:"+r,t)}invalidateElementCache(e){const t=this.getElementCacheKey(e);for(const e of[this.domQueryCache,this.cssMatchCache,this.formValueCache])for(const r of Array.from(e.cache.keys()))"string"==typeof r&&r.includes(t)&&e.delete(r)}invalidateAll(){this.domQueryCache.clear(),this.exprResultCache.clear(),this.cssMatchCache.clear(),this.formValueCache.clear(),this.hits=0,this.misses=0}getElementCacheKey(e){if(e.id)return"#"+e.id;const t=Array.from(e.classList).sort().join("."),r=this.getElementPosition(e);return`${e.tagName.toLowerCase()}${t?"."+t:""}@${r}`}getElementPosition(e){return""+Array.from(e.parentElement?.children||[]).indexOf(e)}getPerformanceStats(){const e=this.hits+this.misses;return{hits:this.hits,misses:this.misses,hitRate:Math.round(100*(e>0?this.hits/e*100:0))/100,domQueryCache:this.domQueryCache.getStats(),exprResultCache:this.exprResultCache.getStats(),cssMatchCache:this.cssMatchCache.getStats(),formValueCache:this.formValueCache.getStats()}}cleanup(){const e=Date.now();[this.domQueryCache,this.exprResultCache,this.cssMatchCache,this.formValueCache].forEach(t=>{Array.from(t.cache.entries()).forEach(([r,n])=>{e-n.timestamp>t.ttl&&t.delete(r)})})}};var xt;"undefined"!=typeof window&&setInterval(()=>{kt.cleanup()},1e4),function(e){e.IDENTIFIER="identifier",e.STRING="string",e.NUMBER="number",e.SELECTOR="selector",e.OPERATOR="operator",e.TIME="time",e.TEMPLATE="template",e.COMMENT="comment",e.SYMBOL="symbol",e.UNKNOWN="unknown"}(xt||(xt={}));const Ct=new Set(["+","-","*","/","mod"]),At=new Set(["ms","s","seconds","minutes","hours","days"]);function St(e){const t={input:"",position:0,line:1,column:1,tokens:[]};t.input=e;const r=e.length;for(;r>t.position&&(Ot(t),r>t.position);){const r=e[t.position];if("-"!==r||"-"!==Tt(t,1))if('"'!==r){if("'"===r||"'"===r){const e=Tt(t,1),r=t.tokens[t.tokens.length-1];if("s"===e&&r&&!/\s/.test(t.input[t.position-1]??" ")&&(r.kind===xt.IDENTIFIER||r.kind===xt.SELECTOR||"]"===r.value||")"===r.value||"}"===r.value)){const e=t.position;Lt(t),Lt(t),Nt(t,xt.OPERATOR,"'s",e)}else Rt(t);continue}if("`"!==r)if("<"!==r)if("#"!==r){if("."===r){if("."===Tt(t,1)){const e=t.position;Lt(t),Lt(t),Nt(t,xt.OPERATOR,"..",e);continue}const e=t.tokens[t.tokens.length-1],r=new Set(["from","to","into","on","in","at","between","first","last","next","previous","closest","random","of","some","no"]),n=e&&e.kind===xt.IDENTIFIER&&j.has(e.value.toLowerCase()),s=e&&e.kind===xt.IDENTIFIER&&r.has(e.value.toLowerCase());if((!e||e.kind===xt.OPERATOR&&")"!==e.value&&"]"!==e.value||n||s||"("===e.value||"["===e.value||"{"===e.value||","===e.value||";"===e.value)&&!(e&&e.end===t.position)&&(Ft(Tt(t))||"{"===Tt(t)||"-"===Tt(t))){$t(t);continue}}if("@"!==r)if("{"!==r)if("}"!==r){if("["===r){const e=t.tokens[t.tokens.length-1],r=e&&e.kind===xt.IDENTIFIER&&U.has(e.value)&&t.tokens.length>=2&&"on"===t.tokens[t.tokens.length-2]?.value;e&&(e.kind===xt.IDENTIFIER||")"===e.value||"]"===e.value)&&!r?(Lt(t),Nt(t,xt.OPERATOR,"[")):r?(Lt(t),Nt(t,xt.SYMBOL,"[")):(Lt(t),Nt(t,xt.OPERATOR,"["));continue}if("]"!==r){if("$"===r){const e=Tt(t,1);if(e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"===e){Bt(t);continue}}Kt(r)?Wt(t):"0">r||r>"9"?("a">r||r>"z")&&("A">r||r>"Z")&&"_"!==r?(Nt(t,xt.UNKNOWN,r),Lt(t)):Dt(t):Vt(t)}else Lt(t),Nt(t,xt.OPERATOR,"]")}else Lt(t),Nt(t,xt.OPERATOR,"}");else Lt(t),Nt(t,xt.OPERATOR,"{");else qt(t)}else $t(t);else zt(t)?Ht(t):Wt(t);else Mt(t)}else Rt(t);else jt(t)}return t.tokens}function Tt(e,t=1){const r=e.position+t;return e.input.length>r?e.input[r]:""}function Lt(e){const t=e.input[e.position];if(e.position++,"\n"===t)e.line++,e.column=1;else if("\r"===t){"\n"===(e.input.length>e.position?e.input[e.position]:"")&&e.position++,e.line++,e.column=1}else e.column++;return t}function Ot(e){const t=e.input,r=t.length;for(;r>e.position;){const r=t[e.position];if(" "!==r&&"\t"!==r&&"\r"!==r&&"\n"!==r)break;Lt(e)}}function Nt(e,t,r,n,s){const i=n??e.position-r.length,a=e.position;let o=e.column-r.length;void 0!==n&&(o=Pt(e.input,n).column);const c={kind:t,value:r,start:i,end:a,line:It(e,i),column:o};e.tokens.push(c)}function Pt(e,t){let r=1,n=-1;const s=Math.min(t,e.length);for(let t=0;s>t;t++){const s=e[t];"\n"===s?(r++,n=t):"\r"===s&&(r++,e.length>t+1&&"\n"===e[t+1]&&t++,n=t)}return{line:r,column:t-n}}function It(e,t){return Pt(e.input,t).line}function jt(e){const t=e.position;let r="";for(Lt(e),Lt(e);e.input.length>e.position;){if("\n"===e.input[e.position])break;r+=Lt(e)}Nt(e,xt.COMMENT,"--"+r,t)}function Rt(e){const t=e.position,r=Lt(e);let n=r;for(;e.input.length>e.position;){const t=Lt(e);if(n+=t,t===r)break;"\\"===t&&e.input.length>e.position&&(n+=Lt(e))}Nt(e,xt.STRING,n,t)}function Mt(e){const t=e.position;Lt(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if("`"===t){Lt(e);break}if("\\"===t){if(Lt(e),e.input.length>e.position){const t=Lt(e);switch(t){case"n":r+="\n";break;case"t":r+="\t";break;case"r":r+="\r";break;case"\\":r+="\\";break;case"`":r+="`";break;default:r+=t}}}else r+=Lt(e)}if(e.position>=e.input.length&&!e.input.endsWith("`"))throw Error(`Unterminated template literal at line ${e.line}, column ${e.column-r.length}`);Nt(e,xt.TEMPLATE,r,t)}function $t(e){const t=e.position;let r=Lt(e);if(e.position<e.input.length&&"{"===e.input[e.position]){for(r+=Lt(e);e.input.length>e.position;){const t=e.input[e.position];if(r+=Lt(e),"}"===t)break}Nt(e,xt.SELECTOR,r,t)}else{for(;e.input.length>e.position;){const t=e.input[e.position];if("\\"===t)Lt(e),e.input.length>e.position&&(r+=Lt(e));else{if(!_t(t)&&"-"!==t&&"_"!==t&&":"!==t)break;r+=Lt(e)}}Nt(e,xt.SELECTOR,r,t)}}function Ht(e){const t=e.position;if(Ut(e))return void function(e,t){const r=e.input;let n="",s=0,i="";for(;r.length>e.position;){const t=r[e.position];if(i)n+=Lt(e),t===i&&(i="");else if('"'!==t&&"'"!==t){if("<"===t){if("/"===r[e.position+1]){for(;r.length>e.position&&">"!==r[e.position];)n+=Lt(e);if(r.length>e.position&&(n+=Lt(e)),s--,0>=s)break;continue}let t=!1,i="";for(;r.length>e.position;){const s=r[e.position];if(i)n+=Lt(e),s===i&&(i="");else if('"'!==s&&"'"!==s){if(">"===s){t="/"===r[e.position-1],n+=Lt(e);break}n+=Lt(e)}else i=s,n+=Lt(e)}if(t||s++,0>=s)break;continue}n+=Lt(e)}else i=t,n+=Lt(e)}Nt(e,xt.SELECTOR,n,t)}(e,t);let r="";for(r+=Lt(e);e.input.length-1>e.position;){const t=e.input[e.position],n=e.input[e.position+1];if(r+=Lt(e),"/"===t&&">"===n){r+=Lt(e);break}}Nt(e,xt.SELECTOR,r,t)}function qt(e){const t=e.position;let r=Lt(e);for(;e.input.length>e.position;){const t=e.input[e.position];if(!_t(t)&&"_"!==t&&"-"!==t)break;r+=Lt(e)}Nt(e,xt.SYMBOL,r,t)}function Wt(e){const t=e.position;let r="";const n=e.input[e.position];if(("'"===n||"'"===n)&&"s"===Tt(e,1))return r="'s",Lt(e),Lt(e),void Nt(e,xt.OPERATOR,r,t);const s=e.input.substring(e.position,e.position+2),i=e.input.substring(e.position,e.position+3);["===","!=="].includes(i)?(r=i,Lt(e),Lt(e),Lt(e)):["==","!=","<=",">=","&&","||","**","~=","|=","^=","$=","*=","?."].includes(s)?(r=s,Lt(e),Lt(e)):r=Lt(e),Nt(e,xt.OPERATOR,r,t)}function Vt(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=Lt(e)}if(n>e.position&&"."===r[e.position]&&(e.position+1>=n||"."!==r[e.position+1]))for(s+=Lt(e);n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=Lt(e)}if(n>e.position){const t=r[e.position];if("e"===t||"E"===t){const t=n>e.position+1?r[e.position+1]:"",i=n>e.position+2?r[e.position+2]:"";if(t>="0"&&"9">=t||!("+"!==t&&"-"!==t||"0">i||i>"9"))for(s+=Lt(e),"+"!==r[e.position]&&"-"!==r[e.position]||(s+=Lt(e));n>e.position;){const t=r[e.position];if("0">t||t>"9")break;s+=Lt(e)}}}const i=e.position;let a="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z"))break;a+=Lt(e)}At.has(a)?Nt(e,xt.TIME,s+a,t):(e.position=i,Nt(e,xt.NUMBER,s,t))}function Dt(e){const t=e.position,r=e.input,n=r.length;let s="";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;s+=Lt(e)}const i=function(e,t,r){const n=t.toLowerCase(),s=e.position;if("'s"===t||"'s"===t)return!1;const i=e.tokens[e.tokens.length-1];if(i&&(i.kind===xt.IDENTIFIER||i.kind===xt.SELECTOR)){const t=e.input.length>e.position?e.input[e.position]:"";if("'"===t||"'"===t)return!1}Ot(e);let a="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;a+=Lt(e)}if(a){const t=a.toLowerCase(),s=`${n} ${t}`,i=function(e,t,r,n){const s=t.toLowerCase(),i=r.toLowerCase();if("at"===s){const t=e.position;if("the"===i){Ot(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=Lt(e)}const s=r.toLowerCase();if("start"===s||"end"===s){Ot(e);let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z")&&("0">r||r>"9")&&"_"!==r&&"-"!==r)break;t+=Lt(e)}if("of"===t.toLowerCase()){return Nt(e,xt.IDENTIFIER,`at the ${s} of`,n),!0}}return e.position=t,!1}if("start"===i||"end"===i){Ot(e);let r="";for(;e.input.length>e.position;){const t=e.input[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t&&"-"!==t)break;r+=Lt(e)}if("of"===r.toLowerCase()){return Nt(e,xt.IDENTIFIER,`at ${i} of`,n),!0}return e.position=t,!1}}return!1}(e,n,t,r);if(i)return!0;const o=function(e,t,r){const n=e.position;let s=`${t} ${r}`,i=e.position;const a=[t,r],o=8;for(;o>a.length&&(Ot(e),e.input.length>e.position);){let t="";for(;e.input.length>e.position;){const r=e.input[e.position];if(("a">r||r>"z")&&("A">r||r>"Z"))break;t+=Lt(e)}if(!t)break;a.push(t.toLowerCase());const r=a.join(" ");_.has(r)&&(s=r,i=e.position)}if(_.has(s)&&s!==`${t} ${r}`)return e.position=i,s;return e.position=n,null}(e,n,t);if(o)return Nt(e,xt.OPERATOR,o,r),!0;if(_.has(s))return Nt(e,xt.OPERATOR,s,r),!0}if(_.has(n))return e.position=s,Nt(e,xt.OPERATOR,t,r),!0;return e.position=s,!1}(e,s,t);if(i)return;const a=function(e){const t=e.toLowerCase();if("include"===t||"includes"===t)return xt.OPERATOR;if(F.has(t))return xt.OPERATOR;if(Ct.has(e)||Ct.has(t))return xt.OPERATOR;if(_.has(t))return xt.OPERATOR;return xt.IDENTIFIER}(s);Nt(e,a,s,t)}function Bt(e){const t=e.position,r=e.input,n=r.length;Lt(e);let s="$";for(;n>e.position;){const t=r[e.position];if(("a">t||t>"z")&&("A">t||t>"Z")&&("0">t||t>"9")&&"_"!==t)break;s+=Lt(e)}Nt(e,xt.IDENTIFIER,s,t)}function Ft(e){return/[a-zA-Z]/.test(e)}function _t(e){return/[a-zA-Z0-9]/.test(e)}function Ut(e){const t=e.input,r=t[e.position+1];if(!r||!/[a-zA-Z]/.test(r))return!1;let n=e.position+1,s="";for(;t.length>n&&/[a-zA-Z0-9-]/.test(t[n]);)s+=t[n],n++;return s.length>0&&-1!==t.indexOf("</"+s+">",n)}function zt(e){if(Ut(e))return!0;let t=e.position+1,r=!1;for(;e.input.length>t;){const n=e.input[t];if("/"===n&&e.input.length>t+1&&">"===e.input[t+1])return r;if(_t(n)||"."===n||"#"===n||"["===n||"]"===n||":"===n||"-"===n||"_"===n||" "===n||"="===n||'"'===n||"'"===n||"("===n||")"===n||"*"===n||"^"===n||"$"===n||"~"===n||"|"===n||">"===n||"+"===n||","===n||"{"===n||"}"===n)r=!0,t++;else{if(" "!==n&&"\t"!==n)return!1;t++}if(t-e.position>50)return!1}return!1}function Kt(e){return"+-*/^%=!<>&|(){}[],.;:?''~$".includes(e)}const Zt=new class{constructor(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0},this.startTimes=new Map}startTimer(e){this.startTimes.set(e,performance.now())}endTimer(e){const t=this.startTimes.get(e);if(t){const r=performance.now()-t;return this.startTimes.delete(e),r}return 0}recordTokenization(e){this.metrics.tokenizationTime+=e}recordEvaluation(e){this.metrics.evaluationTime+=e}updateCacheMetrics(){const e=kt.getPerformanceStats();this.metrics.cacheHitRate=e.hitRate}getMetrics(){return this.updateCacheMetrics(),{...this.metrics}}reset(){this.metrics={tokenizationTime:0,evaluationTime:0,cacheHitRate:0,memoryUsage:0,domOperations:0}}};function Gt(){kt.cleanup();Zt.getMetrics().memoryUsage>52428800&&Zt.reset()}let Qt=null;function Jt(e,t){if("number"==typeof e){if(!Number.isFinite(e))throw Error(`${t} must be a finite number, got ${e}`);return e}if("string"==typeof e){const r=e.trim();if(""===r)return 0;const n=parseFloat(r);if(isNaN(n))throw Error(`${t} cannot be converted to number: "${e}"`);return n}if("boolean"==typeof e)return e?1:0;if(null==e)return 0;if("object"==typeof e&&null!==e){if(Array.isArray(e)&&1===e.length){const r=e[0];if(Array.isArray(r))throw Error(t+" is a nested array, cannot convert to number");return Jt(r,t)}if("string"==typeof e.textContent||"value"in e){const t=e.value??e.textContent;if(null!=t){const e=(t+"").trim();if(""===e)return 0;const r=parseFloat(e);if(!isNaN(r))return r}}const r=e.valueOf();if("number"==typeof r&&Number.isFinite(r))return r}throw Error(`${t} cannot be converted to number: ${typeof e}`)}function Yt(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){const t=e.trim();if(""===t)return 0;const r=parseFloat(t);return isNaN(r)?null:r}return"boolean"==typeof e?e?1:0:null==e?0:null}function Xt(e,t){if(!Number.isFinite(e)){if(Number.isNaN(e))throw Error(t+" resulted in non-finite value: NaN");throw Error(`${t} resulted in non-finite value: ${e>0?"Infinity":"-Infinity"}`)}return e}function er(e){try{return Jt(e,"_"),!0}catch{return!1}}function tr(e,t,r){if("==="===r)return e===t;if("!=="===r)return e!==t;if(null==e||null==t)return function(e,t,r){const n=null==e,s=null==t;if(n&&s)switch(r){case"==":case">=":case"<=":return!0;default:return!1}switch(r){case"==":case">":case"<":case">=":case"<=":default:return!1;case"!=":return!0}}(e,t,r);const[n,s]=function(e,t){if("number"==typeof e&&"number"==typeof t)return[e,t];if("string"==typeof e&&"string"==typeof t){const r=parseFloat(e),n=parseFloat(t);return isNaN(r)||isNaN(n)?[e,t]:[r,n]}const r=Yt(e),n=Yt(t);if(null!==r&&null!==n)return[r,n];return[e+"",t+""]}(e,t);switch(r){case">":return n>s;case"<":return s>n;case">=":return n>=s;case"<=":return s>=n;case"==":return rr(e,t);case"!=":return!rr(e,t);default:return!1}}function rr(e,t){if(e===t)return!0;if(typeof e==typeof t)return("string"==typeof e||"number"==typeof e)&&e===t;if("number"==typeof e&&"string"==typeof t){const r=parseFloat(t);return!isNaN(r)&&e===r}if("string"==typeof e&&"number"==typeof t){const r=parseFloat(e);return!isNaN(r)&&r===t}return"boolean"==typeof e?rr(e?1:0,t):"boolean"==typeof t?rr(e,t?1:0):e+""==t+""}function nr(e,t=[]){return{isValid:!1,errors:e,suggestions:t}}function sr(e,t,r=[],n="error"){return{type:e,message:t,suggestions:r,severity:n}}function ir(e,t,r,n,s,i=!0,a){return n}function ar(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType}"undefined"!=typeof window&&function(e=3e4){Qt&&clearInterval(Qt),Qt=setInterval(Gt,e)}();const or=bt([wt(),wt()]),cr=bt([wt(),ft()]),lr={name:"equals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["is","==","equals"],async evaluate(e,t,r){try{return ir(0,0,0,t==r)}catch(e){throw e}},validate:e=>Ye(e,"equals"),inputSchema:or,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"value is 5",description:"Check if value equals 5 using loose equality",expectedOutput:!0,context:{result:5}},{input:'"5" == 5',description:'String "5" equals number 5 with type coercion',expectedOutput:!0}],relatedExpressions:["strictEquals","notEquals"],performance:{averageTime:.001,complexity:"O(1)"}}},ur={name:"strictEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["==="],evaluate:async(e,t,r)=>t===r,validate:e=>Ye(e,"strictEquals")},dr={name:"notEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=","is not","does not equal"],evaluate:async(e,t,r)=>t!=r,validate:e=>Ye(e,"notEquals")},mr={name:"strictNotEquals",category:"Comparison",evaluatesTo:"Boolean",precedence:10,associativity:"Left",operators:["!=="],evaluate:async(e,t,r)=>t!==r,validate:e=>Ye(e,"strictNotEquals")},pr={name:"lessThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<","is less than"],evaluate:async(e,t,r)=>tr(t,r,"<"),validate:e=>Ye(e,"lessThan")},hr={name:"lessThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:["<=","is less than or equal to"],evaluate:async(e,t,r)=>tr(t,r,"<="),validate:e=>Ye(e,"lessThanOrEqual")},fr={name:"greaterThan",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">","is greater than"],evaluate:async(e,t,r)=>tr(t,r,">"),validate:e=>Ye(e,"greaterThan")},yr={name:"greaterThanOrEqual",category:"Comparison",evaluatesTo:"Boolean",precedence:12,associativity:"Left",operators:[">=","is greater than or equal to"],evaluate:async(e,t,r)=>tr(t,r,">="),validate:e=>Ye(e,"greaterThanOrEqual")},gr={name:"and",category:"Logical",evaluatesTo:"Boolean",precedence:6,associativity:"Left",operators:["and","&&"],async evaluate(e,t,r){try{return ir(0,0,0,t&&r)}catch(e){throw e}},validate:e=>Ye(e,"and"),inputSchema:or,metadata:{category:"Logical",complexity:"simple",sideEffects:[],dependencies:[],returnTypes:["Boolean"],examples:[{input:"true and false",description:"Logical AND of boolean values",expectedOutput:!1},{input:"name and age",description:"Both name and age must be truthy",expectedOutput:!0,context:{variables:new Map([["name","John"],["age",25]])}}],relatedExpressions:["or","not"],performance:{averageTime:.001,complexity:"O(1)"}}},vr={name:"or",category:"Logical",evaluatesTo:"Boolean",precedence:5,associativity:"Left",operators:["or","||"],evaluate:async(e,t,r)=>t||r,validate:e=>Ye(e,"or")},br={name:"not",category:"Logical",evaluatesTo:"Boolean",precedence:15,associativity:"Right",operators:["not","!"],evaluate:async(e,t)=>!t,validate:e=>Ge(e,1,"not","operand")},wr={name:"isEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is empty","isEmpty"],async evaluate(e,t){let r;return r=null==t||($e(t)||Array.isArray(t)||t instanceof NodeList?0===t.length:!(t instanceof Node||t instanceof Element)&&(!!We(t)&&0===Object.keys(t).length)),r},validate:e=>Ge(e,1,"isEmpty","value")},Er={name:"no",category:"Logical",evaluatesTo:"Boolean",operators:["no"],async evaluate(e,t){let r;return r=null==t||(!1===t||(Array.isArray(t)||t instanceof NodeList?0===t.length:($e(t),!1))),r},validate:e=>Ge(e,1,"no","value")},kr={name:"isNotEmpty",category:"Logical",evaluatesTo:"Boolean",operators:["is not empty","isNotEmpty"],evaluate:async(e,t)=>!await wr.evaluate(e,t),validate:e=>Ge(e,1,"isNotEmpty","value")},xr={name:"exists",category:"Logical",evaluatesTo:"Boolean",operators:["exists"],evaluate:async(e,t)=>Cr(t),validate:e=>Ge(e,1,"exists","value")};function Cr(e){return null!=e&&(Array.isArray(e)?e.length>0:!("undefined"!=typeof NodeList&&e instanceof NodeList)||e.length>0)}const Ar={name:"doesNotExist",category:"Logical",evaluatesTo:"Boolean",operators:["does not exist","doesNotExist"],evaluate:async(e,t)=>!Cr(t),validate:e=>Ge(e,1,"doesNotExist","value")},Sr={name:"contains",category:"Logical",evaluatesTo:"Boolean",operators:["contains","includes","include"],async evaluate(e,t,r){let n;if(t&&r){if(ar(t)&&ar(r))return n=t.contains(r),n;if($e(t)&&t.match(/^[.#][\w-]+$/)){const e=document.querySelector(t);if(e&&ar(r))return n=e.contains(r),n;if(e&&$e(r)&&r.match(/^[.#][\w-]+$/)){const t=document.querySelector(r);return n=!!t&&e.contains(t),n}}if($e(r)&&r.match(/^[.#][\w-]+$/)&&ar(t)){const e=document.querySelector(r);return n=!!e&&t.contains(e),n}}if($e(t)&&$e(r))n=t.includes(r);else if(Array.isArray(t)||"undefined"!=typeof NodeList&&t instanceof NodeList){const e=Array.from(t);n=e.includes(r)||r instanceof Node&&e.some(e=>e instanceof Node&&e.contains(r))}else n=!(!We(t)||!$e(r))&&r in t;return n},validate:e=>Ge(e,2,"contains","container, value")},Tr={name:"doesNotContain",category:"Logical",evaluatesTo:"Boolean",operators:["does not contain","doesNotContain","does not include","doesNotInclude"],evaluate:async(e,t,r)=>!await Sr.evaluate(e,t,r),validate:e=>Ge(e,2,"doesNotContain","container, value")},Lr={name:"startsWith",category:"Logical",evaluatesTo:"Boolean",operators:["starts with","startsWith"],evaluate:async(e,t,r)=>null!=t&&null!=r&&(t+"").startsWith(r+""),validate:e=>Ge(e,2,"startsWith","str, prefix")},Or={name:"endsWith",category:"Logical",evaluatesTo:"Boolean",operators:["ends with","endsWith"],evaluate:async(e,t,r)=>null!=t&&null!=r&&(t+"").endsWith(r+""),validate:e=>Ge(e,2,"endsWith","str, suffix")},Nr={name:"between",category:"Logical",evaluatesTo:"Boolean",operators:["is between","between"],async evaluate(e,t,r,n){let s=r,i=n;if(null!=s&&null!=i&&s>i){const e=s;s=i,i=e}return null!=s&&null!=i&&t>=s&&i>=t},validate:e=>Ge(e,3,"between","value, min, max")},Pr={name:"matches",category:"Logical",evaluatesTo:"Boolean",operators:["matches"],async evaluate(e,t,r){try{let e;if(t instanceof Element&&$e(r)){const n=r;if(n.startsWith(".")||n.startsWith("#")||n.startsWith(":")||n.startsWith("[")||/^[a-zA-Z][\w-]*$/.test(n))try{e=function(e,t){return kt.matches(e,t)}(t,n)}catch(t){e=!1}else e=!1}else if($e(t)&&$e(r)){const n=t,s=r;try{e=(s.startsWith("/")&&s.endsWith("/")?RegExp(s.slice(1,-1)):RegExp(s)).test(n)}catch(t){e=n.includes(s)}}else e=!1;return ir(0,0,0,e)}catch(e){throw e}},validate:e=>Ge(e,2,"matches","element, selector"),inputSchema:cr,metadata:{category:"Logical",complexity:"medium",sideEffects:["dom-query"],dependencies:[],returnTypes:["Boolean"],examples:[{input:'element matches ".active"',description:"Check if element has active class",expectedOutput:!0},{input:'text matches "/^hello/"',description:'Check if text starts with "hello" using regex',expectedOutput:!0,context:{variables:new Map([["text","hello world"]])}}],relatedExpressions:["contains","startsWith","endsWith"],performance:{averageTime:.5,complexity:"O(n)"}}},Ir={name:"has",category:"Logical",evaluatesTo:"Boolean",operators:["has","have"],async evaluate(e,t,r){let n=!1;if(t instanceof Element&&$e(r)){const e=r;e.startsWith(".")?n=t.classList.contains(e.slice(1)):e.startsWith("[")&&e.endsWith("]")&&(n=t.hasAttribute(e.slice(1,-1)))}return n},validate:e=>Ge(e,2,"has","element, selector")},jr={name:"doesNotHave",category:"Logical",evaluatesTo:"Boolean",operators:["does not have"],evaluate:async(e,t,r)=>!await Ir.evaluate(e,t,r),validate:e=>Ge(e,2,"doesNotHave","element, selector")},Rr={equals:lr,strictEquals:ur,notEquals:dr,strictNotEquals:mr,lessThan:pr,lessThanOrEqual:hr,greaterThan:fr,greaterThanOrEqual:yr,and:gr,or:vr,not:br,no:Er,isEmpty:wr,isNotEmpty:kr,exists:xr,doesNotExist:Ar,contains:Sr,doesNotContain:Tr,startsWith:Lr,endsWith:Or,between:Nr,matches:Pr,has:Ir,doesNotHave:jr},Mr=new Set(["__proto__","constructor","prototype"]);function $r(e,t){if(e instanceof Element)return Ke(e,t);if(We(e)){if(Mr.has(t))return;return e[t]}return e[t]}function Hr(e){let t;if(Array.isArray(e))t=e;else{if(!("undefined"!=typeof NodeList&&e instanceof NodeList||"undefined"!=typeof HTMLCollection&&e instanceof HTMLCollection))return!1;t=Array.from(e)}return 0!==t.length&&t.every(e=>e instanceof Element||null!=e&&"object"==typeof e&&e.constructor!==Object&&!Array.isArray(e))}const qr={possessive:{name:"possessive",category:"Reference",evaluatesTo:"Any",operators:["'s","s"],async evaluate(e,...t){const[r,n]=t;if(null!=r){if("string"!=typeof n)throw Error("Property name must be a string");return Hr(r)&&!(n in r)?Array.from(r,e=>$r(e,n)):$r(r,n)}},validate:e=>Ge(e,2,"possessive","element, property")??Qe(e,1,"possessive","property name")},my:{name:"my",category:"Reference",evaluatesTo:"Any",operators:["my"],async evaluate(e,...t){const[r]=t;if(e.me){if("string"!=typeof r)throw Error("Property name must be a string");if(e.me instanceof Element)return Ke(e.me,r);if(We(e.me)){if(Mr.has(r))return;return e.me[r]}return e.me[r]}},validate:e=>Je(e,"my","property")},its:{name:"its",category:"Reference",evaluatesTo:"Any",operators:["its"],async evaluate(e,...t){const[r]=t;if(null==e.it)return;if("string"!=typeof r)throw Error("Property name must be a string");const n=e.it;if(n instanceof Element)return Ke(n,r);if(We(n)){if(Mr.has(r))return;return n[r]}return n[r]},validate:e=>Je(e,"its","property")},your:{name:"your",category:"Reference",evaluatesTo:"Any",operators:["your"],async evaluate(e,...t){const[r]=t;if(e.you){if("string"!=typeof r)throw Error("Property name must be a string");if(e.you instanceof Element)return Ke(e.you,r);if(We(e.you)){if(Mr.has(r))return;return e.you[r]}return e.you[r]}},validate:e=>Je(e,"your","property")},of:{name:"of",category:"Reference",evaluatesTo:"Any",operators:["of"],async evaluate(e,...t){const[r,n]=t;if(null!=n){if("string"!=typeof r)throw Error("Property name must be a string");if(n instanceof Element)return Ke(n,r);if(We(n)){if(Mr.has(r))return;return n[r]}return n[r]}},validate:e=>Ge(e,2,"of","property, object")??Qe(e,0,"of","property name")},attribute:{name:"attribute",category:"Reference",evaluatesTo:"String",operators:["@"],async evaluate(e,...t){const[r,n]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");const s=n||e.me;return s&&s instanceof Element?s.getAttribute(r):null},validate:e=>tt(e,1,2,"attribute","attributeName, optional element")??Qe(e,0,"attribute","attribute name")??(2>e.length||null==e[1]||e[1]instanceof Element?null:"attribute element must be an Element")},attributeWithValue:{name:"attributeWithValue",category:"Reference",evaluatesTo:"Boolean",operators:["@="],async evaluate(e,...t){const[r,n,s]=t;if("string"!=typeof r)throw Error("Attribute name must be a string");if("string"!=typeof n)throw Error("Expected value must be a string");const i=s||e.me;if(!(i&&i instanceof Element))return!1;return i.getAttribute(r)===n},validate:e=>tt(e,2,3,"attributeWithValue","attributeName, expectedValue, optional element")??Qe(e,0,"attributeWithValue","attribute name")??Qe(e,1,"attributeWithValue","expected value")??(3>e.length||null==e[2]||e[2]instanceof Element?null:"attributeWithValue element must be an Element")},classReference:{name:"classReference",category:"Reference",evaluatesTo:"Array",operators:["."],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("Class name must be a string");const n=r.startsWith(".")?r.slice(1):r,s=document.getElementsByClassName(n);return Array.from(s)},validate:e=>Je(e,"classReference","className")},idReference:{name:"idReference",category:"Reference",evaluatesTo:"Element",operators:["#"],async evaluate(e,...t){const[r]=t;if("string"!=typeof r)throw Error("ID value must be a string");const n=r.startsWith("#")?r.slice(1):r;return document.getElementById(n)},validate:e=>Je(e,"idReference","idValue")}};function Wr(e){return Array.isArray(e)?e:null==e?[]:"string"==typeof e?[e]:e instanceof NodeList||e instanceof HTMLCollection||"number"==typeof e.length?Array.from(e):[e]}!function(){if("undefined"!=typeof localStorage)try{const e=localStorage,t=e.getItem("hyperfixi:debug")||e.getItem("lokascript:debug");if("*"===t||"true"===t)return!0}catch{}!("undefined"==typeof window||!window.__HYPERFIXI_DEBUG__)||"undefined"!=typeof process&&process}();const Vr={command:(...e)=>{},event:(...e)=>{},parse:(...e)=>{},expr:(...e)=>{},expressions:(...e)=>{},style:(...e)=>{},runtime:(...e)=>{},loop:(...e)=>{},async:(...e)=>{}};function Dr(e){return e.kind===xt.IDENTIFIER&&j.has(e.value.toLowerCase())}function Br(e){return e.kind===xt.IDENTIFIER&&z.has(e.value.toLowerCase())}function Fr(e){return e.kind===xt.IDENTIFIER&&U.has(e.value.toLowerCase())}function _r(e){return e.kind===xt.IDENTIFIER&&B.has(e.value.toLowerCase())}function Ur(e){return _.has(e.value.toLowerCase())}function zr(e){return e.kind===xt.IDENTIFIER}function Kr(e){return e.kind===xt.SELECTOR}function Zr(e){return e.kind===xt.SELECTOR&&!e.value.startsWith("<")}function Gr(e){return e.kind===xt.STRING||e.kind===xt.NUMBER||e.kind===xt.TEMPLATE}function Qr(e){return e.kind===xt.IDENTIFIER}function Jr(e){return e.kind===xt.TIME}function Yr(e){return e.kind===xt.SYMBOL}function Xr(e){return e.kind===xt.COMMENT}function en(e){if(e.kind!==xt.IDENTIFIER)return!1;const t=e.value.toLowerCase();return!(j.has(t)||z.has(t)||U.has(t)||B.has(t))}function tn(e){return e.kind===xt.STRING}function rn(e){return e.kind===xt.NUMBER}function nn(e){if(e.kind===xt.IDENTIFIER){const t=e.value;return"true"===t||"false"===t||"null"===t||"undefined"===t}return!1}function sn(e){return e.kind===xt.TEMPLATE}function an(e){return e.kind===xt.SELECTOR&&e.value.startsWith("<")}function on(e){return e.kind===xt.SELECTOR&&e.value.startsWith("#")}function cn(e){return e.kind===xt.SELECTOR&&e.value.startsWith(".")}function ln(e){return e.kind===xt.SELECTOR&&(!e.value.startsWith("#")&&!e.value.startsWith("."))}function un(e){if(e.kind!==xt.OPERATOR)return!1;const t=e.value.toLowerCase();return!F.has(t)&&!_.has(t)}function dn(e){const t=e.value.toLowerCase();return"then"===t||"and"===t||"else"===t||"end"===t||"on"===t}function mn(e,t,r){return{type:"literal",value:e,raw:t,start:r.start,end:r.end,line:r.line,column:r.column}}function pn(e,t){return{type:"identifier",name:e,start:t.start,end:t.end,line:t.line,column:t.column}}function hn(e,t,r,n){return{type:"binaryExpression",operator:e,left:t,right:r,start:n.start,end:n.end,line:n.line,column:n.column}}function fn(e,t){return{type:"block",commands:e,start:t.start,end:t.end,line:t.line,column:t.column}}function yn(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function gn(e,t){return{type:"objectLiteral",properties:e,start:t.start,end:t.end,line:t.line,column:t.column}}function vn(e,t){return{type:"arrayLiteral",elements:e,start:t.start,end:t.end,line:t.line,column:t.column}}function bn(e,t,r){return{type:"propertyOfExpression",property:e,target:t,start:r.start,end:r.end,line:r.line,column:r.column}}function wn(e,t,r){return{type:"command",name:"__ERROR__",args:[],diagnostics:[{message:t,severity:"error",code:"parse-error",line:e.line,column:e.column,...r&&{source:r}}],start:e.start,end:e.end,line:e.line,column:e.column}}function En(e){return e}function kn(e){return e}function xn(e,t){return!!e&&t.some(t=>e.value===t||e.value.toLowerCase()===t)}const Cn=[s,o,i,a];function An(e,t=[]){if(e.isAtEnd())return!0;for(const t of Cn)if(e.check(t))return!0;for(const r of t)if(e.check(r))return!0;return!!e.checkIsCommand()}function Sn(e,t=[]){if(!An(e,t))return e.parseExpression()}function Tn(e,t){return!!e.check(t)&&(e.advance(),!0)}function Ln(e){const t=e.savePosition();let r;if(e.checkIdentifierLike()){const n=e.peek().value;e.advance(),e.check(":")?(e.advance(),r=n):e.restorePosition(t)}const n=e.parseExpression();return void 0!==r?{name:r,value:n}:{value:n}}class On{constructor(e){this.args=[],this.isBlocking=!1,this.name=e}static from(e){const t=new On(e.value);return t.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},t}static fromIdentifier(e){const t=new On(e.name);return void 0!==e.start&&(t.startPos={start:e.start,end:e.end??0,line:e.line??1,column:e.column??1}),t}static named(e){return new On(e)}withArgs(...e){return this.args.push(...e),this}withBody(e){return this.body=e,this}withImplicitTarget(e){return this.implicitTarget=e,this}withModifier(e,t){return this.modifiers||(this.modifiers={}),this.modifiers[e]=t,this}withModifiers(e){return this.modifiers={...this.modifiers,...e},this}withName(e){return this.name=e,this}withOriginalCommand(e){return this.originalCmd=e,this}blocking(e=!0){return this.isBlocking=e,this}startingAt(e){return this.startPos={start:e.start??0,end:e.end??0,line:e.line??1,column:e.column??1},this}endingAt(e){return this.endPos={start:e.start??this.startPos?.start??0,end:e.end,line:e.line??this.startPos?.line??1,column:e.column??this.startPos?.column??1},this}build(){const e={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&&(e.body=this.body),this.implicitTarget&&(e.implicitTarget=this.implicitTarget),this.modifiers&&(e.modifiers=this.modifiers),this.originalCmd&&(e.originalCommand=this.originalCmd),e}clone(){const e=new On(this.name);return e.args=[...this.args],e.body=this.body?[...this.body]:void 0,e.implicitTarget=this.implicitTarget,e.isBlocking=this.isBlocking,e.modifiers=this.modifiers?{...this.modifiers}:void 0,e.originalCmd=this.originalCmd,e.startPos=this.startPos?{...this.startPos}:void 0,e.endPos=this.endPos?{...this.endPos}:void 0,e}}function Nn(e,t){const r=[];let n="";const s=e.peek().start||0,i=e.peek().line||1,a=e.peek().column||1;if(e.checkIdentifierLike()){for(n=e.advance().value;e.check(":")&&!e.isAtEnd();)e.advance(),n+=":",e.checkIdentifierLike()&&(n+=e.advance().value);if(e.check("(")){e.advance();const t=[];for(;!e.isAtEnd()&&!e.check(")");){const{name:r,value:n}=Ln(e);if(t.push(void 0!==r?{type:"objectLiteral",properties:[{key:{type:"identifier",name:r},value:n}],start:n.start,end:n.end,line:n.line,column:n.column}:n),e.check(","))e.advance();else if(!e.check(")"))break}e.check(")")&&e.advance(),r.push({type:"functionCall",name:n,args:t,start:s,end:e.getPosition().end,line:i,column:a})}else r.push({type:"string",value:n,start:s,end:e.getPosition().end,line:i,column:a})}const o=[...r],c={};for(;!An(e);){if(e.check(x)||e.check(g)){e.advance();const t=Sn(e,[b]);t&&(c.on=t);continue}if(e.check(b)){e.advance();const t=[];for(;!An(e,[x,g]);){const r=e.savePosition(),n=e.parsePrimary();n&&t.push(n),e.savePosition()===r&&e.advance()}const r=t[0],n=t[t.length-1];c.with=En({type:"arrayLiteral",elements:t,...void 0!==r?.start?{start:r.start}:{},...void 0!==n?.end?{end:n.end}:{},...void 0!==r?.line?{line:r.line}:{},...void 0!==r?.column?{column:r.column}:{}});continue}const t=e.savePosition(),r=e.parsePrimary();r&&o.push(r),e.savePosition()===t&&e.advance()}const l=On.fromIdentifier(t).withArgs(...o);return Object.keys(c).length>0&&l.withModifiers(c),l.endingAt(e.getPosition()).build()}function Pn(e,t){const r=On.fromIdentifier(t);if(e.check(N)){const t=e.advance(),n=e.check(A)?e.advance():t;r.withModifier("the",{type:"literal",value:"event",start:t.start,end:n.end,line:t.line,column:t.column})}return r.endingAt(e.getPosition()).build()}function In(e,t){const r=[],n=()=>e.check(a)||t&&e.check(i);for(;!e.isAtEnd()&&!n();){if(Xr(e.peek())){e.advance();continue}if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))break;e.advance();const t=e.parseCommand();t&&r.push(t),(e.check(s)||e.check(o)||e.check(","))&&e.advance()}return r}const jn=new Set(["is","am","are","not","no","and","or","==","===","!=","!==","<",">","<=",">=","+","-","*","/","mod"]);function Rn(e,t,r){return null!==t&&(!jn.has(t.value?.toLowerCase?.()??"")&&(e.checkIsCommand()||e.isCommand(r.value?.toLowerCase())))}function Mn(e,t){const r=[];let n=!1;const o=e.savePosition();let l=null;for(let r=0;500>r&&!e.isAtEnd();r++){const r=e.peek();if(r.value===s){n=!0;break}if(r.value===a||r.value===T||r.value===S||r.value===x)break;if(void 0!==r.line&&r.line!==t.line&&Rn(e,l,r))break;Xr(r)||(l=r),e.advance()}e.restorePosition(o);let u=!1;if(!n){const r=e.savePosition(),n=t.line,s=100;let o=!1,c=null;for(;!e.isAtEnd()&&s>e.current-r;){const t=e.peek(),r=t.value?.toLowerCase();if(o&&void 0!==t.line&&t.line!==n)break;if(r===T||r===S||r===x)break;if(r===i||r===a){t.line===n&&(u=!0);break}if(Rn(e,c,t)){if(void 0!==t.line&&t.line!==n){u=!0;break}o=!0}Xr(t)||(c=t),e.advance()}e.restorePosition(r)}const d=n||u;let m;if(d)m=e.parseExpression();else{const r=[],n=20;let i=0,a=!0;for(;!e.isAtEnd()&&!e.check(s)&&(a||!e.checkIsCommand()&&!e.isCommand(e.peek().value))&&n>i;){a=!1;const t=e.savePosition();r.push(e.parseLogicalAnd()),e.savePosition()===t&&e.advance(),i++}if(0===r.length)throw Error("Expected condition after if/unless");m=1===r.length?r[0]:{type:"expression",tokens:r,start:r[0].start,end:r[r.length-1].end,line:t.line,column:t.column}}if(r.push(m),d){Tn(e,s);const n=In(e,!0);if(0===n.length&&e.isAtEnd())throw Error("Expected command after 'then' in if statement - incomplete conditional");r.push(fn(n,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}));let o=!1;if(e.check(i))if(e.advance(),e.check(c)){const t=e.peek();e.advance();const n=Mn(e,t);r.push(fn([n],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column})),o=!0}else{const n=In(e,!1);r.push(fn(n,{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}o||e.isAtEnd()||e.consume(a,"Expected 'end' after if block")}else{if(!e.checkIsCommand()&&!e.isCommand(e.peek().value))throw Error("Expected command after if condition in single-line form");{e.advance();const n=e.parseCommand();r.push(fn([n],{start:t.start,end:e.getPosition().end,line:t.line,column:t.column}))}}return On.from(t).withArgs(...r).endingAt(e.getPosition()).build()}function $n(e,t){const r=[],n={};if(e.checkAnySelector()||e.checkContextVar()||e.match("<")){const t=e.parsePrimary();if(r.push(t),e.match("*")){if(e.checkIdentifierLike()){const t=e.advance();r.push({type:"identifier",name:"*"+t.value,start:t.start-1,end:t.end,line:t.line,column:t.column})}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}}else if(e.checkIdentifierLike()){const t=e.parsePrimary();r.push(t)}if(e.match("and")&&e.match("set")&&e.checkIdentifierLike()){const t=e.advance();n.set={type:"identifier",name:t.value,start:t.start,end:t.end,line:t.line,column:t.column}}const s=On.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}const Hn=new Set(["my","its","your"]);function qn(e){return{type:"literal",value:e,raw:e}}function Wn(e){const t={};if(Tn(e,l)){const r=e.parseExpression();return r&&(t.for=r),t}if(!e.check(d))return t;e.advance();const r=e.peek();if(!r||!zr(r))return t;e.advance();let n=r.value;if(e.check(":")){e.advance();const t=e.peek();t&&zr(t)&&(e.advance(),n=`${n}:${t.value}`)}if(t.until=qn(n),Tn(e,v)){const r=Sn(e);r&&(t.from=r)}return t}function Vn(e,t){const r=[],n=Sn(e,[v]);n&&r.push(n);const s={};if(Tn(e,v)){const t=Sn(e);t&&(s.from=t)}return On.fromIdentifier(t).withArgs(...r).withModifiers(s).endingAt(e.getPosition()).build()}function Dn(e,t){const r=[],n={};if(e.check(k)){e.advance();const t=[],r=Sn(e,[o]);if(r&&"binaryExpression"===r.type&&"and"===r.operator)r.left&&t.push(r.left),r.right&&t.push(r.right);else{r&&t.push(r),Tn(e,o);const n=Sn(e,[v,x,l]);n&&t.push(n)}const s=t[0],i=t[t.length-1];n.between={type:"arrayLiteral",elements:t,...void 0!==s?.start?{start:s.start}:{},...void 0!==i?.end?{end:i.end}:{},...void 0!==s?.line?{line:s.line}:{},...void 0!==s?.column?{column:s.column}:{}}}else{const t=Sn(e,[v,x]),s="asExpression"===t?.type?function(e){const t="string"==typeof e?e:e?.name;return"modal"===t||"non-modal"===t?t:void 0}(t.targetType):void 0;t&&void 0!==s&&t.expression?(r.push(t.expression),n.as=qn(s)):t&&r.push(t),void 0===s&&e.check("modal")&&(e.advance(),n.as=qn("modal"))}if(Tn(e,v)||Tn(e,x)){const t=Sn(e);t&&(n.on=t)}return On.fromIdentifier(t).withArgs(...r).withModifiers({...n,...Wn(e)}).endingAt(e.getPosition()).build()}function Bn(e){if(!e.check("using"))return{};if(e.advance(),!e.match("view"))throw Error("expected 'view transition' after 'using'");if(!e.match("transition"))throw Error("expected 'transition' after 'using view'");return{viewTransition:qn("transition")}}function Fn(e,t){const r=[];if(e.match("{"))r.push(e.parseCSSObjectLiteral());else{const t=Sn(e,[g]);t&&r.push(t)}const n={};if(Tn(e,g)){const t=Sn(e);t&&(n.to=t)}return On.from(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}function _n(e,t){const r=e.parseExpression();if(!r)return e.addError("Put command requires content expression"),null;const n=e.peek();if(!n||!q.includes(n.value))return e.addError(`Expected operation keyword (${q.join(", ")}) after put expression, got: ${n?.value}`),null;let s=e.advance().value;const i=s.toLowerCase();"at start of"===i||"at the start of"===i?s=$:"at end of"===i||"at the end of"===i?s=H:s===M&&(e.check(P)||e.check(N)?(Tn(e,N),e.check(P)&&(e.advance(),e.check(w)&&(e.advance(),s=$))):e.check(a)&&(e.advance(),e.check(w)&&(e.advance(),s=H)));const o=e.parseExpression();return o?On.fromIdentifier(t).withArgs(r).withModifier(s,o).endingAt(e.getPosition()).build():(e.addError("Put command requires target expression after operation keyword"),null)}const Un=["afterbegin","afterend","beforebegin","beforeend","delete","innerhtml","innermorph","into","morph","none","outerhtml","outermorph","over"];function zn(e,t){const r=[],n={};if(!e.isAtEnd()){const t=e.peek(),r=t?.value?.toLowerCase();r&&Un.includes(r)&&(e.advance(),n.strategy=qn(r))}const s="delete"===n.strategy?.value;Tn(e,w);const i=s?e.parseExpression():Sn(e,[b]);if(i&&r.push(i),!s&&Tn(e,b)){const t=Sn(e,["using"]);t&&(n.with=t)}return On.fromIdentifier(t).withArgs(...r).withModifiers({...n,...Bn(e)}).endingAt(e.getPosition()).build()}function Kn(e,t){const r=[],n={};if(!(An(e,["catch","finally"])||e.check(C)||e.check("where")||e.check(b))){const t=e.parseExpression();t&&r.push(t)}if(Tn(e,b)){const t=function(e){if(!e)return null;const t="string"==typeof e.name?e.name:"string"==typeof e.value?e.value:null;return null===t?null:t.replace(/^\*/,"")}(e.parseExpression());null!==t&&(n.with=qn(t))}const s=On.fromIdentifier(t).withArgs(...r).endingAt(e.getPosition());return Object.keys(n).length>0&&s.withModifiers(n),s.build()}function Zn(e,t){const r=e.savePosition();let n=null,c=[];try{n=function(e){if(!e.check(":"))return null;if(e.advance(),e.check(":")){e.advance();const t=e.advance();return{type:"identifier",name:t.value,scope:"global",start:t.start-2,end:t.end}}const t=e.advance();return{type:"identifier",name:t.value,scope:"element",start:t.start-1,end:t.end}}(e)??function(e){if(!e.check(L)&&!e.check(O))return null;const t=e.advance(),r=e.advance();return{type:"identifier",name:r.value,scope:t.value,start:t.start,end:r.end}}(e)??function(e){if(!e.check(N))return null;const t=e.savePosition();e.advance();const r=e.parseExpression();if(!r)return e.restorePosition(t),null;if("binaryExpression"===r.type&&r.operator===w){const e=r.left,t=r.right;return bn(e,t,{start:e.start??0,end:t.end??0,line:e.line??1,column:e.column??1})}return e.check(g)?r:(e.restorePosition(t),null)}(e),n||(n=e.parseExpression())}catch{e.restorePosition(r),n=null}if(!n){const t=function(e){if(e.match(":")){const t=e.advance();return{expression:{type:"identifier",name:t.value,scope:"element",start:t.start,end:t.end},tokens:[]}}const t=[];for(;!(e.isAtEnd()||e.check(g)||e.check(s)||e.check(o)||e.check(i)||e.check(a));)t.push(e.parsePrimary());if(0===t.length)return{expression:null,tokens:[]};if(t.length>=4){const e=(e,t)=>e[t];if(e(t[0],"value")===N&&e(t[2],"value")===w){const r=t[1],n=t[3];return{expression:bn(pn(e(r,"value")||e(r,"name")||"",{start:r.start??0,end:r.end??0,line:r.line??1,column:r.column??1}),{type:"idSelector"===n.type?"idSelector":"cssSelector",value:e(n,"value")||e(n,"name")||"",start:n.start??0,end:n.end??0,line:n.line,column:n.column},{start:t[0].start??0,end:n.end??0,line:t[0].line??1,column:t[0].column??1}),tokens:[]}}}return 1===t.length?{expression:t[0],tokens:[]}:{expression:null,tokens:t}}(e);n=t.expression,c=t.tokens}if(!e.check(g)){const t=e.isAtEnd()?"end of input":e.peek().value;throw Error("Expected 'to' in set command, found: "+t)}e.advance();const l=e.parseExpression()??e.parsePrimary();let u;var d;e.check(x)&&((d=e.peekAt(1))&&("selector"===d.kind||d.value.startsWith("<")||Gn.has(d.value)))&&(e.advance(),u=Sn(e));const m=[];n?m.push(n):c.length>0&&m.push(...c);const p=On.fromIdentifier(t).withArgs(...m);return l&&p.withModifier("to",l),u&&p.withModifier("on",u),p.endingAt(e.getPosition()).build()}const Gn=new Set(["me","my","it","its","you","your","yourself"]);const Qn=new Set(["top","middle","bottom","left","center","right","nearest"]);function Jn(e,t){return{type:"string",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}function Yn(e){if(e.isAtEnd())return;const t=e.current,r=e.parsePrimary();return e.current===t?void 0:r}const Xn=new Set(["then","and","else","end","when","where","catch","finally"]);function es(e,t){return e.isAtEnd()?null:"to"===e.resolveKeyword(e.peek().value).toLowerCase()?function(e,t){const r=[],n={};e.advance();for(;!An(e,["when","where","catch","finally"]);){const t=e.peek(),s=e.resolveKeyword(t.value).toLowerCase();if("the"!==s)if(!ts.has(s)||n.position){if("of"===s){e.advance();const t=Sn(e,ns);t&&(n.of=t);continue}if(!ss(e,n)){if(0===r.length&&!n.of){const t=Sn(e,ns);if(t){r.push(t);continue}}break}}else e.advance(),n.position=Jn(s,t);else e.advance()}return On.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(e,t):function(e){for(let t=0;12>t;t++){const r=e.peekAt(t);if(!r)return!1;const n=e.resolveKeyword(r.value).toLowerCase();if("by"===n)return!0;if(Xn.has(n))return!1}return!1}(e)?function(e,t){const r=[],n={};for(;!An(e,["when","where","catch","finally"]);){const t=e.peek(),s=e.resolveKeyword(t.value).toLowerCase();if(rs.has(s))e.advance(),n.direction=Jn(s,t);else{if("by"===s){e.advance();let t=1;const r=e.peek();"+"!==r.value&&"-"!==r.value||(e.advance(),"-"===r.value&&(t=-1));const s=e.peek();if("number"===s.kind){e.advance();const r=e.peek();let i=s.end;e.isAtEnd()||"px"!==r.value||r.start!==s.end||(i=e.advance().end),n.by=En({type:"literal",value:t*Number(s.value),raw:s.value,start:s.start,end:i,line:s.line,column:s.column})}else{const t=Sn(e,ns);t&&(n.by=t)}continue}if(!ss(e,n)){if(0===r.length){const t=Sn(e,ns);if(t){r.push(t);continue}}break}}}return On.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(e,t):null}const ts=new Set(["top","middle","bottom","left","center","right","nearest"]),rs=new Set(["up","down","left","right"]),ns=["of","smoothly","instantly","by","up","down","left","right"];function ss(e,t){const r=e.peek(),n=e.resolveKeyword(r.value).toLowerCase();return("smoothly"===n||"instantly"===n)&&(e.advance(),t.behavior=Jn("smoothly"===n?"smooth":"instant",r),!0)}function is(e,t){const r=[],n={};if(Tn(e,"url"),!e.isAtEnd()&&ps(e)){const t=fs(e);t&&r.push(t)}else{const t=Sn(e,["with"]);t&&r.push(t)}if(Tn(e,"with")){Tn(e,"title");const t=Sn(e);t&&(n.title=t)}return On.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}function as(e,t){if(e.isAtEnd())return!0;const r=e.peek();return(!e.checkIsCommand()||"("!==e.peekAt(1)?.value)&&(!!An(e,["catch","finally","on"])||xn(r,[...t.markers]))}function os(e,t,r,n){const s=[],i={};if("none"!==n.positional){const t=n.continuation??[];for(;!as(e,n);){const r="expression"===n.positional?e.parseExpression():e.parsePrimary();if(!r)break;if(s.push(r),e.match(","))continue;if("primary"===n.positional)continue;const i=r.name;if("identifier"===r.type&&i&&t.includes(i.toLowerCase()))continue;const a=e.peek();if(!a||!t.includes(a.value.toLowerCase()))break;e.advance(),s.push(e.createIdentifier(a.value))}}const a=new Set(n.commaList??[]);for(;!e.isAtEnd()&&xn(e.peek(),[...n.markers]);){const t=e.advance().value,r=e.resolveKeyword(t).toLowerCase();let n=e.parseExpression();if(n&&a.has(r)&&e.check(",")){const t=[n];for(;e.match(",");){const r=e.parseExpression();if(!r)break;t.push(r)}const r=t[0];n={type:"arrayLiteral",elements:t,start:r.start,end:t[t.length-1].end,line:r.line,column:r.column}}n&&(i[r]=n)}const o=On.from(t).withName(r).withArgs(...s);return Object.keys(i).length>0&&o.withModifiers(i),o.endingAt(e.getPosition()).build()}const cs=new Map([["put",_n],["trigger",Nn],["send",Nn],["remove",Vn],["take",function(e,t){const r=[],n={},s=Sn(e,[v,l]);if(s&&r.push(s),Tn(e,v)){const t=Sn(e,[l]);t&&(n.from=t)}if(Tn(e,l)){const t=Sn(e);t&&(n.for=t)}return On.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}],["toggle",Dn],["set",Zn],["add",(e,t)=>Fn(e,us(t))],["halt",Pn],["measure",$n],["js",function(e,t){const r=[];if(e.match("(")){for(;!e.check(")")&&!e.isAtEnd();)e.checkIdentifierLike()&&r.push(e.advance().value),e.match(",");e.consume(")","Expected ) after js parameters")}const n=e.peek().start,s=function(e,t){const r=e.getInputSlice(t);if(!r)return t;let n=0;for(;r.length>n;){const e=r[n];if("'"!==e&&"\u2019"!==e&&"\u2018"!==e)if('"'!==e)if("`"!==e)if("/"===e&&n+1<r.length&&"/"===r[n+1])for(n+=2;r.length>n&&"\n"!==r[n];)n++;else if("/"===e&&n+1<r.length&&"*"===r[n+1]){for(n+=2;r.length>n&&("*"!==r[n]||n+1>=r.length||"/"!==r[n+1]);)n++;n+=2}else{if(("e"===e||"E"===e)&&r.length>=n+3&&"end"===r.slice(n,n+3).toLowerCase()){if((0===n||!/[a-zA-Z0-9_]/.test(r[n-1]))&&(n+3>=r.length||!/[a-zA-Z0-9_]/.test(r[n+3])))return t+n}n++}else{for(n++;r.length>n&&"`"!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&'"'!==r[n];)"\\"===r[n]&&n++,n++;n++}else{for(n++;r.length>n&&r[n]!==e;)"\\"===r[n]&&n++,n++;n++}}return t+r.length}(e,n);for(;!e.isAtEnd()&&!e.check(a)&&e.peek().start<s;)e.advance();e.consume(a,"Expected end after js code body");const i=e.getInputSlice(n,s),o={type:"literal",value:i.trim(),start:t.start,end:e.getPosition().end},c={type:"arrayLiteral",elements:r.map(e=>({type:"literal",value:e,start:t.start,end:t.end})),start:t.start,end:e.getPosition().end};return On.fromIdentifier(t).withArgs(o,c).endingAt(e.getPosition()).build()}],["go",function(e,t){const r=[],n={};for(;!An(e,["when","where","catch","finally"]);){const t=e.peek(),s=e.resolveKeyword(t.value).toLowerCase();if("to"!==s&&"the"!==s)if("back"!==s&&"forward"!==s||0!==r.length||n.url){if("url"===s){e.advance();const t=ps(e)?fs(e):Yn(e);t&&(n.url=t);continue}if("in"===s){e.advance();const t=e.peek(),r=[];for(;!e.isAtEnd()&&["new","window"].includes(e.peek().value.toLowerCase());)r.push(e.advance().value.toLowerCase());n.in=Jn(r.join(" ")||t.value,t);continue}if(!Qn.has(s)||n.position){if("of"===s){e.advance(),"the"===e.resolveKeyword(e.peek().value).toLowerCase()&&e.advance();const t=Yn(e);t&&(n.of=t);continue}if("smoothly"!==s&&"instantly"!==s){if("+"===t.value||"-"===t.value||"number"===t.kind){let r=1;"+"!==t.value&&"-"!==t.value||(e.advance(),"-"===t.value&&(r=-1));const s=e.peek();if("number"!==s.kind)break;e.advance();let i=s.end;const a=e.peek();e.isAtEnd()||"px"!==a.value||a.start!==s.end||(i=e.advance().end),n.by=En({type:"literal",value:r*Number(s.value),raw:s.value,start:t.start,end:i,line:t.line,column:t.column});continue}if(0===r.length&&!n.of&&!n.url){if(ps(e)){const t=fs(e);if(t){r.push(t);continue}}const t=Yn(e);if(t){r.push(t);continue}}break}e.advance(),n.behavior=Jn("smoothly"===s?"smooth":"instant",t)}else e.advance(),n.position=Jn(s,t)}else e.advance(),n[s]=Jn(s,t);else e.advance()}return On.fromIdentifier(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}],["push",is],["replace",is],["scroll",(e,t)=>es(e,t)??ms(e,t)],["tell",function(e,t){const r=e.parseExpression();if(!r)throw Error("tell command requires a target expression");e.check(g)&&e.advance();const n=[];for(;!e.isAtEnd();){if(e.checkIsCommand()){try{e.advance();const t=e.parseCommand();if(!t)break;n.push(t)}catch{break}if(e.match(o)||e.match(s))continue;if(e.check(i))break;if(e.check(a)){e.advance();break}if(e.checkIsCommand())continue;break}break}if(0===n.length)throw Error("tell command requires at least one command after the target");return On.fromIdentifier(t).withArgs(r,...n).endingAt(e.getPosition()).build()}],["pick",function(e,t){const r=On.fromIdentifier(t);Tn(e,N);const n=e.peek().value,s=e=>({type:"literal",value:e,start:t.start,end:t.end}),i=()=>{if(!e.match("of","from"))throw Error("pick: expected 'of' or 'from' before source expression");return e.parseExpression()};if("first"===n){e.advance();const t=e.parsePrimary(),n=i();return r.withArgs(n).withModifier("variant",s("first")).withModifier("count",t).endingAt(e.getPosition()).build()}if("last"===n){e.advance();const t=e.parsePrimary(),n=i();return r.withArgs(n).withModifier("variant",s("last")).withModifier("count",t).endingAt(e.getPosition()).build()}if("random"===n){let t;e.advance(),e.check("of")||e.check("from")||(t=e.parsePrimary());const n=i(),a=r.withArgs(n).withModifier("variant",s("random"));return t&&a.withModifier("count",t),a.endingAt(e.getPosition()).build()}if("item"===n||"items"===n||"character"===n||"characters"===n){let t,n;e.advance(),e.match("at","from"),t=e.match("start")?s("start"):e.parsePrimary();let a=!1;(e.match("to")||e.match(".."))&&(e.match("end")?a=!0:n=e.parsePrimary());let o="default";e.match("inclusive")?o="inclusive":e.match("exclusive")&&(o="exclusive");const c=i(),l=r.withArgs(c).withModifier("variant",s("range")).withModifier("rangeStart",t).withModifier("rangeMode",s(o));return a?l.withModifier("rangeEnd",s("end")):n&&l.withModifier("rangeEnd",n),l.endingAt(e.getPosition()).build()}if("match"===n||"matches"===n){e.advance(),e.match("of");const t=e.parsePrimary();let a;e.matchOperator("|")&&(a=e.advance().value);const o=i(),c=r.withArgs(o).withModifier("variant",s("match"===n?"match":"matches")).withModifier("regex",t);return a&&c.withModifier("flags",s(a)),c.endingAt(e.getPosition()).build()}return ms(e,t)}],["start",function(e,t){if(!e.match("view"))throw Error("start: expected 'view transition' (only `start view transition ... end` is supported)");if(!e.match("transition"))throw Error("start view: expected 'transition'");const r={};if(e.match("using")){const t=e.parsePrimary();r.transitionName=t}const n=e.parseCommandListUntilEnd("start view transition");return On.fromIdentifier(t).withArgs(...n).withModifiers(r).endingAt(e.getPosition()).build()}],["swap",zn],["morph",zn],["show",Kn],["hide",Kn],["process",(e,t)=>function(e,t){if(!e.check("partials"))return null;const r=[];if(e.advance(),Tn(e,y)){const t=Sn(e,["using"]);t&&r.push(t)}const n=Bn(e),s=On.fromIdentifier(t).withArgs(...r);return Object.keys(n).length>0&&s.withModifiers(n),s.endingAt(e.getPosition()).build()}(e,t)??ms(e,t)]]),ls=new Set(cs.keys());function us(e){return{kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0}}const ds={positional:"primary",markers:[]};function ms(e,t){return os(e,us(t),t.name.toLowerCase(),ds)}function ps(e){const t=e.peek();if("/"===t.value)return!0;if(e.checkIdentifierLike()){const r=e.peekAt(1);return!!r&&":"===r.value&&r.start===t.end}return!1}const hs=new Set(["{",")"]);function fs(e){const t=e.savePosition(),r=e.peek();let n="",s=null;for(;!e.isAtEnd();){const t=e.peek();if(s&&t.start!==s.end)break;if("$"===t.value&&"{"===e.peekAt(1)?.value){e.advance();let r=e.advance(),i=1;for(;!e.isAtEnd()&&i>0;)r=e.advance(),"{"===r.value?i++:"}"===r.value&&i--;n+=e.getInputSlice(t.start,r.end),s=r;continue}if(hs.has(t.value))break;s=e.advance(),n+=s.value}if(!n||"/"===n)return e.restorePosition(t),null;const i={start:r.start,end:s?s.end:r.end,line:r.line,column:r.column};return n.includes("${")?{type:"templateLiteral",value:n,...i}:{type:"literal",value:n,raw:n,...i}}function ys(e){if(e.check("{"))return!1;if(!e.checkIdentifierLike())return!1;const t=e.peekAt(1);return null!==t&&":"===t.value}function gs(e){const t=[],r=e.getPosition();do{if(!e.checkIdentifierLike())break;const r=e.advance(),n={type:"identifier",name:r.value,start:r.start,end:r.end,line:r.line,column:r.column};e.consume(":","Expected ':' after property name in fetch named arguments");const s=e.parsePrimary();s&&t.push({key:n,value:s})}while(e.match(",")&&!e.isAtEnd());const n=e.getPosition();return{type:"objectLiteral",properties:t,start:r.start,end:n.end,line:r.line,column:r.column}}const vs={positional:"none",markers:[],syntax:""},bs=e=>({positional:"expression",markers:[],syntax:e}),ws=bs("beep! [<expression>, \u2026]"),Es={append:{positional:"expression",markers:["to"],syntax:"append <value> [to <target>]"},prepend:{positional:"expression",markers:["to"],syntax:"prepend <value> [to <target>]"},make:{positional:"primary",markers:["a","an","from","called"],commaList:["from"],syntax:"make (a|an) <type> [from <args>] [called <name>]"},throw:{positional:"primary",markers:[],syntax:"throw <error>"},"beep!":ws,beep:ws,blur:bs("blur [<target>]"),break:vs,breakpoint:vs,call:bs("call <expression>"),clear:bs("clear <target>"),close:bs("close [<target>]"),continue:vs,copy:{positional:"expression",markers:["to"],syntax:"copy <source> [to clipboard]"},default:{positional:"expression",markers:["to"],syntax:"default <target> to <value>"},empty:bs("empty [<target>]"),exit:vs,focus:bs("focus [<target>]"),get:bs("get <expression>"),log:bs("log <expression>[, <expression>\u2026]"),open:bs("open [<dialog>] [as modal|non-modal]"),"pseudo-command":bs("<method>(\u2026) [on|from|\u2026] <target>"),render:{positional:"expression",markers:["with"],syntax:"render <template> [with <variables>]"},reset:bs("reset [<form>]"),return:bs("return [<value>]"),select:bs("select [<target>]"),settle:{positional:"expression",markers:["for"],syntax:"settle [<target>] [for <timeout>]"}},ks={positional:"expression",markers:[],continuation:["into","from","to","with","by","at","before","after","over"]};function xs(e){return Es[e.toLowerCase()]??null}const Cs=new Set(["em","ex","cap","ch","ic","rem","lh","rlh","vw","vh","vi","vb","vmin","vmax","cm","mm","Q","pc","pt","px"]),As=new Set(["s","seconds","ms","milliseconds"]);class Ss{constructor(e,t,r){this.current=0,this.errors=[],this.warnings=[],this.prattCache=new Map,this.tokens=e,this.keywordResolver=t?.keywords,this.registryIntegration=t?.registryIntegration,this.originalInput=r||e.map(e=>e.value).join(" ")}resolveKeyword(e){return this.keywordResolver?this.keywordResolver.resolve(e)??e:e}addWarning(e){this.warnings.push(e)}parse(){this.prattCache.clear();const e=this.parseInternal();return this.errors.length>0&&(e.errors=[...this.errors],e.recovered=!0),e}parseInternal(){try{if(0===this.tokens.length)return this.addError("Cannot parse empty input"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings};if(this.check("behavior")){const e=[];for(;this.check("behavior");){this.advance();const t=this.parseBehaviorDefinition();if(t&&e.push(t),this.error)break}return this.error?{success:!1,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:1===e.length?e[0]:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}}const e=this.peek(),t=e&&pe(e.value)?e.value:null;if(this.check("init")||this.check("on")||this.check("def")||this.checkComment()||null!==t){const e=[];for(;!this.isAtEnd();)if(this.checkComment())this.advance();else{if(this.check("then")){const e=this.peekAt(1);if(null!==e&&("init"===e.value||"on"===e.value||"def"===e.value||void 0!==pe(e.value))){this.advance();continue}}if(this.check("init")){this.advance();const t=this.parseTopLevelInitBlock();t&&e.push(t)}else if(this.check("on")){this.advance();const t=this.parseEventHandler();t&&e.push(t)}else{if(!this.check("def")){const t=this.peek(),r=t?pe(t.value):void 0;if(r){const t=this.advance(),n=r(this.getContext(),t);n&&e.push(n);continue}break}{this.advance();const t=this.parseDefFeature();t&&e.push(t)}}}return this.isAtEnd()?this.error?{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(e),tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:this.createProgramNode(e),tokens:this.tokens,error:this.error,warnings:this.warnings})}if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){const e=this.parseCommandSequence();if(e){if(!this.isAtEnd()&&this.check("on")){const t=[e];let r=0;for(;!this.isAtEnd()&&this.check("on");){this.peek(),this.advance();const e=this.parseEventHandler();if(e&&(t.push(e),r++),this.isAtEnd()||this.peek(),this.isAtEnd(),this.check("on"),!this.isAtEnd()&&!this.check("on")){if(!this.isAtEnd())return this.peek(),this.addError("Unexpected token after event handlers: "+this.peek().value),{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error};break}}return this.error?{success:!1,node:this.createProgramNode(t),tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:this.createProgramNode(t),tokens:this.tokens,warnings:this.warnings}}return this.isAtEnd()?this.error?{success:!1,node:e,tokens:this.tokens,error:this.error,warnings:this.warnings}:{success:!0,node:e,tokens:this.tokens,warnings:this.warnings}:(this.addError("Unexpected token: "+this.peek().value),{success:!1,node:e||this.createErrorNode(),tokens:this.tokens,error:this.error})}}const r=this.parseExpression();if(this.error)return{success:!1,node:r||this.createErrorNode(),tokens:this.tokens,error:this.error};if(!this.isAtEnd()){const e=this.peek();return r&&["number","string","identifier"].includes(e.kind)?this.addError(`Unexpected token: ${e.value} (missing operator between values? expected one of +, -, *, /, etc.)`):this.addError("Unexpected token: "+e.value),{success:!1,node:r||this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}return{success:!0,node:r,tokens:this.tokens,warnings:this.warnings}}catch(e){return this.addError(e instanceof Error?e.message:"Unknown parsing error"),{success:!1,node:this.createErrorNode(),tokens:this.tokens,error:this.error,warnings:this.warnings}}}parseExpression(){return this.parseExpressionPratt(0)}parseExpressionPratt(e){const t=`${this.current}:${e}`,r=this.prattCache.get(t);if(r)return this.current=r.endPos,r.node;if(this.isAtEnd())return this.addError("Unexpected end of expression"),this.createErrorNode();const n=this.peek(),s=Ss.PRATT_TABLE.get(n.value);let i;if(s?.prefix){const e=this.advance();if(this.isAtEnd())return this.addError(`Expected expression after '${e.value}' operator`),this.createErrorNode();i=s.prefix.handler(e,this.makePrattContext())}else i=this.parseCall();for(;!this.isAtEnd();){const t=this.peek();if(60>=e){const e=this.tryParseStringPostfix(i,t);if(e){i=e;continue}}const r=Ss.PRATT_TABLE.get(t.value);if(!r?.infix){if(K.has(t.value)||Z.has(t.value))break;break}const[n]=r.infix.bp;if(e>n)break;if("="===t.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(e){}return this.createErrorNode()}if("+"===t.value||"-"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("+"===e.value||"-"===e.value))return this.addError(`Invalid operator combination: ${t.value}${e.value}`),i}if("*"===t.value||"/"===t.value||"%"===t.value){const e=this.tokens.length>this.current+1?this.tokens[this.current+1]:null;if(e&&("*"===e.value||"/"===e.value||"%"===e.value||"+"===e.value||"-"===e.value))return this.addError("*"===t.value&&"*"===e.value?"Unexpected token: "+e.value:`Invalid operator combination: ${t.value}${e.value}`),i}const s=this.advance();if(this.isAtEnd()&&!Ss.POSTFIX_UNARY_OPERATORS.has(s.value))return this.addError(`Expected expression after '${s.value}' operator`),i;i=r.infix.handler(i,s,this.makePrattContext())}return this.prattCache.set(t,{node:i,endPos:this.current}),i}tryParseStringPostfix(e,t){const r=t.value;let n=null;if(Cs.has(r))n=r;else if(As.has(r)&&this.isNumericPostfixRoot(e))n=r;else if("%"===r){this.canStartOperand(this.tokens.length>this.current+1?this.tokens[this.current+1]:null)||(n="%")}if(null==n)return null;const s=this.advance();return{type:"stringPostfix",expression:e,unit:n,start:e.start,end:s.end,line:e.line,column:e.column}}isNumericPostfixRoot(e){const t=e;return"literal"===t.type&&"number"==typeof t.value||("unaryExpression"!==t.type||"-"!==t.operator&&"+"!==t.operator?!("binaryExpression"!==t.type||!["+","-","*","/"].includes(t.operator??"")):void 0!==t.argument&&this.isNumericPostfixRoot(t.argument))}canStartOperand(e){if(!e)return!1;const t=e.value;return!K.has(t)&&!Z.has(t)&&("number"===e.kind||"string"===e.kind||"identifier"===e.kind||"symbol"===e.kind||["(","[","{","-","+","!","#",".","<","$","@"].includes(t))}makePrattContext(){const e=this;return{peek:()=>e.tokens.length>e.current?e.tokens[e.current]:void 0,advance:()=>{const t=e.tokens[e.current];return e.current++,t},parseExpr:t=>e.parseExpressionPratt(t),isStopToken:()=>{const t=e.tokens[e.current];return!t||(K.has(t.value)||Z.has(t.value))},atEnd:()=>e.current>=e.tokens.length}}parseLogicalAnd(){return this.parseExpressionPratt(11)}parseImplicitBinary(){let e=this.parseCall();for(;!(this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("and")||this.check("else")||this.check(")")||this.check("]")||this.check(","));){if("identifier"!==e.type){if("literal"===e.type&&(this.checkNumber()||this.checkIdentifier())){const t=this.peek();return this.addError(`Missing operator between '${e.raw||e.value}' and '${t.value}'`),e}break}if(this.isCommand(e.name))if(this.isCompoundCommand(e.name.toLowerCase())){if(!(this.checkCssSelector()||this.checkIdSelector()||this.checkClassSelector()||this.checkTimeExpression()||this.checkString()||this.checkNumber()||this.checkContextVar()||this.checkIdentifier()||this.checkKeyword()))break;{const t=this.createCommandFromIdentifier(e);t&&(e=t)}}else{if("wait"===e.name.toLowerCase()&&(this.checkTimeExpression()||this.checkNumber()||this.checkIdentifier()||this.checkContextVar()||this.check("("))){const t=this.createCommandFromIdentifier(e);t&&(e=t)}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}else{if(!this.checkSelector())break;{const t=this.parseCall();e=this.createBinaryExpression(" ",e,t)}}}return e}isCommand(e){return this.keywordResolver?this.keywordResolver.isCommand(e):V.isCommand(e)}isKeyword(e){return this.keywordResolver?this.keywordResolver.isKeyword(e):V.isKeyword(e)}createCommandFromIdentifier(e){const t=this.resolveKeyword(e.name.toLowerCase());if(this.isCompoundCommand(t))return this.parseCompoundCommand(e);const r={kind:"identifier",value:e.name,start:e.start??0,end:e.end??0,line:e.line??0,column:e.column??0};return os(this.getContext(),r,t,xs(t)??ks)}isCompoundCommand(e){return ls.has(e.toLowerCase())}parseCompoundCommand(e){return function(e,t){const r=cs.get(t.name.toLowerCase());return r?r(e,t):null}(this.getContext(),e)}parsePutCommand(e){return _n(this.getContext(),e)}parseSetCommand(e){return Zn(this.getContext(),e)}parseHaltCommand(e){return Pn(this.getContext(),e)}parseMeasureCommand(e){return $n(this.getContext(),e)}parseTriggerCommand(e){return Nn(this.getContext(),e)}parseCommandListUntilTerminator(e){const t=[],r=()=>this.check("end")||e.some(e=>this.check(e));for(e.join(",");!this.isAtEnd()&&!r();){this.peek(),this.peek();let e=!1;const n=this.checkIsCommand(),s=!n&&this.checkIdentifier()&&this.isCommand(this.peek().value);if(n||s){this.peek(),this.advance();const r=this.error;try{const n=this.parseCommand();this.error&&this.error!==r&&(this.error=r),n&&(t.push(n),e=!0)}catch(e){this.error=r,this.recordDropped("Discarded a command that failed to parse: "+(e instanceof Error?e.message:e+""))}}else this.checkIdentifier()&&this.peek();if(!e){this.peek(),this.isAtEnd()||r()||this.recordDropped(`Not a command, and the rest of the body was discarded: '${this.peek().value}'`);break}this.peek();const i=this.current;for(;!(this.isAtEnd()||r()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(","));)this.peek(),this.advance();if(this.recordDroppedRange(i,this.current),!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value)){this.peek();break}}let n="end";for(const t of e)if(this.check(t)){n=t;break}return this.check("end")||e.some(e=>this.check(e))||(n=""),{commands:t,terminator:n}}parseCommandListUntilEnd(e="repeat"){const{commands:t}=this.parseCommandListUntilTerminator([]);if(this.peek(),!this.check("end"))throw this.peek(),this.peek(),Error(`Expected "end" to close ${e} block`);return this.advance(),t}parseCommandListUntilEndOrElse(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else"]),r="else"===t;if(!r){if(!this.check("end"))throw Error('Expected "end" to close repeat block');this.advance()}return{commands:e,hasElse:r}}parseRepeatBody(){const{commands:e,terminator:t}=this.parseCommandListUntilTerminator(["else","until","while"]);if("end"===t)this.advance();else if(""===t)throw Error('Expected "end", "else", "until", or "while" to close repeat block');return{commands:e,terminator:t}}parseRepeatCommand(e){return function(e,t){const r=[];let n="forever",s=null,i=null,a=null,o=null,c=null,h=null;if(e.check(l)){e.advance(),n=l;const t=e.peek();zr(t)&&(c=t.value,e.advance()),e.check(y)&&(e.advance(),o=e.parseExpression())}else if(e.check(y))e.advance(),n=l,c="it",o=e.parseExpression();else if(e.check(u))e.advance(),n=u,a=e.parseExpression();else if(e.check(d))if(e.advance(),n=d,e.check(A)){e.advance(),n="until-event";const t=e.peek();if(!zr(t)&&!Fr(t))throw Error('Expected event name after "event"');s=t.value,e.advance(),e.peek(),e.peek(),e.check(v)&&(e.advance(),e.peek(),Tn(e,N),e.peek(),i=e.parsePrimary())}else a=e.parseExpression();else e.check(m)?(e.advance(),n=m):(h=e.parseExpression(),e.check(p)&&(e.advance(),n=p));let g,w=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===f&&(e.advance(),e.advance(),w=f)}else if(e.check(f)){e.advance();const t=e.peek();zr(t)?(w=t.value,e.advance()):w=f}let E=null,k=!1;if(n===m){const t=e.parseRepeatBody();if(g=t.commands,"else"===t.terminator)e.advance(),E=e.parseCommandListUntilEnd();else if("until"===t.terminator||"while"===t.terminator){if(k=!0,n=t.terminator,e.advance(),a=e.parseExpression(),!e.check("end"))throw Error('Expected "end" to close repeat block');e.advance()}}else{const t=e.parseCommandListUntilEndOrElse();g=t.commands,t.hasElse&&(e.advance(),E=e.parseCommandListUntilEnd())}const x={start:t.start,end:t.end,line:t.line,column:t.column},C={loopType:yn(n,x)};c&&(C.for=yn(c,x)),o&&(C.in=o),h&&(C.times=h),a&&(C["while"===n?"while":"until"]=a),s&&(C.event=yn(s,x)),i&&(C.from=i),w&&(C.index=yn(w,x)),r.push(fn(g,{...x,end:x.end||0})),null!==E&&r.push(fn(E,{...x,end:x.end||0}));const S=On.from(t).withArgs(...r).withModifiers(C);return k&&S.withModifier("bottomTested",{type:"literal",value:!0,...x}),S.endingAt(e.getPosition()).build()}(this.getContext(),e)}parseForCommand(e){return function(e,t){const r=[];let n=null,s=null;e.check(h)&&e.advance();const i=e.peek();if(!zr(i))throw Error('Expected variable name after "for"');if(n=i.value,e.advance(),!e.check(y))throw Error('Expected "in" after variable name in for loop');if(e.advance(),s=e.parseExpression(),!s)throw Error('Expected collection expression after "in"');let a=null;if(e.check(b)){const t=e.peekAt(1);t&&t.value.toLowerCase()===f&&(e.advance(),e.advance(),a=f)}else if(e.check(f)){e.advance();const t=e.peek();zr(t)?(a=t.value,e.advance()):a=f}const o=e.parseCommandListUntilEnd("for");r.push({type:"identifier",name:"for",start:t.start,end:t.end,line:t.line,column:t.column});const c={start:t.start,end:t.end,line:t.line,column:t.column};return r.push(yn(n,c)),r.push(s),a&&r.push(yn(a,c)),r.push(fn(o,{...c,end:c.end||0})),On.from({...t,value:"repeat"}).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseWaitCommand(e){return function(e,t){const r=[];if(e.checkTimeExpression()||e.checkLiteral()||e.checkContextVar()||e.check("(")||e.checkIdentifierLike()&&!e.check("for")&&!An(e)){const n=e.parseExpression();return r.push(n),On.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}if(e.check("for")){e.advance();const n=[];do{if(e.checkTimeExpression()||e.checkLiteral()||e.check("(")){if(n.push({kind:"duration",expr:e.parseExpression()}),e.check("or")){e.advance();continue}break}const t=e.peek();if(!zr(t))throw Error('Expected event name or duration after "for"');const r=t.value;e.advance();const s=[];if(e.check("(")){for(e.advance();!e.isAtEnd()&&!e.check(")");){const t=e.peek();if(!zr(t))break;s.push(t.value),e.advance(),e.check(",")&&e.advance()}if(!e.check(")"))throw Error('Expected ")" after event parameters');e.advance()}if(n.push({kind:"event",name:r,params:s}),!e.check("or"))break;e.advance()}while(!e.isAtEnd());let s=null;e.check(v)&&(e.advance(),Tn(e,N),s=e.parsePrimary());const i={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(vn(n.map(e=>gn("duration"===e.kind?[{key:pn("duration",i),value:e.expr}]:[{key:pn("name",i),value:mn(e.name,`"${e.name}"`,i)},{key:pn("args",i),value:vn(e.params.map(e=>mn(e,`"${e}"`,i)),i)}],i)),i)),s&&r.push(s)}return On.from(t).withArgs(...r).blocking().endingAt(e.getPosition()).build()}(this.getContext(),e)}parseInstallCommand(e){return function(e,t){const r=[];if(!e.checkIdentifierLike())throw Error('Expected behavior name after "install"');const n=e.advance().value,s=e.previous();if(r.push(pn(n,{start:s.start,end:s.end,line:s.line,column:s.column})),e.check("(")){e.advance();const n=[];for(;!e.isAtEnd()&&!e.check(")");)if(n.push(Ln(e)),e.check(","))e.advance();else if(!e.check(")"))break;if(!e.check(")"))throw Error('Expected ")" after behavior parameters');if(e.advance(),n.length>0){const s={start:t.start,end:e.getPosition().end,line:t.line,column:t.column};r.push(gn(n.map(e=>({key:e.name?pn(e.name,s):mn("_positional","_positional",s),value:e.value})),s))}}return On.from(t).withArgs(...r).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseTransitionCommand(e){return function(e,t){const r=[],n={};let s=null,i=null;const a=e.peek();if(e.checkAnySelector()||e.checkContextVar()||e.check("<")||zr(a)&&Hn.has(a.value)){const t=e.parsePrimary();("possessiveExpression"===t.type||"memberExpression"===t.type&&!t.computed)&&t.object&&t.property?.name?(i=t.object,s={type:"string",value:t.property.name,start:a.start||0,end:e.getPosition().end,line:a.line,column:a.column}):(i=t,e.check("'s")&&e.advance())}const o=e.peek();if(!s&&(zr(o)||"*"===o.value)){let t="";e.check("*")&&(t="*",e.advance());const r=function(e){if(!e.checkIdentifierLike())return"";let t=e.advance().value;for(;e.check("-")&&!e.isAtEnd();)t+="-",e.advance(),e.checkIdentifierLike()&&(t+=e.advance().value);return t}(e);r&&(t+=r,s={type:"string",value:t,start:o.start||0,end:e.getPosition().end,line:o.line,column:o.column})}if(!s)throw Error("Transition command requires a CSS property");if(i&&r.push(i),r.push(s),!e.check(g))throw Error('Expected "to" keyword after property in transition command');e.advance();const c=e.parseExpression();if(n.to=c,e.check("over")){e.advance();const t=e.parseExpression();n.over=t}if(e.check(b)){e.advance();const t=e.parsePrimary();n.with=t}return On.from(t).withArgs(...r).withModifiers(n).endingAt(e.getPosition()).build()}(this.getContext(),e)}parseAddCommand(e){return Fn(this.getContext(),e)}parseIfCommand(e){return Mn(this.getContext(),e)}parseRemoveCommand(e){return Vn(this.getContext(),e)}parseToggleCommand(e){return Dn(this.getContext(),e)}parseCall(){let e=this.parsePrimary();for(;;)if(this.match("("))e=this.finishCall(e);else if(this.match(".")){const t=this.consumeIdentifierLike("Expected property name after '.' - malformed member access");e=this.createMemberExpression(e,this.createIdentifier(t.value),!1)}else if(this.match("?.")){const t=this.consumeIdentifierLike("Expected property name after '?.' - malformed optional access"),r=this.createMemberExpression(e,this.createIdentifier(t.value),!1);r.optional=!0,e=r}else if(this.match("[")){const t=this.parseExpression();this.consume("]","Expected ']' after array index"),e=this.createMemberExpression(e,t,!0)}else{if(!this.check("'s"))break;{let t;if(this.advance(),this.check("*")){this.advance();t="*"+this.consumeIdentifier("Expected property name after * in CSS property syntax").value}else if(Yr(this.peek())&&this.peek().value.startsWith("@"))t=this.advance().value;else if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@"))this.advance(),t=this.advance().value,this.consume("]","Expected ']' after attribute reference");else{t=this.consumeIdentifierLike("Expected property name after possessive").value}e=this.createPossessiveExpression(e,this.createIdentifier(t))}}return e}parsePrimary(){if(this.check("*")){const e=this.current;if(this.advance(),!this.isAtEnd()&&zr(this.peek())){const e=this.advance().value;return this.createSelector("*"+e)}this.current=e}if(this.check("*")||this.check("/")||this.check("%")||this.check("mod")){const e=this.peek();return this.addError(`Binary operator '${e.value}' requires a left operand`),this.createErrorNode()}if(this.matchNumber()){const e=parseFloat(this.previous().value);return this.createLiteral(e,this.previous().value)}if(this.matchString()){const e=this.previous().value;if(2>e.length||e.startsWith('"')&&!e.endsWith('"')||e.startsWith("'")&&!e.endsWith("'"))return this.addError("Unclosed string literal - string not properly closed"),this.createErrorNode();const t=e.slice(1,-1),r=this.processEscapeSequences(t);return this.createLiteral(r,e)}if(this.matchTemplateLiteral()){const e=this.previous();return{type:"templateLiteral",value:e.value,start:e.start||0,end:e.end||0,line:e.line,column:e.column}}if(this.matchBoolean()){const e=this.previous().value;let t;switch(e){case"true":t=!0;break;case"false":t=!1;break;case"null":t=null;break;case"undefined":t=void 0;break;default:t="true"===e}return this.createLiteral(t,e)}if(this.matchTimeExpression()){const e=this.previous().value;return this.createLiteral(e,e)}if(this.matchQueryReference()){const e=this.previous().value,t=e.slice(1,-2).trim(),r=this.createSelector(t);return r.fromQuery=!0,r.raw=e,r}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 e=this.parseExpression();return this.consume(")","Expected closing parenthesis ')' after expression - unclosed parentheses"),e}if(this.match("{"))return this.parseObjectLiteral();if(this.match("["))return this.parseAttributeOrArrayLiteral();if(this.check(":")){if(this.advance(),this.check(":")){this.advance();const e=this.advance();return{type:"identifier",name:e.value,scope:"global",start:e.start-2,end:e.end,line:e.line,column:e.column-2}}{const e=this.advance();return{type:"identifier",name:e.value,scope:"element",start:e.start-1,end:e.end,line:e.line,column:e.column-1}}}if(this.matchBasicOperator()){const e=this.previous();return this.createIdentifier(e.value)}const e=this.peek();if(!(e&&("end"===e.value||"else"===e.value||"then"===e.value))&&(this.matchPredicate(en)||this.matchPredicate(Br)||this.matchPredicate(_r)||this.matchPredicate(Dr)||this.matchPredicate(Fr))){const e=this.previous();if("new"===e.value)return this.parseConstructorCall();if("on"===e.value)return this.parseEventHandler();if("if"===e.value)return this.parseConditional();if("closest"===e.value||"first"===e.value||"last"===e.value||"previous"===e.value||"next"===e.value){if(this.check("(")||this.checkCssSelector()||this.checkClassSelector()||this.checkIdSelector()||this.check("<")||this.checkQueryReference())return this.parseNavigationFunction(e.value);if(this.check(".")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("."+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}if(this.check("#")){const t=this.current;if(this.advance(),this.checkIdentifier()){const t=this.advance().value,r=this.createSelector("#"+t);return this.createCallExpression(this.createIdentifier(e.value),[r])}this.current=t}return this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||this.check("end")?this.createIdentifier(e.value):this.parseNavigationFunction(e.value)}const t=this.check(".")||this.check("?.");if("my"===e.value&&!t)return this.parseContextPropertyAccess("me");if("its"===e.value&&!t)return this.parseContextPropertyAccess("it");if("your"===e.value&&!t)return this.parseContextPropertyAccess("you");if("the"===e.value)return this.parseTheXofY();if("values"===e.value&&this.check("of")){this.advance();return{type:"propertyOfExpression",property:{type:"identifier",name:"values"},target:this.parsePrimary(),line:e.line,column:e.column}}return this.createIdentifier(e.value)}if(this.match("$"))return this.parseDollarExpression();if("\\"===this.peek().value)return this.parseBlockLiteral();if(Yr(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column}}const t=this.peek();return this.addError(`Unexpected token: ${t.value} at line ${t.line}, column ${t.column}`),this.advance(),this.createErrorNode()}parseBlockLiteral(){const e=this.peek().start;this.advance();const t=[];for(;!(this.isAtEnd()||this.check("-")&&">"===this.tokens[this.current+1]?.value);){if(!this.checkIdentifier()){this.addError("Unexpected token in block literal parameters: "+this.peek().value);break}t.push(this.advance().value),this.match(",")}if(!this.check("-")||">"!==this.tokens[this.current+1]?.value)return this.addError("Expected '->' in block literal"),this.createErrorNode();this.advance(),this.advance();return{type:"blockLiteral",parameters:t,body:this.parseExpression(),start:e,end:this.previous().end,line:this.previous().line,column:this.previous().column}}parseDollarExpression(){if(this.checkNumber()){const e=this.advance().value;return this.createLiteral(e,"$"+e)}if(this.checkIdentifier()){const e=this.advance();let t=this.createIdentifier(e.value);for(;this.match(".");){if(!this.checkIdentifier())return this.addError("Expected property name after '.' in dollar expression"),this.createErrorNode();{const e=this.advance();t=this.createMemberExpression(t,this.createIdentifier(e.value),!1)}}return t}return this.addError("Expected identifier or number after '$'"),this.createErrorNode()}parseHyperscriptSelector(){let e="";for(;!this.check("/")&&!this.isAtEnd();)e+=this.advance().value;return this.consume("/","Expected '/' in hyperscript selector"),this.consume(">","Expected '>' after '/' in hyperscript selector"),this.createSelector(e)}parseObjectLiteral(){const e=[],t=this.getPosition();if(this.check("}"))return this.advance(),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column};do{let t;if(this.check("["))this.advance(),t=this.parseExpression(),this.consume("]","Expected ']' after computed property name in object literal");else if(this.matchString()){const e=this.previous().value,r=e.slice(1,-1);t=this.createLiteral(r,e)}else{if(!this.check("-")&&!this.checkPredicate(en))return this.addError("Expected property name in object literal"),this.createErrorNode();{let e="",r=!1;for(;this.check("-");)this.advance(),e+="-",r=!0;for(this.checkPredicate(en)&&(e+=this.advance().value);this.check("-");)this.advance(),e+="-",r=!0,this.checkPredicate(en)&&(e+=this.advance().value);if(""===e||"-"===e)return this.addError("Expected property name in object literal"),this.createErrorNode();t=r?this.createLiteral(e,e):this.createIdentifier(e)}}this.consume(":","Expected ':' after property name in object literal");const r=this.parseExpression();if(e.push({key:t,value:r}),!this.match(","))break;if(this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after object literal properties"),{type:"objectLiteral",properties:e,start:t.start,end:this.getPosition().end,line:t.line,column:t.column}}parseCSSObjectLiteral(){const e=this.getPosition(),t=[];do{if(this.check("}"))break;let r;if(this.matchPredicate(en))r=this.createIdentifier(this.previous().value);else{if(!this.matchString())return this.addError("Expected CSS property name"),this.createErrorNode();{const e=this.previous().value,t=e.slice(1,-1);r=this.createLiteral(t,e)}}if(!this.consume(":","Expected ':' after CSS property name"))return this.createErrorNode();const n=[];let s=!1,i=0,a=-1,o=-1;for(;!this.isAtEnd()&&(0!==i||!this.check(";")&&!this.check("}"));){const e=this.advance();n.push(e.value),0>a&&"number"==typeof e.start&&(a=e.start),"number"==typeof e.end&&(o=e.end),"$"===e.value&&this.check("{")&&(s=!0),"{"===e.value&&i++,"}"===e.value&&i--}const c=this.originalInput&&a>=0&&o>a?this.originalInput.slice(a,o):n.join(""),l=s?{type:"templateLiteral",value:c,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}:this.createLiteral(c,c);if(t.push({key:r,value:l}),this.check(";")&&this.advance(),this.check("}"))break}while(!this.isAtEnd());return this.consume("}","Expected '}' after CSS object literal properties"),{type:"objectLiteral",properties:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseConstructorCall(){const e=this.previous();if(!this.checkIdentifier())return this.addError('Expected constructor name after "new"'),this.createErrorNode();const t=this.advance(),r=t.value;if(!this.check("("))return this.addError('Expected "(" after constructor name'),this.createErrorNode();this.advance();const n=[];if(!this.check(")"))do{n.push(this.parseExpression())}while(this.match(","));return this.consume(")","Expected ')' after constructor arguments"),{type:"callExpression",callee:{type:"identifier",name:r,start:t.start,end:t.end,line:t.line,column:t.column},arguments:n,isConstructor:!0,start:e.start,end:this.previous().end,line:e.line,column:e.column}}parseTopLevelInitBlock(){const e=this.getPosition(),t=this.parseCommandBlock(["end"]);return this.consume("end","Expected 'end' after init block"),{type:"initBlock",commands:t,start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseDefFeature(){const e=this.getPosition();let t="";if(!this.checkIdentifier())return this.addError("Expected function name after 'def'"),{type:"def",name:"",params:[],body:[],start:e.start,end:this.getPosition().end,line:e.line,column:e.column};for(t=this.advance().value;this.check(".");)this.advance(),this.checkIdentifier()&&(t+="."+this.advance().value);const r=[];if(this.check("(")){if(this.advance(),!this.check(")"))for(this.checkIdentifier()&&r.push(this.advance().value);this.check(",");)this.advance(),this.checkIdentifier()&&r.push(this.advance().value);this.consume(")","Expected ')' after parameter list")}const n=this.parseCommandBlock(["end","catch","finally"]),{errorSymbol:s,errorHandler:i,finallyHandler:a}=this.parseErrorAndFinallyBlocks();return this.consume("end","Expected 'end' after function definition"),{type:"def",name:t,params:r,body:n,...void 0!==s&&{errorSymbol:s},...void 0!==i&&{errorHandler:i},...void 0!==a&&{finallyHandler:a},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseErrorAndFinallyBlocks(){let e,t,r;return this.check("catch")&&(this.advance(),this.checkIdentifier()&&(e=this.advance().value),t=this.parseCommandBlock(["end","finally"])),this.check("finally")&&(this.advance(),r=this.parseCommandBlock(["end"])),{...void 0!==e&&{errorSymbol:e},...void 0!==t&&{errorHandler:t},...void 0!==r&&{finallyHandler:r}}}parseEventNameWithNamespace(e){let t;t=this.checkEvent()||this.checkIdentifier()||this.checkIsCommand()||this.checkIdentifierLike()?this.advance():this.consumeEvent(e);let r=t.value;if(this.check(":")){this.advance();r=`${r}:${this.advance().value}`}return r}callExprToCommandNode(e,t){return{type:"command",name:e.callee.name,args:e.arguments,isBlocking:!1,...void 0!==t.start&&{start:t.start},...void 0!==t.end&&{end:t.end},...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}}createPseudoCommandNode(e,t,r,n,s){return{type:"command",name:"pseudo-command",args:[{type:"objectLiteral",properties:[{key:{type:"identifier",name:"methodName"},value:{type:"literal",value:e,raw:`"${e}"`}},{key:{type:"identifier",name:"methodArgs"},value:{type:"literal",value:t.arguments,raw:JSON.stringify(t.arguments)}},...r?[{key:{type:"identifier",name:"preposition"},value:{type:"literal",value:r,raw:`"${r}"`}}]:[],{key:{type:"identifier",name:"targetExpression"},value:n}]}],isBlocking:!1,...void 0!==s.start&&{start:s.start},...void 0!==s.end&&{end:s.end},...void 0!==s.line&&{line:s.line},...void 0!==s.column&&{column:s.column}}}tryParsePseudoCommand(e,t){const r=e.callee.name,n=this.peek();if(!(Ss.PSEUDO_COMMAND_PREPOSITIONS.includes(n.value.toLowerCase())||en(n)&&!this.isCommand(n.value)||_r(n)))return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!1};let s,i;this.isCommand(r)&&this.addWarning({type:"command-shadow",message:`Method '${r}' shadows hyperscript command`,suggestions:[`Rename method to avoid confusion (e.g., '${r}Fn', 'my${r.charAt(0).toUpperCase()+r.slice(1)}')`,`Use 'call' command instead: call ${r}(...)`,"This works but may cause ambiguity"],severity:"warning",code:"PSEUDO_CMD_SHADOW",...void 0!==t.line&&{line:t.line},...void 0!==t.column&&{column:t.column}}),Ss.PSEUDO_COMMAND_PREPOSITIONS.includes(this.peek().value.toLowerCase())&&(s=this.advance().value.toLowerCase());try{i=this.parseExpression()}catch{return{node:this.callExprToCommandNode(e,t),isPseudo:!1,targetFailed:!0}}return{node:this.createPseudoCommandNode(r,e,s,i,t),isPseudo:!0,targetFailed:!1}}parseCommandWithErrorRecovery(){this.advance();const e=this.error;try{const t=this.parseCommand();return this.error&&this.error!==e&&(this.error=e),t}catch(t){return this.error=e,null}}parseTemporalKeywordModifiers(e){if(!this.check("debounced")&&!this.check("throttled"))return;const t=this.advance().value.toLowerCase(),r="debounced"===t?"debounce":"throttle";if(this.match("at"))if(this.checkTimeExpression()){const t=this.advance(),s=(n=t.value).endsWith("ms")?parseInt(n,10):n.endsWith("seconds")?1e3*parseFloat(n):n.endsWith("minutes")?6e4*parseFloat(n):n.endsWith("hours")?36e5*parseFloat(n):n.endsWith("days")?864e5*parseFloat(n):n.endsWith("s")?1e3*parseFloat(n):parseInt(n,10);e[r]=s}else if(this.matchNumber()){const t=parseInt(this.previous().value,10);e[r]=t}else this.addError(`Expected time expression after '${t} at', got: ${this.peek().value}`);else this.addError(`Expected 'at' after '${t}'`);var n}parseEventHandler(){const e=[];let t=!1;if(this.check("first")&&!this.checkIsCommand()&&this.tokens.length>this.current+1){const e=this.tokens[this.current+1],r=e?.value?.toLowerCase();r&&"of"!==r&&"in"!==r&&"from"!==r&&(this.advance(),t=!0)}const r=this.parseEventNameWithNamespace("Expected event name after 'on'");for(e.push(r);this.check("or");){this.advance();const t=this.parseEventNameWithNamespace("Expected event name after 'or'");e.push(t)}let n;if(e.join(", "),this.registryIntegration){const t=e[0];if(this.registryIntegration.hasEventSource(t)){const e=this.registryIntegration.getEventSource(t);n=e?.name}}const s=[];if(this.match("(")){if(!this.check(")"))do{const e=this.advance();s.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after event parameters"),s.join(", ")}const i={};for(;this.check(".");){this.advance();const e=this.advance().value.toLowerCase();if("once"===e)i.once=!0;else if("prevent"===e)i.prevent=!0;else if("stop"===e)i.stop=!0;else if("debounce"===e||"throttle"===e){if(!this.check("("))throw Error(`Expected '(' after '.${e}'`);{this.advance();const t=this.advance(),r=parseInt(t.value,10);if(isNaN(r))throw Error(`Expected number for ${e} delay, got: ${t.value}`);"debounce"===e?i.debounce=r:i.throttle=r,this.consume(")",`Expected ')' after ${e} delay`)}}}let a,o,c,l;if(this.parseTemporalKeywordModifiers(i),t&&(i.once=!0),Object.keys(i),this.match("[")&&(a=this.parseExpression(),this.consume("]","Expected ']' after event condition")),this.match("from")){const e=this.advance();o=e.value,this.parseTemporalKeywordModifiers(i)}if(this.match("of")){const e=this.advance();c=e.value.startsWith("@")?e.value.substring(1):e.value}this.match("in")&&(l=this.parseExpression());const u=[];for(this.isAtEnd()||this.peek(),this.isAtEnd();!this.isAtEnd()&&(this.peek(),this.peek(),!this.check("on"));){if(this.checkComment()){this.peek(),this.advance();continue}if(this.check("end")){this.advance();break}if(this.check("catch")||this.check("finally")){this.peek();break}if(this.checkIsCommand()){const e="("===this.tokens[this.current+1]?.value,t=this.peek().value.toLowerCase();if(e&&!("js"===t||"tell"===t)){let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t,this.advance();const r=this.parseCommand();u.push(r);continue}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.isPseudo||t.targetFailed)continue}}else{const e=this.peek().value,t=this.parseCommandWithErrorRecovery();t?(u.push(t),this.isAtEnd()||this.peek()):this.recordDropped(`Command '${e}' failed to parse and was discarded`)}}else{if(!this.checkIdentifier()){this.isAtEnd()||this.check("end")||this.check("catch")||this.check("finally")||this.recordDropped(`Not a command, and the rest of the handler body was discarded: '${this.peek().value}'`);break}{const e=this.peek();if(this.isCommand(e.value)){const t=this.parseCommandWithErrorRecovery();t?u.push(t):this.recordDropped(`Command '${e.value}' failed to parse and was discarded`)}else{let e;const t=this.error;try{e=this.parseExpression()}catch(e){this.error=t;break}if(e&&"callExpression"===e.type){const t=this.tryParsePseudoCommand(e,e);if(u.push(t.node),t.targetFailed)continue}else{if(!e||"binaryExpression"!==e.type||" "!==e.operator){this.recordDroppedExpression(e);break}{const t=e;if(!t.left||"identifier"!==t.left.type||!this.isCommand(t.left.name)){this.recordDroppedExpression(e);break}{const r={type:"command",name:t.left.name,args:[t.right],isBlocking:!1,...void 0!==e.start&&{start:e.start},...void 0!==e.end&&{end:e.end},...void 0!==e.line&&{line:e.line},...void 0!==e.column&&{column:e.column}};u.push(r)}}}}}}const e=this.current;for(;!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("and")||this.check(",")||this.check("on")||this.check("catch")||this.check("finally"));)this.advance();if(this.recordDroppedRange(e,this.current),!this.match("then","and",",")&&!this.checkIsCommand()&&!this.isCommand(this.peek().value))break}let d,m,p;this.isAtEnd()||!this.check("catch")&&!this.check("finally")||(({errorSymbol:d,errorHandler:m,finallyHandler:p}=this.parseErrorAndFinallyBlocks()),this.check("end")&&this.advance());const h=this.getPosition(),f={type:"eventHandler",event:1===e.length?e[0]:e.join("|"),events:e,commands:u,...void 0!==d&&{errorSymbol:d},...void 0!==m&&{errorHandler:m},...void 0!==p&&{finallyHandler:p},...s.length>0&&{args:s},...a&&{condition:a},...o&&{target:o},...c&&{attributeName:c},...l&&{watchTarget:l},...n&&{customEventSource:n},...Object.keys(i).length>0&&{modifiers:i},start:h.start,end:h.end,line:h.line,column:h.column};return e.join(", "),f}parseBehaviorDefinition(){const e=this.getPosition(),t=this.consumeIdentifier("Expected behavior name after 'behavior' keyword").value;/^[A-Z]/.test(t)||this.addError(`Behavior name must start with uppercase letter (got "${t}")`);const r=[];if(this.match("(")){if(!this.check(")"))do{const e=this.consumeIdentifierLike("Expected parameter name");r.push(e.value)}while(this.match(","));this.consume(")","Expected ')' after behavior parameters")}const n=new Set(r),s=[];let i;for(;!this.isAtEnd()&&!this.check("end");)if(this.match("on")){const e=this.getPosition(),t=this.parseEventNameWithNamespace("Expected event name after 'on'"),r=[];if(this.check("(")){for(this.advance();!this.isAtEnd()&&!this.check(")");){const e=this.peek();en(e)?(r.push(e.value),this.advance(),this.check(",")&&this.advance()):this.advance()}this.check(")")&&this.advance()}let i;if(this.check("from")){this.advance();const e=[];if(this.check("the")&&this.advance(),!this.isAtEnd()){const t=this.peek(),r=n.has(t.value);this.checkIsCommand()&&!r||(e.push(t.value),i=t.value,this.advance())}}const{commands:a,terminator:o}=this.parseCommandListUntilTerminator(["catch","finally"]);let c,l,u;if("catch"!==o&&"finally"!==o||({errorSymbol:c,errorHandler:l,finallyHandler:u}=this.parseErrorAndFinallyBlocks()),!this.check("end"))throw Error('Expected "end" to close behavior event handler');this.advance();const d={type:"eventHandler",event:t,commands:kn(a),...void 0!==c&&{errorSymbol:c},...void 0!==l&&{errorHandler:kn(l)},...void 0!==u&&{finallyHandler:kn(u)},...void 0!==i&&{target:i},...r.length>0&&{args:r},start:e.start,end:this.getPosition().end,line:e.line,column:e.column};s.push(d)}else{if(!this.match("init")){this.addError("Unexpected token in behavior body: "+this.peek().value);break}i={type:"initBlock",commands:kn(this.parseCommandBlock(["end"])),start:e.start,end:this.getPosition().end,line:e.line,column:e.column},this.consume("end","Expected 'end' after init block")}this.consume("end","Expected 'end' to close behavior definition");return{type:"behavior",name:t,parameters:r,eventHandlers:s,...void 0!==i?{initBlock:i}:{},start:e.start,end:this.getPosition().end,line:e.line,column:e.column}}parseCommandSequence(){const e=[];for(;!this.isAtEnd();){if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value)){this.advance();const t=this.error,r=this.parseCommand();if(this.error&&this.error!==t){this.error.message.includes("Expected closing parenthesis")||this.error.message.includes("Expected ')'")||this.error.message.includes("unclosed parenthes")||this.error.message.includes("Unclosed parenthes")||(this.error=t)}for(e.push(r);!(this.isAtEnd()||this.checkIsCommand()||this.isCommand(this.peek().value)||this.check("then")||this.check("on"));)this.peek(),this.advance();if(this.check("on"))break;if(this.match("then"))continue;if(this.checkIsCommand()||this.isCommand(this.peek().value)&&!this.isKeyword(this.peek().value))continue;break}{const t=this.peek(),r=this.getPosition(),n="Expected command, got: "+t.value;this.addError(n);const s=wn(r,n,t.value);if(e.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===e.length?e[0]:function(e){return{type:"CommandSequence",commands:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1}}(e)}isTokenKeyword(e,t){return xn(e,t)}parseCommandBlock(e){const t=[];for(;!this.isAtEnd()&&!e.some(e=>this.check(e));)if(this.checkComment())this.advance();else{if(!this.checkIsCommand()&&!this.isCommand(this.peek().value))break;{this.advance();const e=this.parseCommand();if(t.push(e),this.match("then","and",","))continue}}return t}parseCommand(){const e=this.parseCommandCore();if(e&&"command"===e.type&&!e.body&&(this.check("when")||this.check("where"))){const t=this.peek().value.toLowerCase();this.advance();const r=this.parseExpression();r&&(e.modifiers={...e.modifiers??{},[t]:r})}return e}parseCommandCore(){const e=this.previous();let t=e.value;if("beep"===t&&this.check("!")&&(this.advance(),t="beep!"),"fetch"===t)return function(e,t){const r={};let n=null;if(!e.isAtEnd()&&ps(e)&&(n=fs(e)),n||(n=e.parsePrimary()),!n)return e.addError("fetch requires a URL"),On.from(t).endingAt(e.getPosition()).build();!e.isAtEnd()&&e.check("{")&&(r.with=e.parsePrimary());for(let t=0;3>t&&!e.isAtEnd();t++)if(!e.check("as")||r.as){if(!e.check("with")||r.with){if(e.check("do")&&!r.doNotThrow){const t=e.peekAt(1),n=e.peekAt(2);if("not"===t?.value&&"throw"===n?.value){const t=e.advance();e.advance();const n=e.advance();r.doNotThrow=En({type:"literal",value:!0,start:t.start,end:n.end,line:t.line,column:t.column});continue}}break}e.advance(),r.with=ys(e)?gs(e):e.parsePrimary()}else e.advance(),e.isAtEnd()||Tn(e,"a")||Tn(e,"an"),r.as=e.parsePrimary();const s=On.from(t).withArgs(n).endingAt(e.getPosition());return Object.keys(r).length>0&&s.withModifiers(r),s.build()}(this.getContext(),e);const r=t.toLowerCase();if("repeat"===r)return this.parseRepeatCommand(e);if("for"===r)return this.parseForCommand(e);if("if"===r||"unless"===r)return this.parseIfCommand(e);if("wait"===r)return this.parseWaitCommand(e);if("install"===r)return this.parseInstallCommand(e);if("transition"===r)return this.parseTransitionCommand(e);if("add"===r)return this.parseAddCommand(e);if(this.isCompoundCommand(r)){return this.parseCompoundCommand({type:"identifier",name:r,start:e.start||0,end:e.end||0,line:e.line,column:e.column})||(n=r,s=this.getPosition(),{type:"command",name:n,args:[],partial:!0,start:s.start,end:s.end,line:s.line,column:s.column})}var n,s;return"increment"!==t&&"decrement"!==t||this.isAtEnd()?os(this.getContext(),e,t,xs(t)??ks):function(e,t){const r=t.value,n="increment"===r?"+":"-";let s=!1;e.check(L)&&(s=!0,e.advance());const i=e.parseExpression();if(!i)throw Error("Expected variable or expression after "+r);let a;if(e.check(E)){e.advance();const t=e.parseExpression();if(!t)throw Error(`Expected amount after 'by' in ${r} command`);a=t}else a=mn(1,"1",{start:t.start,end:e.previous().end,line:t.line,column:t.column});let o=i;s&&"identifier"===i.type&&(o={...i,scope:"global"});const c=hn(n,i,a,{start:t.start,end:e.previous().end,line:t.line,column:t.column});return c.coerceNumeric=!0,On.from(t).withName("set").withArgs(o).withModifier("to",c).withOriginalCommand(r).endingAt({end:e.previous().end}).build()}(this.getContext(),e)}parseConditional(){const e=this.parseExpression();this.consume("then","Expected 'then' after if condition");const t=this.parseConditionalBranch();let r;this.match("else")&&(r=this.parseConditionalBranch());const n=this.getPosition();return{type:"conditionalExpression",test:e,consequent:t,alternate:r,start:n.start,end:n.end,line:n.line,column:n.column}}parseConditionalBranch(){if(this.checkIsCommand()){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}if(this.checkIdentifier()||this.checkKeyword()){const e=this.peek();if(this.isCommand(e.value)){const e=this.advance(),t=this.createIdentifier(e.value);return this.createCommandFromIdentifier(t)||t}}return this.parseExpression()}parseNavigationFunction(e){const t=this.getPosition(),r=[];if(this.match("of"))r.push(this.parseExpression());else{if(this.check("("))return this.finishCall(pn(e,t));this.isAtEnd()||this.checkBasicOperator()||this.check("then")||this.check("else")||r.push(this.parsePrimary())}const n=this.createCallExpression(pn(e,t),r);if("next"===e||"previous"===e){const e=this.parseRelativePositionalModifiers();e&&(n.relativePositional=e)}return n}parseRelativePositionalModifiers(){if(!(this.check("from")||this.check("within")||this.check("in")||this.check("with")))return null;let e,t,r,n=!1,s=!1;return this.match("from")&&(e=this.parseRelativePositionalOperand()),this.match("in")?(n=!0,r=this.parseRelativePositionalOperand()):this.match("within")&&(t=this.parseRelativePositionalOperand()),this.match("with")&&(this.match("wrapping"),s=!0),{from:e,within:t,inElt:r,inSearch:n,wrapping:s}}parseRelativePositionalOperand(){return this.match("the"),this.parsePrimary()}parseTheXofY(){if(!this.checkIdentifier())return this.createIdentifier("the");const e=this.peek(),t=e.value;if(["first","last","next","previous","random","closest"].includes(t))return this.advance(),this.parseNavigationFunction(t);if(this.advance(),!this.check("of"))return this.createIdentifier(t);this.advance();return{type:"propertyOfExpression",property:{type:"identifier",name:t},target:this.parseCall(),line:e.line,column:e.column}}parseContextPropertyAccess(e){const t=this.getPosition(),r=()=>pn(e,t);if(this.match("*")){let e="";if(!this.checkIdentifier())return this.addError("Expected property name after 'my *'"),this.createMemberExpression(r(),this.createIdentifier(""),!1);for(e=this.advance().value;this.check("-")&&!this.isAtEnd();){if(e+="-",this.advance(),!this.checkIdentifier()){this.addError("Expected identifier after hyphen in CSS property name");break}e+=this.advance().value}const t="*"+e;return this.createMemberExpression(r(),this.createIdentifier(t),!1)}{if(this.check("[")&&this.tokens[this.current+1]?.value?.startsWith("@")){this.advance();const e=this.advance();return this.consume("]","Expected ']' after attribute reference"),this.createMemberExpression(r(),{type:"attributeAccess",attributeName:e.value.substring(1),start:e.start,end:e.end,line:e.line,column:e.column},!0)}if(Yr(this.peek())&&this.peek().value.startsWith("@")){const e=this.advance();return this.createMemberExpression(r(),this.createIdentifier(e.value),!1)}const t=this.consumeIdentifierLike(`Expected property name after '${{me:"my",it:"its",you:"your"}[e]}'`);return this.createMemberExpression(r(),this.createIdentifier(t.value),!1)}}parseMyPropertyAccess(){return this.parseContextPropertyAccess("me")}finishCall(e){const t=[];if(!this.check(")"))do{if(this.check(","))return this.addError("Unexpected token in function arguments"),this.createCallExpression(e,[this.createErrorNode()]);t.push(this.parseExpression())}while(this.match(","));if(!this.check(")")&&"identifier"===e.type){const t=e.name;V.isCSSFunction(t)}return this.consume(")","Expected ')' after arguments"),this.createCallExpression(e,t)}createLiteral(e,t){return mn(e,t,this.getPosition())}createIdentifier(e){return pn(e,this.getPosition())}createBinaryExpression(e,t,r){return hn(e,t,r,this.getPosition())}createUnaryExpression(e,t,r){return function(e,t,r,n){return{type:"unaryExpression",operator:e,argument:t,prefix:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.getPosition())}spanFromLeftmost(e){const t=this.getPosition(),r=e?.start;return"number"==typeof r&&t.start>r?this.originalInput?{...Pt(this.originalInput,r),start:r,end:t.end}:{...t,start:r}:t}createCallExpression(e,t){return function(e,t,r){return{type:"callExpression",callee:e,arguments:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.spanFromLeftmost(e))}createMemberExpression(e,t,r){return function(e,t,r,n){return{type:"memberExpression",object:e,property:t,computed:r,start:n.start,end:n.end,line:n.line,column:n.column}}(e,t,r,this.spanFromLeftmost(e))}createSelector(e){return function(e,t){return{type:"selector",value:e,start:t.start,end:t.end,line:t.line,column:t.column}}(e,this.getPosition())}createPossessiveExpression(e,t){return function(e,t,r){return{type:"possessiveExpression",object:e,property:t,start:r.start,end:r.end,line:r.line,column:r.column}}(e,t,this.spanFromLeftmost(e))}createErrorNode(){return{type:"identifier",name:"__ERROR__",start:(e=this.getPosition()).start,end:e.end,line:e.line,column:e.column};var e}processEscapeSequences(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){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 t}})}createProgramNode(e){return function(e){if(0===e.length)return{type:"identifier",name:"__ERROR__",start:0,end:0,line:1,column:1};if(1===e.length)return e[0];const t={type:"Program",statements:e,start:e[0]?.start||0,end:e[e.length-1]?.end||0,line:e[0]?.line||1,column:e[0]?.column||1};return t}(e)}match(...e){for(const t of e)if(this.check(t))return this.advance(),!0;return!1}matchOperator(e){if(this.isAtEnd())return!1;const t=this.peek();return!(!un(t)||t.value!==e)&&(this.advance(),!0)}check(e){if(this.isAtEnd())return!1;const t=this.peek().value;return this.resolveKeyword(t)===e}checkPredicate(e){return!this.isAtEnd()&&e(this.peek())}matchPredicate(e){return!!this.checkPredicate(e)&&(this.advance(),!0)}checkSelector(){return this.checkPredicate(Zr)}matchSelector(){return this.matchPredicate(Zr)}checkAnySelector(){return this.checkPredicate(Kr)}checkLiteral(){return this.checkPredicate(Gr)}checkIdentifierLike(){return this.checkPredicate(zr)}checkIsCommand(){return this.checkPredicate(Dr)}checkCommandTerminator(){return this.checkPredicate(dn)}checkReference(){return this.checkPredicate(Qr)}checkTimeExpression(){return this.checkPredicate(Jr)}checkEvent(){return this.checkPredicate(Fr)}checkContextVar(){return this.checkPredicate(_r)}checkComment(){return this.checkPredicate(Xr)}checkIdentifier(){return this.checkPredicate(en)}checkKeyword(){return this.checkPredicate(Br)}checkString(){return this.checkPredicate(tn)}matchString(){return this.matchPredicate(tn)}checkNumber(){return this.checkPredicate(rn)}matchNumber(){return this.matchPredicate(rn)}checkBoolean(){return this.checkPredicate(nn)}matchBoolean(){return this.matchPredicate(nn)}checkTemplateLiteral(){return this.checkPredicate(sn)}matchTemplateLiteral(){return this.matchPredicate(sn)}checkQueryReference(){return this.checkPredicate(an)}matchQueryReference(){return this.matchPredicate(an)}checkIdSelector(){return this.checkPredicate(on)}checkClassSelector(){return this.checkPredicate(cn)}checkCssSelector(){return this.checkPredicate(ln)}checkBasicOperator(){return this.checkPredicate(un)}matchBasicOperator(){return this.matchPredicate(un)}matchTimeExpression(){return this.matchPredicate(Jr)}matchIdentifierLike(){return this.matchPredicate(zr)}matchComparisonOperator(){return this.matchPredicate(Ur)}consumePredicate(e,t){return this.checkPredicate(e)?this.advance():(this.addError(t),this.peek())}consumeIdentifier(e){return this.consumePredicate(en,e)}consumeIdentifierLike(e){return this.consumePredicate(zr,e)}consumeEvent(e){return this.consumePredicate(Fr,e)}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.current>=this.tokens.length}peek(){return this.isAtEnd()?{kind:"unknown",value:"",start:0,end:0,line:1,column:1}:this.tokens[this.current]}peekAt(e){const t=this.current+e;return t>=0&&this.tokens.length>t?this.tokens[t]:null}previous(){return this.tokens[this.current-1]}consume(e,t){return this.check(e)?this.advance():(this.addError(t),this.peek())}addError(e){const t=this.peek();let r=t.start||0,n=t.line||1,s=t.column||1;if(e.includes("property name after '.'")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1}if(e.includes("parenthes")){const e=this.current>0?this.previous():t;r=e.end||e.start||0,n=e.line||1,s=e.column||1,0===r&&this.current>0&&(r=this.current)}if(e.includes("Expected expression after")){const e=this.current>0?this.previous():t;r=e.start||0,n=e.line||1,s=e.column||1,0===r&&(r=Math.max(1,this.current-1))}if(e.includes("Missing operand")){let e=t;for(let t=this.current-1;t>=0;t--){const r=this.tokens[t];if(r&&("+"===r.value||"-"===r.value)){e=r;break}}r=e.start||0,n=e.line||1,s=e.column||1}this.error={message:e,line:Math.max(1,n),column:Math.max(1,s),position:Math.max(0,r)},this.errors.push(this.error)}recordDroppedRange(e,t){const r=this.tokens.slice(e,t).filter(e=>!Xr(e)&&"end"!==e.value);0!==r.length&&this.recordDropped(`Discarded input the parser could not place: '${r.map(e=>e.value).join(" ")}'`)}recordDropped(e){const t=this.peek();this.errors.push({message:e,line:Math.max(1,t.line||1),column:Math.max(1,t.column||1),position:Math.max(0,t.start||0)})}recordDroppedExpression(e){this.recordDropped("Not a command, and the rest of the handler body was discarded: "+(e&&"string"==typeof e.name?`'${e.name}'`:"a "+(e?.type??"expression")))}synchronizeToCommandBoundary(){for(;!this.isAtEnd();){const e=this.peek();if("then"===e.value||"end"===e.value||"on"===e.value)return;if(this.checkIsCommand()||this.isCommand(e.value)&&!this.isKeyword(e.value))return;this.advance()}}parseAttributeOrArrayLiteral(){const e=this.previous().start,t=this.previous().line,r=this.previous().column;if(!this.isAtEnd()&&this.peek().value.startsWith("@")){const n=[];for(;!this.check("]")&&!this.isAtEnd();){const e=this.advance();n.push(e.value)}this.consume("]","Expected ']' after attribute literal");const s=n.join("");if(!s.includes("="))return{type:"attributeAccess",attributeName:s.replace(/^@/,""),start:e,end:this.previous().end,line:t,column:r};const i="["+s+"]";return{type:"literal",value:i,raw:i,start:e,end:this.previous().end,line:t,column:r}}const n=new Set(["=","~=","|=","^=","$=","*="]),s=this.tokens[this.current],i=this.tokens[this.current+1];if("identifier"===s?.kind&&("]"===i?.value||i&&n.has(i.value)&&"string"===this.tokens[this.current+2]?.kind)){let e="["+this.advance().value;if(this.check("]"))this.advance(),e+="]";else{const t=this.advance().value,r=this.advance().value;e+=t+'"'+(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r)+'"',this.consume("]","Expected ']' after attribute selector"),e+="]"}return this.createSelector(e)}const a=[];if(!this.check("]"))do{if(this.check("]"))break;a.push(this.parseExpression())}while(this.match(","));return this.consume("]","Expected ']' after array elements"),{type:"arrayLiteral",elements:a,start:e,end:this.previous().end,line:t,column:r}}getPosition(){const e=this.current>0?this.previous():this.peek();return{start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}getContext(){const e=this,t={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),isKeyword:this.isKeyword.bind(this),resolveKeyword:this.resolveKeyword.bind(this),savePosition:()=>e.current,restorePosition:t=>{e.current=t},peekAt:t=>e.peekAt(t),getInputSlice:(e,t)=>this.originalInput?0>e||e>=this.originalInput.length?"":void 0!==t?this.originalInput.slice(e,t):this.originalInput.slice(e):""};return Object.defineProperty(t,"current",{get:()=>e.current,set:t=>{e.current=t},enumerable:!0,configurable:!0}),t}}function Ts(e,t){const r=St(e);return new Ss(r,t,e).parse()}function Ls(e,t){const r=e.registry?.get(t);if(!r)throw Error(`Expression '${t}' 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 r}function Os(e){if(e&&"object"==typeof e&&"success"in e){if(e.success)return"value"in e?e.value:void 0;const t=e.errors||[];throw Error(t.length>0?t[0].message:"Expression evaluation failed")}return e}Ss.POSTFIX_UNARY_OPERATORS=new Set(["exists","does not exist","is empty","is not empty","ignoring case"]),Ss.PRATT_TABLE=ee,Ss.PSEUDO_COMMAND_PREPOSITIONS=["from","on","with","into","at","to"];const Ns=new Set(["literal","string","identifier","selector","attributeAccess","binaryExpression","unaryExpression","callExpression","memberExpression","possessiveExpression","propertyOfExpression","arrayLiteral","objectLiteral","templateLiteral","asExpression","betweenExpression","typeCheckExpression","collectionExpression","conditionalExpression","stringPostfix","blockLiteral","propertyAccess","contextReference","eventHandler"]);async function Ps(e,t){switch(e.type){case"literal":return function(e){return e.value}(e);case"identifier":return Vs(e,t);case"binaryExpression":return async function(e,t){const r=e.operator,n=e.right,s=e.left;if("="===r){const r=await Is(e.right,t);if("identifier"===s?.type&&"string"==typeof s.name){const e=s.name;return e.startsWith("$")?le(t,e.slice(1),r):"global"===s.scope?le(t,e,r):"element"===s.scope?we(t,e,r):(t.locals||(t.locals=new Map),t.locals.set(e,r)),r}throw Error(`Assignment target must be a variable identifier (got '${s?.type??"undefined"}')`)}if("has"===r||"have"===r){const r=await Is(e.left,t);return!!(r instanceof Element&&"selector"===n.type&&"string"==typeof n.value&&n.value.startsWith("."))&&r.classList.contains(n.value.slice(1))}if("in"===r||"is in"===r){const r="callExpression"===s?.type&&"identifier"===s.callee?.type?s.callee.name:null;if(("first"===r||"last"===r)&&Array.isArray(s.arguments)){const n=s.arguments[0];if("selector"===n?.type&&"string"==typeof n.value){const s=await Is(e.right,t);if(s&&"function"==typeof s.querySelectorAll){const e=Array.from(s.querySelectorAll(n.value));return 0===e.length?null:"first"===r?e[0]:e[e.length-1]}}}if("selector"===s?.type&&s.fromQuery&&"string"==typeof s.value){const r=await Is(e.right,t),n=r&&"function"==typeof r.querySelectorAll?r:null;if(n)return Array.from(n.querySelectorAll(s.value))}}if("of"===r&&"selector"===s?.type&&"string"==typeof s.value&&/^\*[a-zA-Z][\w-]*$/.test(s.value)){const r=await Is(e.right,t);return Ls(t,"styleRef").evaluate(t,s.value.slice(1),r)}if("of"===r){const r=Ds(e.left);if(r){const n=await Is(e.right,t);let s=n;for(const e of r){if(null==s)return;s=Be(s)?Ke(s,e):s[e]}return"function"==typeof s?s.bind(n):s}}const i=await Is(e.left,t);if("and"===r){if(!i)return i;const r=await Is(e.right,t);return Ls(t,"and").evaluate(t,i,r)}if("or"===r){if(i)return i;const r=await Is(e.right,t);return Ls(t,"or").evaluate(t,i,r)}const a=await Is(e.right,t),o=e=>"string"==typeof e?e.toLowerCase():e,c=e.ignoringCase?o(i):i,l=e.ignoringCase?o(a):a;switch(r){case"+":{let r=i,n=a;return e.coerceNumeric&&("string"==typeof r&&(r=Se(r)),"string"==typeof n&&(n=Se(n))),"string"==typeof r||"string"==typeof n?(r??"")+""+(n??""):Array.isArray(r)?Array.isArray(n)?[...r,...n]:[...r,n]:Os(await Ls(t,"addition").evaluate(t,{left:r,right:n}))}case"-":return Os(await Ls(t,"subtraction").evaluate(t,{left:i,right:a}));case"*":return Os(await Ls(t,"multiplication").evaluate(t,{left:i,right:a}));case"/":return Os(await Ls(t,"division").evaluate(t,{left:i,right:a}));case"%":case"mod":return Os(await Ls(t,"modulo").evaluate(t,{left:i,right:a}));case"^":case"**":return Os(await Ls(t,"power").evaluate(t,{left:i,right:a}));case">":case"is greater than":return Ls(t,"greaterThan").evaluate(t,i,a);case"<":case"is less than":return Ls(t,"lessThan").evaluate(t,i,a);case">=":case"is greater than or equal to":return Ls(t,"greaterThanOrEqual").evaluate(t,i,a);case"<=":case"is less than or equal to":return Ls(t,"lessThanOrEqual").evaluate(t,i,a);case"==":return Ls(t,"equals").evaluate(t,c,l);case"is":case"am":case"equals":case"is equal":case"is equal to":{const r=_s(e,i,a);return void 0!==r?r:Ls(t,"equals").evaluate(t,c,l)}case"!=":return Ls(t,"notEquals").evaluate(t,c,l);case"is not":case"is not equal":case"is not equal to":{const r=_s(e,i,a);return void 0!==r?!r:Ls(t,"notEquals").evaluate(t,c,l)}case"===":case"really equals":case"is really":case"is really equal to":return Ls(t,"strictEquals").evaluate(t,c,l);case"!==":case"is not really":case"is not really equal to":return Ls(t,"strictNotEquals").evaluate(t,c,l);case"as":return Ls(t,"as").evaluate(t,i,zs(a));case"contains":case"contain":case"includes":case"include":return Ls(t,"contains").evaluate(t,c,l);case"does not contain":case"do not contain":case"does not contains":case"does not include":return Ls(t,"doesNotContain").evaluate(t,c,l);case"starts with":return Ls(t,"startsWith").evaluate(t,c,l);case"ends with":return Ls(t,"endsWith").evaluate(t,c,l);case"does not start with":return!await Ls(t,"startsWith").evaluate(t,c,l);case"does not end with":return!await Ls(t,"endsWith").evaluate(t,c,l);case"match":case"matches":return Ls(t,"matches").evaluate(t,c,Fs(e.right,l));case"does not match":case"do not match":return!await Ls(t,"matches").evaluate(t,c,Fs(e.right,l));case"in":case"is in":case"am in":return Bs(i,a);case"is not in":case"am not in":return!Bs(i,a);case"of":return a&&"object"==typeof a?a[i]:void 0;case"precedes":return Us(i,a,Node.DOCUMENT_POSITION_FOLLOWING);case"does not precede":return!Us(i,a,Node.DOCUMENT_POSITION_FOLLOWING);case"follows":return Us(i,a,Node.DOCUMENT_POSITION_PRECEDING);case"does not follow":return!Us(i,a,Node.DOCUMENT_POSITION_PRECEDING);default:throw Error("Unknown binary operator: "+r)}}(e,t);case"asExpression":return async function(e,t){const r=await Is(e.expression,t),n=zs(e.targetType);return Ls(t,"as").evaluate(t,r,n)}(e,t);case"betweenExpression":return async function(e,t){const r=await Is(e.value,t),n=await Is(e.min,t),s=await Is(e.max,t),i=e=>"string"==typeof e?e.toLowerCase():e,[a,o,c]=e.ignoringCase?[i(r),i(n),i(s)]:[r,n,s],l=await Rr.between.evaluate(t,a,o,c);return e.negated?!l:l}(e,t);case"typeCheckExpression":return async function(e,t){const r=await Is(e.value,t),n=e.typeName+"",s=!1!==e.nullOk,i=function(e,t,r){if(null==e&&r)return!0;const n=Object.prototype.toString.call(e).slice(8,-1);if(n===t)return!0;const s=globalThis[t];return"function"==typeof s&&e instanceof s}(r,n,s);return e.negated?!i:i}(e,t);case"collectionExpression":return async function(e,t){const r=await Is(e.collection,t);if(null==r)return r;const n=async(e,r)=>Is(e,{...t,it:r});switch(e.operator){case"where":return async function(e,t,r){const n=Wr(e),s=[];for(const e of n)await r(t,e)&&s.push(e);return s}(r,e.right,n);case"sorted by":return async function(e,t,r,n){const s=[...Wr(e)],i=await Promise.all(s.map(e=>n(t,e))),a=s.map((e,t)=>t);a.sort((e,t)=>{const r=i[e],n=i[t];return r===n?0:null==r?1:null==n||n>r?-1:1});const o=a.map(e=>s[e]);return"desc"===r?o.reverse():o}(r,e.right,e.order??"asc",n);case"mapped to":return async function(e,t,r){const n=Wr(e);return Promise.all(n.map(e=>r(t,e)))}(r,e.right,n);case"split by":{const n=await Is(e.right,t);return i=n,null==(s=r)?[]:(s+"").split(null==i?"":i+"")}case"joined by":return function(e,t){const r=null==t?"":t+"";return Wr(e).map(e=>null==e?"":e+"").join(r)}(r,await Is(e.right,t));default:throw Error("Unknown collection operator: "+e.operator)}var s,i}(e,t);case"unaryExpression":return async function(e,t){const r=e.operand??e.argument;if(!r)throw Error(`Unary expression has no operand (operator: ${e.operator})`);const n=await Is(r,t);switch(e.operator){case"not":case"!":return Rr.not.evaluate(t,n);case"no":return Rr.no.evaluate(t,n);case"-":return-n;case"+":return+n;case"exists":case"some":return Rr.exists.evaluate(t,n);case"does not exist":return Rr.doesNotExist.evaluate(t,n);case"is empty":return Rr.isEmpty.evaluate(t,n);case"is not empty":return Rr.isNotEmpty.evaluate(t,n);default:throw Error("Unknown unary operator: "+e.operator)}}(e,t);case"memberExpression":return async function(e,t){const r=await Is(e.object,t);if(e.computed){const n=await Is(e.property,t);return Array.isArray(r)&&"number"==typeof n&&0>n?r[r.length+n]:r?.[n]}return Qs(r,e.property.name,t)}(e,t);case"propertyAccess":return async function(e,t){let r=await Is(e.object,t);for(const n of(e.property+"").split(".")){if(null==r)return;r=await Qs(r,n,t)}return r}(e,t);case"callExpression":return async function(e,t){const r=await Is(e.callee,t);if(e.isConstructor&&"function"==typeof r){return new r(...await Promise.all(e.arguments.map(e=>Is(e,t))))}if("identifier"===e.callee.type){const n=e.callee.name,s=await async function(e,t,r){if(!Js.has(t))return Promise.all(e.map(e=>Is(e,r)));return Promise.all(e.map(e=>"identifier"===e.type&&e.name?e.name:"selector"===e.type&&e.value?e.value:Is(e,r)))}(e.arguments,n,t);switch(n){case"closest":return lt.closest.evaluate(t,...s);case"previous":case"next":{const r=e.relativePositional;if(r){const e=r.from?Ys(await Is(r.from,t)):t.me,i=r.within?Ys(await Is(r.within,t)):void 0,a=r.inElt?await Is(r.inElt,t):void 0;return Ls(t,n).evaluate(t,s[0],e,{within:i,inElt:a,inSearch:r.inSearch,wrapping:r.wrapping})}return Ls(t,n).evaluate(t,...s)}case"first":return Ls(t,"first").evaluate(t,...s);case"last":return Ls(t,"last").evaluate(t,...s);default:if("function"==typeof r)return r(...s);throw Error("Cannot call non-function: "+n)}}if("function"==typeof r){const n=await Promise.all(e.arguments.map(e=>Is(e,t)));if("memberExpression"===e.callee.type&&e.callee.object){const s=await Is(e.callee.object,t);return r.apply(s,n)}return r(...n)}throw Error("Cannot call non-function")}(e,t);case"selector":return async function(e,t){let r=e.value;if("string"==typeof r&&!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(r))return lt.styleRef.evaluate(t,r.slice(1));if("string"==typeof r&&e.fromQuery&&/\$[^=]/.test(r)){const{selector:n,elements:s}=await async function(e,t){const r=ni(e),n=await Promise.all(r.filter(e=>"expr"in e).map(e=>Hs(e.expr,t)));return si(r,n)}(r,t),i=ti(e,n);s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return await lt.elementWithSelector.evaluate(t,i)}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}"string"==typeof r&&!e.fromQuery&&r.includes("{")&&(r=await function(e,t){return Gs(e,/\{([^}]*)\}/g,async(e,r)=>(await Hs(r.trim(),t)??"")+"")}(r,t));const n="string"==typeof r?ti(e,r):r,s=await lt.elementWithSelector.evaluate(t,n);return Ie(s,r,e.fromQuery)}(e,t);case"contextReference":return async function(e,t){switch(e.contextType){case"me":case"you":case"it":return Ls(t,e.contextType).evaluate(t);case"my":case"myself":case"I":return lt.me.evaluate(t);case"your":case"yourself":return lt.you.evaluate(t);case"its":return lt.it.evaluate(t);case"event":return t.event;case"target":return t.target??t.event?.target??lt.me.evaluate(t);case"body":return"undefined"!=typeof document?document.body:void 0;case"document":return lt.document.evaluate(t);case"window":return lt.window.evaluate(t);default:return}}(e,t);case"possessiveExpression":return async function(e,t){const r=await Is(e.object,t),n=e.property.name;return Ls(t,"possessive").evaluate(t,r,n)}(e,t);case"eventHandler":return async function(e,t){return{event:e.event,selector:e.selector,commands:e.commands,handler:async r=>{const n={...t,event:r,target:r.target,currentTarget:r.currentTarget};for(const t of e.commands)await Is(t,n)}}}(e,t);case"conditionalExpression":return async function(e,t){const r=await Is(e.test,t);if(r)return Is(e.consequent,t);if(e.alternate)return Is(e.alternate,t);return}(e,t);case"string":return e.value;case"arrayLiteral":return async function(e,t){const r=[];for(const n of e.elements)r.push(await Is(n,t));return r}(e,t);case"objectLiteral":return async function(e,t){const r={};for(const n of e.properties){const e=n.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value:await Is(e,t)+"",r[s]=await Is(n.value,t)}return r}(e,t);case"attributeAccess":return async function(e,t){const r=e.attributeName;if(t.me&&t.me instanceof Element)return t.me.getAttribute(r);return"@"+r}(e,t);case"propertyOfExpression":return async function(e,t){const r=e.property;if("identifier"!==r?.type)throw Error('Property name must be an identifier in "the X of Y" pattern');const n=r.name,s=await Is(e.target,t);if(null==s)throw Error(`Cannot access property "${n}" of ${s}`);return Ls(t,"possessive").evaluate(t,s,n)}(e,t);case"templateLiteral":return async function(e,t){let r=e.value;return r=await Gs(r,/\$([a-zA-Z_$][a-zA-Z0-9_.$]*|\d+)/g,async(e,r)=>{try{if(/^\d+$/.test(r))return r;if(r.includes(".")){const e=r.split(".");let n=Zs(e[0],t);for(let t=1;e.length>t&&null!=n;t++)n=n[e[t]];return(n??"")+""}return(Zs(r,t)??"")+""}catch{return""}}),r=await Gs(r,/\$(?:\{([^}]+)\}|\(([^)]+)\))/g,async(e,r,n)=>{const s=r||n;try{return await Hs(s,t)+""}catch{return"undefined"}}),r}(e,t);case"stringPostfix":return async function(e,t){const r=await Is(e.expression,t);return`${r}${e.unit}`}(e,t);case"blockLiteral":return Ks(e,t);default:throw Error("Unhandled evaluable AST node type: "+(e.type+""))}}async function Is(e,t){if(!e)throw Error("Cannot evaluate null or undefined AST node");if("literal"===e.type)return e.value;if("identifier"===e.type)return Vs(e,t);if(Ns.has(e.type))return Ps(e,t);const r=de.get(e.type);if(r)return r(e,t);throw Error("Unknown AST node type: "+e.type)}class js extends Error{constructor(e){super(`Expression node "${e}" is not synchronously evaluable`),this.name="NotSyncEvaluable"}}const Rs=new Set(["literal","string","selector","identifier","contextReference","arrayLiteral","objectLiteral","asExpression","stringPostfix","blockLiteral","memberExpression"]);function Ms(e,t){const r=e?.type;if("string"==typeof r&&Rs.has(r))return function(e,t){switch(e.type){case"literal":case"string":return e.value;case"selector":return function(e,t){const r=e.value;if("string"!=typeof r)throw new js("selector");if(!e.fromQuery&&/^\*[a-zA-Z][\w-]*$/.test(r))throw new js("selector");if(e.fromQuery&&/\$[^=]/.test(r)){const{selector:n,elements:s}=function(e,t){const r=ni(e),n=r.filter(e=>"expr"in e).map(e=>$s(e.expr,t));return si(r,n)}(r,t),i=ti(e,n),a=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!a)throw new js("selector");s.forEach((e,t)=>e.setAttribute("data-hs-query-id",t+""));try{return Array.from(a.querySelectorAll(i))}finally{s.forEach(e=>e.removeAttribute("data-hs-query-id"))}}const n=!e.fromQuery&&r.includes("{")?function(e,t){return e.replace(/\{([^}]*)\}/g,(e,r)=>($s(r.trim(),t)??"")+"")}(r,t):r,s=ti(e,n),i=t?.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!i)throw new js("selector");return Ie(Array.from(i.querySelectorAll(s)),n,e.fromQuery)}(e,t);case"identifier":return function(e,t,r){return"me"===e||"my"===e||"I"===e?t.me:"you"===e||"your"===e||"yourself"===e?t.you:"it"===e||"its"===e?t.it??t.result:"result"===e?t.result??t.it:"window"===e?"undefined"!=typeof window?window:globalThis:"document"===e?"undefined"!=typeof document?document:void 0:"element"===r?be(t,e):t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):e.startsWith("$")&&t.globals?.has(e.slice(1))?t.globals.get(e.slice(1)):"body"===e&&"undefined"!=typeof document?document.body:"detail"===e?t.event?.detail??null:"sender"===e?t.event?.detail?.sender??null:void 0!==t[e]?t[e]:"undefined"!=typeof globalThis&&e in globalThis?globalThis[e]:void 0}(e.name,t,e.scope);case"contextReference":return function(e,t){switch(e){case"me":return t.me;case"you":return t.you;case"it":return t.it??t.result;case"event":return t.event;case"target":return t.target??t.event?.target??t.me;default:throw new js("contextReference")}}(e.contextType,t);case"arrayLiteral":return e.elements.map(e=>Ms(e,t));case"objectLiteral":return function(e,t){const r={};for(const n of e.properties){const e=n.key;let s;s="identifier"===e.type?e.name:"literal"===e.type&&"string"===e.valueType?e.value+"":Ms(e,t)+"",r[s]=Ms(n.value,t)}return r}(e,t);case"asExpression":return at(Ms(e.expression,t),zs(e.targetType),t);case"stringPostfix":return`${Ms(e.expression,t)}${e.unit}`;case"blockLiteral":return Ks(e,t);case"memberExpression":{const r=Ms(e.object,t);if(null==r)return;if(r instanceof Element||Array.isArray(r)||"undefined"!=typeof Node&&r instanceof Node)throw new js("memberExpression");const n=r[e.computed?Ms(e.property,t)+"":e.property.name];return"function"==typeof n?n.bind(r):n}default:throw new js((e.type??"unknown")+"")}}(e,t);throw new js("string"==typeof r?r:"unknown")}function $s(e,t){const r=Ts(e);if(!r.success||!r.node){const e=r.error??r.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}return Ms(r.node,t)}async function Hs(e,t){const r=Ts(e);if(!r.success||!r.node){const e=r.error??r.errors?.[0];throw Error("Failed to parse expression: "+(e?.message??"unknown error"))}const n=t.registry?t:{...t,registry:await Ws()};return Is(r.node,n)}let qs=null;async function Ws(){if(!qs){const e=await Promise.resolve().then(function(){return Gi});qs=e.createFullExpressionRegistry()}return qs}async function Vs(e,t){const r=e.name;return r.startsWith("$")?ae(r.slice(1),t):"global"===e.scope&&ae(r,t),"me"===r||"my"===r||"I"===r?lt.me.evaluate(t):"you"===r||"your"===r||"yourself"===r?lt.you.evaluate(t):"it"===r||"its"===r?lt.it.evaluate(t):"result"===r?lt.result.evaluate(t):"window"===r?lt.window.evaluate(t):"document"===r?lt.document.evaluate(t):"global"===e.scope&&t.globals?.has(r)?t.globals.get(r):"element"===e.scope?be(t,r):t.locals&&t.locals.has(r)?(ce(r,t),t.locals.get(r)):t.globals&&t.globals.has(r)?t.globals.get(r):r.startsWith("$")&&t.globals&&t.globals.has(r.slice(1))?t.globals.get(r.slice(1)):"body"===r&&"undefined"!=typeof document?document.body:"detail"===r?t.event?.detail??null:"sender"===r?t.event?.detail?.sender??null:void 0!==t[r]?t[r]:"undefined"!=typeof globalThis&&r in globalThis?globalThis[r]:void 0}function Ds(e){const t=e;if(!t)return null;if("identifier"===t.type&&"string"==typeof t.name)return[t.name];if("memberExpression"===t.type&&!t.computed){const e=Ds(t.object);if(!e)return null;const r=t.property,n="identifier"===r?.type&&"string"==typeof r.name?r.name:"string"==typeof r?.value?r.value:null;return null==n?null:[...e,n]}return null}function Bs(e,t){return Array.isArray(t)?t.includes(e):"string"==typeof t?t.includes(e+""):e instanceof Node&&t instanceof Node?e===t||t.contains(e):null!=t&&"object"==typeof t&&e in t}function Fs(e,t){return e&&"selector"===e.type&&"string"==typeof e.value?e.value:t}function _s(e,t,r){if(void 0!==r)return;const n=e.right;if(!n||"identifier"!==n.type||"string"!=typeof n.name)return;if(null==t||"object"!=typeof t)return;const s=t[n.name];return"boolean"==typeof s?!0===s:void 0}function Us(e,t,r){return e instanceof Node&&t instanceof Node&&0!==(e.compareDocumentPosition(t)&r)}function zs(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){if("string"==typeof e.name)return e.name;if("string"==typeof e.value)return e.value}return e+""}function Ks(e,t){const r=e.parameters??[];return(...n)=>{const s=new Map(t.locals??new Map);r.forEach((e,t)=>s.set(e,n[t]));const i={...t,locals:s};try{return Ms(e.body,i)}catch(t){if(t instanceof js)return Is(e.body,i);throw t}}}function Zs(e,t){if(t.locals?.has(e))return ce(e,t),t.locals.get(e);if("me"===e&&t.me)return t.me;if("you"===e&&t.you)return t.you;if("it"===e){const e=t.it??t.result;if(e)return e}if("result"===e){const e=t.result??t.it;if(e)return e}return"undefined"!=typeof window&&"window"===e?window:t.globals?.has(e)?t.globals.get(e):void 0}async function Gs(e,t,r){const n=[];let s;for(;null!==(s=t.exec(e));)n.push({index:s.index,length:s[0].length,replacement:await r(s[0],...s.slice(1))});let i=e;for(let e=n.length-1;e>=0;e--){const{index:t,length:r,replacement:s}=n[e];i=i.substring(0,t)+s+i.substring(t+r)}return i}function Qs(e,t,r){if("string"==typeof t&&t.startsWith("@")){const r=t.substring(1);return e&&"function"==typeof e.getAttribute?e.getAttribute(r):void 0}return e instanceof Element&&"string"==typeof t?Ke(e,t):Hr(e)&&!(t in e)?Ls(r,"possessive").evaluate(r,e,t):e?.[t]}const Js=new Set(["closest","previous","next"]);function Ys(e){return e instanceof Element?e:Array.isArray(e)&&e[0]instanceof Element?e[0]:void 0}const Xs=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");const ei=/[:&()[\]/]/g;function ti(e,t){return e.fromQuery||!t.startsWith(".")||t.includes("{")?function(e){return e.replace(Xs,"$1\\:")}(t):function(e){return e[0]+e.slice(1).replace(ei,"\\$&")}(t)}const ri=/\$\{([^}]+)\}|\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g;function ni(e){const t=[];let r,n=0;for(ri.lastIndex=0;null!==(r=ri.exec(e));)r.index>n&&t.push({lit:e.slice(n,r.index)}),t.push({expr:r[1]??r[2]}),n=r.index+r[0].length;return e.length>n&&t.push({lit:e.slice(n)}),t}function si(e,t){let r="";const n=[];let s=0;for(const i of e){if("lit"in i){r+=i.lit;continue}const e=t[s++];Be(e)?(r+=`[data-hs-query-id='${n.length}']`,n.push(e)):r+=(e??"")+""}return{selector:r,elements:n}}class ii{constructor(){this.hooks=new Map,this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}register(e,t){this.unregister(e),this.hooks.set(e,t),t.beforeExecute&&this.beforeExecuteHooks.push(t.beforeExecute),t.afterExecute&&this.afterExecuteHooks.push(t.afterExecute),t.onError&&this.onErrorHooks.push(t.onError),t.interceptCommand&&this.interceptCommandHooks.push(t.interceptCommand)}unregister(e){const t=this.hooks.get(e);if(!t)return!1;if(t.beforeExecute){const e=this.beforeExecuteHooks.indexOf(t.beforeExecute);e>-1&&this.beforeExecuteHooks.splice(e,1)}if(t.afterExecute){const e=this.afterExecuteHooks.indexOf(t.afterExecute);e>-1&&this.afterExecuteHooks.splice(e,1)}if(t.onError){const e=this.onErrorHooks.indexOf(t.onError);e>-1&&this.onErrorHooks.splice(e,1)}if(t.interceptCommand){const e=this.interceptCommandHooks.indexOf(t.interceptCommand);e>-1&&this.interceptCommandHooks.splice(e,1)}return this.hooks.delete(e)}has(e){return this.hooks.has(e)}async runBeforeExecute(e){for(const t of this.beforeExecuteHooks)await t(e)}async runAfterExecute(e,t){for(const r of this.afterExecuteHooks)await r(e,t)}async runOnError(e,t){let r=t;for(const t of this.onErrorHooks){const n=await t(e,r);n instanceof Error&&(r=n)}return r}shouldIntercept(e,t){for(const r of this.interceptCommandHooks)if(r(e,t))return!0;return!1}getRegisteredNames(){return Array.from(this.hooks.keys())}clear(){this.hooks.clear(),this.beforeExecuteHooks=[],this.afterExecuteHooks=[],this.onErrorHooks=[],this.interceptCommandHooks=[]}}class ai{constructor(e){this.elementCleanups=new WeakMap,this.elementCount=0,this.typeCounts={listener:0,observer:0,interval:0,timeout:0,custom:0},this.globalCleanups=[],this.debugMode=e?.debug??!1}registerListener(e,t,r,n,s){this.addCleanup(e,{type:"listener",target:t,eventName:r,cleanup:()=>{t.removeEventListener(r,n,s)},description:r+" listener"})}registerObserver(e,t){this.addCleanup(e,{type:"observer",cleanup:()=>{t.disconnect()},description:"MutationObserver"})}registerInterval(e,t){this.addCleanup(e,{type:"interval",cleanup:()=>{clearInterval(t)},description:"Interval"})}registerTimeout(e,t){this.addCleanup(e,{type:"timeout",cleanup:()=>{clearTimeout(t)},description:"Timeout"})}registerCustom(e,t,r){this.addCleanup(e,{type:"custom",cleanup:t,description:r||"Custom cleanup"})}registerGlobal(e,t="custom",r){this.globalCleanups.push({type:t,cleanup:e,description:r||"Global cleanup"})}addCleanup(e,t){const r=this.elementCleanups.get(e);r?r.push(t):(this.elementCleanups.set(e,[t]),this.elementCount++),this.typeCounts[t.type]++}cleanupElement(e){const t=this.elementCleanups.get(e);if(!t||0===t.length)return 0;let r=0;for(const e of t){try{e.cleanup(),r++}catch(e){}this.typeCounts[e.type]--}return this.elementCleanups.delete(e),this.elementCount--,r}cleanupElementTree(e){let t=this.cleanupElement(e);const r=e.querySelectorAll("*");for(const e of r)t+=this.cleanupElement(e);return t}cleanupGlobal(){let e=0;for(const t of this.globalCleanups)try{t.cleanup(),e++}catch(e){}return this.globalCleanups=[],e}cleanupAll(){return this.cleanupGlobal()}hasCleanups(e){const t=this.elementCleanups.get(e);return void 0!==t&&t.length>0}getCleanupCount(e){const t=this.elementCleanups.get(e);return t?.length??0}getStats(){let e=0,t=0,r=0,n=0,s=0;for(const i of this.globalCleanups)switch(i.type){case"listener":e++;break;case"observer":t++;break;case"interval":r++;break;case"timeout":n++;break;case"custom":s++}return{elementsTracked:this.elementCount,listeners:this.typeCounts.listener+e,observers:this.typeCounts.observer+t,intervals:this.typeCounts.interval+r,timeouts:this.typeCounts.timeout+n,custom:this.typeCounts.custom+s,global:this.globalCleanups.length}}setDebugMode(e){this.debugMode=e}}class oi{constructor(){this.sources=new Map,this.subscriptions=new Map,this.nextId=1}register(e,t){const r=e.toLowerCase();this.sources.has(r),this.sources.set(r,t)}unregister(e){const t=e.toLowerCase(),r=this.sources.get(t);if(r){for(const[e,r]of this.subscriptions.entries())r.source===t&&(r.unsubscribe(),this.subscriptions.delete(e));return r.destroy?.(),this.sources.delete(t)}return!1}get(e){return this.sources.get(e.toLowerCase())}has(e){return this.sources.has(e.toLowerCase())}subscribe(e,t,r){const n=this.get(e);if(!n)return;n.initialize?.();const s=n.subscribe(t,r);return this.subscriptions.set(s.id,s),s}unsubscribe(e){const t=this.subscriptions.get(e);return!!t&&(t.unsubscribe(),this.subscriptions.delete(e))}getSourceNames(){return Array.from(this.sources.keys())}getSubscriptions(){return Array.from(this.subscriptions.values())}findSourceForEvent(e){for(const[t,r]of this.sources.entries())if(r.supports?.(e)??r.supportedEvents?.includes(e))return t}generateId(){return`sub_${this.nextId++}_${Date.now().toString(36)}`}destroy(){for(const e of this.subscriptions.values())e.unsubscribe();this.subscriptions.clear();for(const e of this.sources.values())e.destroy?.();this.sources.clear()}}const ci={evaluate:(e,t)=>Is(e,t)};class li{constructor(e,t,r){this.impl=e,this.hookRegistry=r??null}setHookRegistry(e){this.hookRegistry=e}createHookContext(e,t,r={}){return{commandName:this.name,element:e.me instanceof Element?e.me:null,args:t,modifiers:r,event:e.event??void 0,executionContext:e}}get name(){const e=this.impl.name;if(e)return e;const t=this.impl.metadata?.name;return"string"==typeof t?t:""}get metadata(){const e=this.impl.metadata?.syntax;return{description:this.impl.metadata?.description||"",examples:this.impl.metadata?.examples||[],syntax:"string"==typeof e?e:e?e.join(" | "):""}}async execute(e,...t){const r=t[0],n=this.createHookContext(e,t,r&&"object"==typeof r&&"modifiers"in r&&r.modifiers||{});try{if(this.hookRegistry&&await this.hookRegistry.runBeforeExecute(n),this.hookRegistry?.shouldIntercept(this.name,n))return;e.variables||(e.variables=new Map);const s=e;let i,a;if(this.impl.parseInput&&"function"==typeof this.impl.parseInput)if(r&&"object"==typeof r&&("args"in r||"modifiers"in r)){const t=r.modifiers,n=t?.when||t?.where;if(n&&!this.impl.ownsConditionalModifier){if(!await Is(n,e))return}i=await this.impl.parseInput({args:r.args||[],modifiers:t||{},commandName:r.commandName,bodies:r.bodies},ci,e)}else i=t;else i=t;if(2===this.impl.execute.length)a=await this.impl.execute(i,s);else{const e=Array.isArray(i)?i:[i];a=await this.impl.execute(s,...e)}return this.hookRegistry&&await this.hookRegistry.runAfterExecute(n,a),a}catch(e){if(this.hookRegistry&&e instanceof Error){throw await this.hookRegistry.runOnError(n,e)}throw e}}validate(e){return{isValid:!this.impl.validate||this.impl.validate(e),errors:[],suggestions:[]}}}class ui{constructor(e,t){this.adapters=new Map,this.implementations=new Map,this.hookRegistry=t}setHookRegistry(e){this.hookRegistry=e;for(const t of this.adapters.values())t.setHookRegistry(e)}getHookRegistry(){return this.hookRegistry}register(e){const t=e.name||e.metadata?.name;if(!t||"string"!=typeof t)throw Error("Cannot register command: no name found. Provide a 'name' property or 'metadata.name' on the implementation.");const r=t.toLowerCase();this.implementations.set(r,e);const n=new li(e,void 0,this.hookRegistry);this.adapters.set(r,n),j.add(r);const s=e.metadata?.aliases;if(s&&Array.isArray(s))for(const t of s){const r=t.toLowerCase();this.implementations.set(r,e),this.adapters.set(r,n),j.add(r)}}getAdapter(e){return this.adapters.get(e.toLowerCase())}has(e){return this.adapters.has(e.toLowerCase())}getCommandNames(){return Array.from(this.adapters.keys())}getImplementation(e){return this.implementations.get(e.toLowerCase())}getAdapters(){return new Map(this.adapters)}validateCommand(e,t){const r=this.getAdapter(e);return r?r.validate(t):{isValid:!1,errors:[{type:"runtime-error",message:"Unknown command: "+e,suggestions:["Available commands: "+this.getCommandNames().join(", ")]}],suggestions:["Available commands: "+this.getCommandNames().join(", ")]}}}function di(e){const t=e?.commands??new ui,r=e?.eventSources??new oi,n=new Set,s={commands:t,eventSources:r,use(e){if(!n.has(e.name)){if(e.commands)for(const r of e.commands)t.register(r);if(e.eventSources)for(const t of e.eventSources)r.register(t.name,t);e.setup?.(s),n.add(e.name)}},reset(){n.clear()}};return s}let mi=null;function pi(){return mi||(mi=di()),mi}class hi{constructor(e={}){const t=pi();this.options={enableEventSources:e.enableEventSources??!0,registry:e.registry??{}},this.eventSourceRegistry=this.options.registry.eventSources??t.eventSources}getEventSource(e){if(!this.options.enableEventSources)return;const t=this.eventSourceRegistry.get(e);if(t)return t;const r=this.eventSourceRegistry.findSourceForEvent(e);if(r){return this.eventSourceRegistry.get(r)}}hasEventSource(e){return void 0!==this.getEventSource(e)}subscribeToEventSource(e,t,r){if(!this.options.enableEventSources)throw Error("Event sources are disabled in this runtime");const n=this.eventSourceRegistry.subscribe(e,t,r);if(!n)throw Error(`Failed to subscribe to event source '${e}'`);return n}getEventSourceNames(){return this.eventSourceRegistry.getSourceNames()}destroy(){this.eventSourceRegistry.destroy()}}class fi extends Error{constructor(e){super(`'${e.type}' used outside of a loop`),this.signal=e,this.name="StrayControlFlowError"}}function yi(e){return null!==e&&"object"==typeof e&&"command"in e&&"selector"in e}const gi=new WeakMap;function vi(e,t=new Set){if(null===e||"object"!=typeof e)return t;if(Array.isArray(e)){for(const r of e)vi(r,t);return t}const r=e;"identifier"===r.type&&"string"==typeof r.name&&t.add(r.name);for(const e of Object.keys(r))"start"!==e&&"end"!==e&&"line"!==e&&"column"!==e&&vi(r[e],t);return t}class bi{constructor(e){if(this.autoCleanupObserver=null,this.registryIntegration=null,this.runtimeWarnings=[],this.ops=new WeakMap,this.options={commandTimeout:1e4,enableErrorReporting:!0,enableAutoCleanup:!0,...e},this.registry=e.registry,this.expressionRegistry=e.expressionRegistry,this.behaviorRegistry=new Map,this.globalVariables=ke(),this.hookRegistry=new ii,e.hooks&&this.hookRegistry.register("default",e.hooks),this.registry.setHookRegistry(this.hookRegistry),this.cleanupRegistry=new ai,this.options.enableAutoCleanup&&this.setupAutoCleanup(),!1!==e.registryIntegration){this.registryIntegration=new hi("object"==typeof e.registryIntegration?e.registryIntegration:{})}this.behaviorAPI={has:e=>this.behaviorRegistry.has(e),get:e=>this.behaviorRegistry.get(e),set:(e,t)=>this.behaviorRegistry.set(e,t),resolve:null,install:async(e,t,r)=>await this.installBehaviorOnElement(e,t,r)}}setupAutoCleanup(){"undefined"!=typeof MutationObserver&&"undefined"!=typeof document&&(this.autoCleanupObserver=new MutationObserver(e=>{const t=[];for(const r of e)for(const e of r.removedNodes)e instanceof Element&&t.push(e);t.length>0&&queueMicrotask(()=>{for(const e of t)if(!e.isConnected){this.cleanupRegistry.cleanupElementTree(e)}})}),document.body?this.autoCleanupObserver.observe(document.body,{childList:!0,subtree:!0}):document.addEventListener("DOMContentLoaded",()=>{this.autoCleanupObserver?.observe(document.body,{childList:!0,subtree:!0})},{once:!0}))}registerHooks(e,t){this.hookRegistry.register(e,t)}unregisterHooks(e){return this.hookRegistry.unregister(e)}getRegisteredHooks(){return this.hookRegistry.getRegisteredNames()}cleanup(e){return this.cleanupRegistry.cleanupElement(e)}trackListener(e,t,r,n,s){this.cleanupRegistry.registerListener(e,t,r,n,s)}cleanupTree(e){return this.cleanupRegistry.cleanupElementTree(e)}getCleanupStats(){return this.cleanupRegistry.getStats()}getCleanupRegistry(){return this.cleanupRegistry}logError(...e){this.options.enableErrorReporting&&console.error(...e)}logWarn(...e){this.options.enableErrorReporting&&console.warn(...e)}destroy(){this.autoCleanupObserver&&(this.autoCleanupObserver.disconnect(),this.autoCleanupObserver=null),this.cleanupRegistry.cleanupAll(),this.hookRegistry.clear(),this.behaviorRegistry.clear()}hasErrorDiagnostics(e){const t=e.diagnostics;return!!t?.some(e=>"error"===e.severity)}getWarnings(){return this.runtimeWarnings}async execute(e,t){const n=await this.executeNode(e,t);if(r(n))return n.value;const s=n.error;if("return"===s.type){const e=s.returnValue;return void 0!==e&&Object.assign(t,{it:e,result:e}),e}if("halt"!==s.type&&"exit"!==s.type)throw new fi(s)}async executeNode(e,t){return this.prepareContext(t),this.compile(e)(t)}prepareContext(e){e.registry||(e.registry=this.expressionRegistry),e.locals.has("_behaviors")||e.locals.set("_behaviors",this.behaviorAPI)}compile(e){const t=this.ops.get(e);if(t)return t;const r=this.compileNode(e);return this.ops.set(e,r),r}compileSequence(t){const n=t.map(e=>this.compile(e));return async t=>{let s;for(const e of n){const n=await e(t);if(!r(n))return n;s=n.value}return e(s)}}compileNode(t){if(this.hasErrorDiagnostics(t)){const r=t.diagnostics?.[0],n=r?.message||"Skipped error node";return async()=>(this.runtimeWarnings.push(n),e(void 0))}switch(t.type){case"command":{const e=t,r=(e.args??[]).map(e=>function(e){const t=e?.type;return"block"===t||"command"===t}(e)?this.compile(e):void 0),n=r.some(Boolean);return t=>this.processCommandWithResult(e,t,n?r:void 0)}case"initBlock":case"block":{const n=t,s=(Array.isArray(n.commands)?n.commands:[]).map(e=>this.compile(e)),i="initBlock"===t.type;return async t=>{for(const e of s){const n=await e(t);if(!r(n)){if(i&&"halt"===n.error.type)break;return n}}return e(void 0)}}case"sequence":case"CommandSequence":{const e=t;return t=>this.executeCommandSequenceWithResult(e.commands||[],t)}case"Program":return e=>this.executeProgram(t,e);default:return e=>this.dispatch(t,e)}}async dispatch(t,r){switch(t.type){case"eventHandler":return e(await this.executeEventHandler(t,r));case"event":{const n={type:"eventHandler",event:t.event,events:[t.event],commands:t.body||[],target:t.filter,modifiers:t.modifiers||{}};return e(await this.executeEventHandler(n,r))}case"behavior":return e(await this.executeBehaviorDefinition(t,r));case"def":return e(this.installFunction(t,r));case"objectLiteral":return e(await this.executeObjectLiteral(t,r));default:return await this.evaluateExpressionWithResult(t,r)}}async processCommandWithResult(r,n,s){const{name:i,args:a,modifiers:o}=r,c=i.toLowerCase();if(!this.registry.has(c)){const e=`Unknown command: ${i}. Ensure it is registered in the Runtime options.`;throw this.logWarn(e),Error(e)}const l=await this.registry.getAdapter(c);if(!l)throw Error(`Command '${c}' is registered but failed to load adapter.`);try{const r=await l.execute(n,{args:a||[],modifiers:o||{},bodies:s,commandName:c,runtime:this});return"object"==typeof(u=r)&&null!==u&&"type"in u&&"string"==typeof u.type&&["halt","exit","break","continue","return"].includes(u.type)?t(r):e(r)}catch(e){throw this.logError(`Error executing command '${c}':`,e),e}var u}async executeCommandSequenceWithResult(t,n){let s;for(const i of t){if(this.hasErrorDiagnostics(i)){const e=i.diagnostics?.[0];this.runtimeWarnings.push(e?.message||"Skipped error node");continue}if("command"===i.type){const t=await this.compile(i)(n);if(!r(t)){const r=t.error;switch(r.type){case"halt":case"exit":case"break":case"continue":return t;case"return":return void 0!==r.returnValue&&Object.assign(n,{it:r.returnValue,result:r.returnValue}),e(r.returnValue)}}s=t.value}else{const e=await this.evaluateExpressionWithResult(i,n);if(!r(e))return e;s=e.value}}return e(s)}async evaluateExpression(e,t){const n=t.registry?t:{...t,registry:this.expressionRegistry},s=await Is(e,n);if(yi(s)){const e={type:"command",name:s.command,args:[{type:"literal",value:s.selector}],isBlocking:!1},n=await this.processCommandWithResult(e,t);if(!r(n))throw new fi(n.error);return n.value}return s}async evaluateExpressionWithResult(n,s){const i=s.registry?s:{...s,registry:this.expressionRegistry},a=await async function(r,n){try{return e(await Is(r,n))}catch(e){if(e instanceof Error){const r=e;if(r.isHalt)return t({type:"halt"});if(r.isExit)return t({type:"exit",returnValue:r.returnValue});if(r.isBreak)return t({type:"break"});if(r.isContinue)return t({type:"continue"});if(r.isReturn)return t({type:"return",returnValue:r.returnValue})}throw e}}(n,i);if(!r(a))return a;const o=a.value;if(yi(o)){return this.processCommandWithResult({type:"command",name:o.command,args:[{type:"literal",value:o.selector}],isBlocking:!1},s)}return e(o)}installFunction(e,t){const n=e.params??[],s=e.errorHandler,i=e.finallyHandler,a=e.errorSymbol,o=this.compileSequence(e.body??[]),c=s?this.compileSequence(s):void 0,l=i?this.compileSequence(i):void 0;t.globals.set(e.name,async(...e)=>{const s={...t,locals:new Map(t.locals)};n.forEach((t,r)=>{t&&s.locals.set(t,e[r])});const i=async e=>{const t=await e(s);if(!r(t)){const e=t.error;if("break"===e.type||"continue"===e.type)throw new fi(e);return"return"===e.type?e.returnValue:void 0}return t.value};if(!c&&!l)return await i(o);try{return await i(o)}catch(e){if(!c||e instanceof fi)throw e;return a&&s.locals.set(a,e),await i(c)}finally{l&&await i(l)}})}async executeProgram(t,n){if(!t.statements||!Array.isArray(t.statements))return e(void 0);let s;const i=[],a=[],o=[],c=[];for(const e of t.statements)"eventHandler"===e.type?i.push(e):"def"===e.type?a.push(e):"initBlock"===e.type?o.push(e):c.push(e);for(const e of a)this.executeNode(e,n);for(const e of i){const t=await this.executeNode(e,n);if(!r(t)){if("halt"===t.error.type||"exit"===t.error.type)break;return t}}for(const e of o){const t=await this.executeNode(e,n);if(!r(t)){if("halt"===t.error.type||"exit"===t.error.type)break;if("return"===t.error.type){s=t.error.returnValue;break}return t}s=t.value}for(const e of c){const t=await this.executeNode(e,n);if(!r(t)){if("halt"===t.error.type||"exit"===t.error.type)break;if("return"===t.error.type){s=t.error.returnValue;break}return t}s=t.value}return e(s)}async executeBlock(e,t){return this.compile(e)(t)}async executeObjectLiteral(e,t){const r={};if(!e.properties)return r;for(const n of e.properties){let e;if("identifier"===n.key.type)e=n.key.name;else if("literal"===n.key.type)e=n.key.value+"";else{e=await this.execute(n.key,t)+""}const s=await this.execute(n.value,t);r[e]=s}return r}async executeBehaviorDefinition(e,t){const{name:r,parameters:n=[],eventHandlers:s=[],initBlock:i}=e,a=e.imperativeInstaller;this.behaviorRegistry.set(r,"function"==typeof a?{name:r,parameters:n,type:"imperative",install:a}:{name:r,parameters:n,eventHandlers:s,initBlock:i&&i})}async installBehaviorOnElement(e,t,r){let n=this.behaviorRegistry.get(e);if(!n&&(this.behaviorAPI.resolve&&this.behaviorAPI.resolve(e)&&(n=this.behaviorRegistry.get(e)),!n))throw Error(`Behavior "${e}" not found`);if("imperative"===n.type)return void("function"==typeof n.install&&n.install(t,r));const s={me:t,owner:t,you:null,it:null,result:null,locals:new Map,globals:this.globalVariables,registry:this.expressionRegistry};if(n.parameters)for(const e of n.parameters){s.locals.set(e,e in r?r[e]:void 0)}for(const[e,t]of Object.entries(r))n.parameters?.includes(e)||s.locals.set(e,t);if(n.initBlock){const t=this.options.commandTimeout??1e4;try{await Promise.race([this.execute(n.initBlock,s),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" init block timed out after ${t}ms`)),t))])}catch(e){throw e}}if(n.eventHandlers){const t=this.options.commandTimeout??1e4;for(const r of n.eventHandlers)await Promise.race([this.executeEventHandler(r,s),new Promise((r,n)=>setTimeout(()=>n(Error(`Behavior "${e}" handler attachment timed out after ${t}ms`)),t))])}}async executeEventHandler(e,t){const{event:r,events:n,commands:s,target:i,args:a,selector:o,condition:c,attributeName:l,watchTarget:u,modifiers:d,errorSymbol:m,errorHandler:p,finallyHandler:h}=e,f=n&&n.length>0?n:[r];let y=[],g=null;if(i){const e="string"==typeof i?i.toLowerCase():"";if("window"===e||"the window"===e)g=window;else if("document"===e||"the document"===e||"body"===e)g=document;else if("me"===e||"myself"===e)y=t.me?[t.me]:[];else if("string"==typeof i&&t.locals.has(i)){const e=t.locals.get(i);this.isElement(e),this.isElement(e)?y=[e]:Array.isArray(e)?y=e.filter(e=>this.isElement(e)):"string"==typeof e&&(y=this.queryElements(e,t))}else y=this.queryElements(i,t)}else y=t.me?[t.me]:[];if(0===y.length&&!g)return;if("mutation"===r&&l)return void this.setupMutationObserver(y,l,s,t);if("change"===r&&u)return void this.setupChangeObserver(u,s,t);const v=e.customEventSource;if(v&&this.registryIntegration){const e=async e=>{const n=new Map(t.locals),i={...t,locals:n,it:e,event:e};try{await this.execute({type:"program",commands:s},i)}catch(e){this.logError(`[HyperFixi] Error executing commands for custom event '${r}':`,e)}};try{const n=this.registryIntegration.subscribeToEventSource(v,{event:r,handler:e,target:i,selector:o},t);this.cleanupRegistry.registerGlobal(()=>n.unsubscribe(),"listener",`Custom event source '${v}' subscription ${n.id}`)}catch(e){this.logError(`[HyperFixi] Failed to subscribe to custom event source '${v}':`,e)}return}const b=bi.createEventHandler(this,s,t,o,a,{errorSymbol:m,errorHandler:p,finallyHandler:h},1===f.length?c:void 0);let w,E=null;if(d){let e=b;if(d.prevent){const t=e;e=async e=>(e.preventDefault(),t(e))}if(d.stop){const t=e;e=async e=>(e.stopPropagation(),t(e))}if(d.debounce){const t=d.debounce;let r;w=n=>{r&&clearTimeout(r),r=setTimeout(()=>e(n),t)},E=()=>{r&&(clearTimeout(r),r=void 0)}}else if(d.throttle){const t=d.throttle;let r=0;w=n=>{const s=Date.now();t>s-r||(r=s,e(n))}}else w=e}else w=b;const k=d?.once?{once:!0}:void 0;if(g){for(const e of f)g.addEventListener(e,w,k),y.length>0?this.cleanupRegistry.registerListener(y[0],g,e,w):this.cleanupRegistry.registerGlobal(()=>g.removeEventListener(e,w),"listener",`Global ${e} listener`);E&&(y.length>0?this.cleanupRegistry.registerCustom(y[0],E,"debounce-timeout"):this.cleanupRegistry.registerGlobal(E,"timeout","debounce-timeout"))}else for(const e of y){for(const t of f){if("resize"===t&&"undefined"!=typeof ResizeObserver){const t=new ResizeObserver(e=>{for(const r of e){const e=new CustomEvent("resize",{detail:r,bubbles:!1,cancelable:!1});if(e.synthetic=!0,w(e),k?.once){t.disconnect();break}}});t.observe(e),this.cleanupRegistry.registerCustom(e,()=>t.disconnect(),"resize-observer");continue}e.addEventListener(t,w,k),this.cleanupRegistry.registerListener(e,e,t,w)}E&&this.cleanupRegistry.registerCustom(e,E,"debounce-timeout")}}static createEventHandler(e,t,n,s,i,a,o){const c=e.compileSequence(t),l=a?.errorHandler?e.compileSequence(a.errorHandler):void 0,u=a?.finallyHandler?e.compileSequence(a.finallyHandler):void 0;return async t=>{const d=gi.get(t)??0;if(d>=100)return;if(gi.set(t,d+1),s&&t.target instanceof Element)try{if(!t.target.matches(s)&&!t.target.closest(s))return}catch{}const m=new Map(n.locals),p={...n,locals:m,it:t,event:t};if(m.has("target")||p.locals.set("target",t.target),i&&i.length>0){const e=t,r=e.detail;for(const t of i){p.locals.set(t,e[t]??r?.[t]??null)}}if(o){const r=t;for(const e of vi(o))!p.locals.has(e)&&e in r&&p.locals.set(e,r[e]);let n;try{n=await e.evaluateExpression(o,p)}catch(e){return}if(!n)return}e.prepareContext(p);const h=async t=>{let n;try{n=await t(p)}catch(t){throw e.logError("COMMAND FAILED:",t),t}if(r(n))return;const s=n.error;if("return"===s.type&&void 0!==s.returnValue&&Object.assign(p,{it:s.returnValue,result:s.returnValue}),"break"===s.type||"continue"===s.type)throw new fi(s)};if(l||u)try{await h(c)}catch(e){if(!l||e instanceof fi)throw e;a?.errorSymbol&&p.locals.set(a.errorSymbol,e),await h(l)}finally{u&&await h(u)}else await h(c)}}setupMutationObserver(e,t,n,s){for(const i of e){const e=new MutationObserver(async e=>{for(const a of e)if("attributes"===a.type&&a.attributeName===t){const e={...s,me:i,it:a,locals:new Map(s.locals)},o=a.oldValue,c=i.getAttribute(t);e.locals.set("oldValue",o),e.locals.set("newValue",c);for(const t of n){let n;try{n=await this.executeNode(t,e)}catch(e){this.logError("Error executing mutation handler command:",e)}if(n&&!r(n)){const e=n.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});e.observe(i,{attributes:!0,attributeOldValue:!0,attributeFilter:[t]}),this.cleanupRegistry.registerObserver(i,e)}}async setupChangeObserver(e,t,n){const s=await this.execute(e,n);let i=[];this.isElement(s)?i=[s]:Array.isArray(s)&&(i=s.filter(e=>this.isElement(e)));for(const e of i){const s=new MutationObserver(async s=>{for(const i of s)if("childList"===i.type||"characterData"===i.type){const s={...n,me:n.me,it:i,locals:new Map(n.locals)};s.locals.set("target",e);const a=i.oldValue,o=e.textContent;null!==a&&s.locals.set("oldValue",a),s.locals.set("newValue",o);for(const e of t){let t;try{t=await this.executeNode(e,s)}catch(e){this.logError("Error executing change handler command:",e)}if(t&&!r(t)){const e=t.error.type;if("halt"===e||"exit"===e||"return"===e)break}}}});s.observe(e,{childList:!0,characterData:!0,subtree:!0,characterDataOldValue:!0}),this.cleanupRegistry.registerObserver(e,s)}}queryElements(e,t){const r=t.me,n=(r instanceof Element?r.ownerDocument:null)??("undefined"!=typeof document?document:null);if(!n)return[];let s=e;s.startsWith("<")&&s.endsWith("/>")&&(s=s.slice(1,-2).trim());try{return Array.from(n.querySelectorAll(s))}catch{return[]}}isElement(e){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;if(e&&"object"==typeof e){return!!e.style&&!!e.classList}return!1}}function wi(...e){const t=new Map;for(const r of e)for(const[e,n]of Object.entries(r))t.set(e,n);return t}class Ei{trackPerformance(e,t,r,n){}trackSimple(e,t,r,n=(r?"success":"error")){}toBoolean(e){return!1!==e&&0!==e&&0n!==e&&""!==e&&null!=e&&(!He(e)||!isNaN(e))}success(e,t){return{success:!0,value:e,type:t}}failure(e,t,r,n,s=[]){return{success:!1,error:{name:e,type:t,message:r,code:n,suggestions:s}}}validationSuccess(){return{isValid:!0,errors:[],suggestions:[]}}validationFailure(e,t,r=[]){return{isValid:!1,errors:[{type:e,message:t,suggestions:r}],suggestions:r}}isElement(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&1===e.nodeType&&"tagName"in e&&"string"==typeof e.tagName}inferType(e){return null===e?"null":void 0===e?"undefined":this.isElement(e)?"element":Array.isArray(e)?"array":We(e)?"object":typeof e}inferEvaluationType(e){return void 0===e?"Undefined":null===e?"Null":$e(e)?"String":He(e)?"Number":qe(e)?"Boolean":Array.isArray(e)?"Array":this.isElement(e)?"Element":"Object"}normalizeCollection(e){return Array.isArray(e)?e:e instanceof NodeList?Array.from(e):$e(e)?e.split(""):null==e?[]:We(e)&&Symbol.iterator in e?Array.from(e):[]}toNumber(e){if(He(e)&&Number.isFinite(e))return e;if($e(e)){const t=Number(e);return Number.isFinite(t)?t:null}return qe(e)?e?1:0:null}}const ki=vt({value:ft().describe("String literal value")}).strict(),xi=vt({value:yt().describe("Number literal value")}).strict(),Ci=vt({value:gt().describe("Boolean literal value")}).strict(),Ai=vt({left:wt().describe("Left operand"),right:wt().describe("Right operand")}).strict();class Si extends Ei{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=ki,this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid){const t=this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions);return this.trackSimple(e,r,!1),t}let s=t.value;(s.includes("${")||s.includes("$"))&&(s=this.interpolateString(s,e));const i=this.success(s,"string");return this.trackSimple(e,r,!0,s),i}catch(t){return this.trackSimple(e,r,!1),this.failure("StringEvaluationError","runtime-error","String literal evaluation failed: "+(t instanceof Error?t.message:t+""),"STRING_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string literal input",["Provide a value parameter","Ensure value is a string"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}interpolateString(e,t){let r=e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=this.resolveExpression(r.trim(),t);return void 0!==e?e+"":""}catch(e){return""}});return r=r.replace(/\$([a-zA-Z_$][a-zA-Z0-9_.$]*)/g,(e,r)=>{try{const e=this.resolveVariable(r,t);return void 0!==e?e+"":""}catch(e){return""}}),r}resolveExpression(e,t){if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++)n=n[r[e]];return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return"me"===e&&t.me?t.me:"you"===e&&t.you?t.you:"it"===e&&t.it?t.it:"result"===e&&t.result?t.result:t.locals?.has(e)?(ce(e,t),t.locals.get(e)):t.globals?.has(e)?t.globals.get(e):void 0}}class Ti extends Ei{constructor(){super(...arguments),this.name="numberLiteral",this.category="Special",this.syntax="123 or 3.14",this.description="Numeric literal with validation",this.inputSchema=xi,this.outputType="Number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?Number.isFinite(t.value)?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"number")):(this.trackSimple(e,r,!1),this.failure("NumberValidationError","invalid-argument","Number literal must be finite","NUMBER_NOT_FINITE")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("NumberEvaluationError","runtime-error","Number literal evaluation failed: "+(t instanceof Error?t.message:t+""),"NUMBER_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?Number.isFinite(t.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",t.error?.errors.map(e=>e.message).join(", ")||"Invalid number literal input",["Provide a value parameter","Ensure value is a number"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Li extends Ei{constructor(){super(...arguments),this.name="booleanLiteral",this.category="Special",this.syntax="true or false",this.description="Boolean literal values",this.inputSchema=Ci,this.outputType="Boolean",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);return n.isValid?(this.trackSimple(e,r,!0,t.value),this.success(t.value,"boolean")):(this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors.map(e=>e.message).join(", "),"VALIDATION_FAILED",n.suggestions))}catch(t){return this.trackSimple(e,r,!1),this.failure("BooleanEvaluationError","runtime-error","Boolean literal evaluation failed: "+(t instanceof Error?t.message:t+""),"BOOLEAN_EVALUATION_FAILED")}}validate(e){try{const t=this.inputSchema.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid boolean literal input",["Provide a value parameter","Ensure value is a boolean"])}catch(e){return this.validationFailure("runtime-error","Validation failed with exception",["Check input structure and types"])}}}class Oi extends Ei{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=Ai,this.outputType="String",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=Date.now();try{const n=this.validate(t);if(!n.isValid)return this.trackSimple(e,r,!1),this.failure("ValidationError","validation-error",n.errors[0]?.message||"Invalid input","STRING_CONCATENATION_VALIDATION_FAILED",n.suggestions);const s=this.convertToString(t.left),i=s+this.convertToString(t.right);return this.trackSimple(e,r,!0,i),this.success(i,"string")}catch(t){return this.trackSimple(e,r,!1),this.failure("StringConcatenationError","runtime-error",t instanceof Error?t.message:"String concatenation failed","STRING_CONCATENATION_ERROR",["Check that operands can be converted to strings"])}}validate(e){const t=Ai.safeParse(e);return t.success?this.validationSuccess():this.validationFailure("type-mismatch",t.error?.errors.map(e=>e.message).join(", ")||"Invalid string concatenation input",["Provide left and right operands for concatenation"])}convertToString(e){if(null===e)return"null";if(void 0===e)return"undefined";if($e(e))return e;if(He(e))return""+e;if(qe(e))return""+e;if(e instanceof Date)return""+e;try{return e+""}catch{return"[object Object]"}}}const Ni={stringLiteral:new Si,numberLiteral:new Ti,booleanLiteral:new Li,stringConcatenation:new Oi};class Pi{constructor(){this.name="addition",this.category="Special",this.syntax="left + right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=Jt(r,"right operand");return{success:!0,value:Xt(n+s,"addition"),type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Addition failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){const t=function(e){if(null==e)return nr([sr("missing-argument","Input is null or undefined")],["Provide an object with left and right operands"]);if("object"!=typeof e)return nr([sr("type-mismatch","Expected object, got "+typeof e)],["Provide an object with left and right operands"]);const t=e;if(!("left"in t)||!("right"in t)){const e=[];return"left"in t||e.push("left"),"right"in t||e.push("right"),nr([sr("missing-argument",`Missing ${e.join(" and ")} operand${e.length>1?"s":""}`)],["Provide { left: value, right: value }"])}return{isValid:!0,errors:[],suggestions:[]}}(e);if(!t.isValid)return t;const{left:r,right:n}=e;return er(r)?er(n)?{isValid:!0,errors:[],suggestions:[]}:{isValid:!1,errors:[sr("type-mismatch","Right operand cannot be converted to number: "+(n+""))],suggestions:["Provide a numeric value for right operand"]}:{isValid:!1,errors:[sr("type-mismatch","Left operand cannot be converted to number: "+(r+""))],suggestions:["Provide a numeric value for left operand"]}}}class Ii{constructor(){this.name="subtraction",this.category="Special",this.syntax="left - right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=Jt(r,"right operand");return{success:!0,value:Xt(n-s,"subtraction"),type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Subtraction failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Pi).validate(e)}}class ji{constructor(){this.name="multiplication",this.category="Special",this.syntax="left * right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=Jt(r,"right operand");return{success:!0,value:Xt(n*s,"multiplication"),type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Multiplication failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Pi).validate(e)}}class Ri{constructor(){this.name="division",this.category="Special",this.syntax="left / right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=function(e,t,r=!0){if(0===t){if(r)return 0===e?NaN:e>0?1/0:-1/0;throw Error("Division by zero")}return e/t}(n,Jt(r,"right operand"),!0);return{success:!0,value:s,type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Division failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Pi).validate(e)}}class Mi{constructor(){this.name="modulo",this.category="Special",this.syntax="left mod right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=function(e,t){if(0===t)throw Error("Modulo by zero");return e%t}(n,Jt(r,"right operand"));return{success:!0,value:s,type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Modulo failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric and divisor is not zero"]}}}validate(e){return(new Pi).validate(e)}}class $i{constructor(){this.name="power",this.category="Special",this.syntax="left ** right",this.outputType="number",this.metadata={category:"Special",complexity:"simple"}}async evaluate(e,t){const r=this.validate(t);if(!r.isValid)return{success:!1,errors:r.errors,suggestions:r.suggestions};try{const{left:e,right:r}=t,n=Jt(e,"left operand"),s=Jt(r,"right operand");return{success:!0,value:Xt(Math.pow(n,s),"power"),type:"number"}}catch(e){return{success:!1,errors:[sr("runtime-error","Power failed: "+(e instanceof Error?e.message:e+""))],suggestions:["Ensure both operands are numeric"]}}}validate(e){return(new Pi).validate(e)}}const Hi={addition:new Pi,subtraction:new Ii,multiplication:new ji,division:new Ri,modulo:new Mi,power:new $i};const qi={name:"first",category:"Reference",evaluatesTo:"Any",operators:["first"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[0]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[0]:null;if(r instanceof Element)return r.children.length>0?r.children[0]:null;if($e(r)){return r.length>0?r[0]:null}if(We(r)&&"length"in r&&He(r.length)){return r.length>0?r[0]:null}return null},validate:e=>et(e,1,"first","collection")},Wi={name:"last",category:"Reference",evaluatesTo:"Any",operators:["last"],async evaluate(e,t){const r=void 0!==t?t:e.it;if(null==r)return null;if(Array.isArray(r))return r.length>0?r[r.length-1]:null;if(r instanceof NodeList||r instanceof HTMLCollection)return r.length>0?r[r.length-1]:null;if(r instanceof Element){const e=r.children;return e.length>0?e[e.length-1]:null}if($e(r)){return r.length>0?r[r.length-1]:null}if(We(r)&&"length"in r&&He(r.length)){return r.length>0?r[r.length-1]:null}return null},validate:e=>et(e,1,"last","collection")},Vi={name:"at",category:"Reference",evaluatesTo:"Any",operators:["at"],async evaluate(e,...t){const[r,n]=t;if(!He(r))throw Error("Index must be a number");const s=r,i=void 0!==n?n:e.it;if(null==i)return null;if(Array.isArray(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof NodeList||i instanceof HTMLCollection){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(i instanceof Element){const e=i.children,t=0>s?e.length+s:s;return t>=0&&e.length>t?e[t]:null}if($e(i)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}if(We(i)&&"length"in i&&He(i.length)){const e=0>s?i.length+s:s;return e>=0&&i.length>e?i[e]:null}return null},validate:e=>tt(e,1,2,"at","index, optional collection")??function(e,t,r,n){if("number"!=typeof e[t])return`${r} ${n} must be a number`;return null}(e,0,"at","index")};function Di(e,t){let r=e.nextElementSibling;for(;r;){if(r.matches(t))return r;const e=r.querySelector(t);if(e)return e;r=r.nextElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Di(n,t):null}function Bi(e,t){let r=e.previousElementSibling;for(;r;){const e=Array.from(r.querySelectorAll(t)).reverse();if(e.length>0)return e[0];if(r.matches(t))return r;r=r.previousElementSibling}const n=e.parentElement;return n&&n!==document.documentElement?Bi(n,t):null}const Fi=2,_i=4;function Ui(e,t,r,n){if(r.inSearch){if(null==r.inElt)return;return function(e,t,r,n){const s=Array.from(t??[]),i=[];for(const t of s)(t.matches&&t.matches(r)||t===e)&&i.push(t);for(let t=0;i.length-1>t;t++)if(i[t]===e)return i[t+1];if(n){const e=i[0];if(e&&e.matches&&e.matches(r))return e}}(e,n?Array.from(r.inElt):Array.from(r.inElt).reverse(),t,!!r.wrapping)}const s=r.within??("undefined"!=typeof document?document.body:null);if(s)return n?function(e,t,r,n){const s=t.querySelectorAll(r);for(let t=0;s.length>t;t++){const r=s[t];if(r.compareDocumentPosition(e)===Fi)return r}return n?s[0]:void 0}(e,s,t,!!r.wrapping):function(e,t,r,n){const s=t.querySelectorAll(r);for(let t=s.length-1;t>=0;t--){const r=s[t];if(r.compareDocumentPosition(e)===_i)return r}return n?s[s.length-1]:void 0}(e,s,t,!!r.wrapping)}function zi(e){let t=0,r=e;for(;r&&r.parentElement;){t+=Array.from(r.parentElement.children).indexOf(r),r=r.parentElement,t+=1e3}return t}const Ki={first:qi,last:Wi,at:Vi,next:{name:"next",category:"Reference",evaluatesTo:"Element",operators:["next"],async evaluate(e,...t){const[r,n,s]=t,i=n||e.me;return i&&i instanceof Element?r?s?Ui(i,r,s,!0):Di(i,r):i.nextElementSibling:null},validate(e){const t=et(e,3,"next","optional selector, optional fromElement, optional modifiers");return t||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[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(e,...t){const[r,n,s]=t,i=n||e.me;return i&&i instanceof Element?r?s?Ui(i,r,s,!1):Bi(i,r):i.previousElementSibling:null},validate(e){const t=et(e,3,"previous","optional selector, optional fromElement, optional modifiers");return t||(1>e.length||null==e[0]||"string"==typeof e[0]?2>e.length||null==e[1]||e[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(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=zi(e);for(const e of n){if(zi(e)>s)return e}return null}(i,r,a):null},validate(e){const t=tt(e,2,3,"nextWithin","selector, withinSelector, optional fromElement");return t||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}},previousWithin:{name:"previousWithin",category:"Reference",evaluatesTo:"Element",operators:["previous within"],async evaluate(e,...t){const[r,n,s]=t,i=s||e.me;if(!(i&&i instanceof Element))return null;const a=i.closest(n);return a?function(e,t,r){const n=Array.from(r.querySelectorAll(t)),s=zi(e);for(let e=n.length-1;e>=0;e--){const t=n[e];if(s>zi(t))return t}return null}(i,r,a):null},validate(e){const t=tt(e,2,3,"previousWithin","selector, withinSelector, optional fromElement");return t||("string"!=typeof e[0]?"selector must be a string":"string"!=typeof e[1]?"withinSelector must be a string":3>e.length||null==e[2]||e[2]instanceof Element?null:"fromElement must be an Element")}}};function Zi(){return wi(lt,Rr,ot,Ki,qr,Ni,Hi)}var Gi=Object.freeze({__proto__:null,conversion:ot,conversionExpressions:ot,createCommonRegistry:function(){return wi(lt,Rr,Ni,Hi,ot,Ki)},createCoreRegistry:function(){return wi(lt,Rr,Ni,Hi)},createExpressionRegistry:wi,createFullExpressionRegistry:Zi,createFullRegistry:function(){return wi(lt,Rr,Ni,Hi,ot,Ki,qr)},logical:Rr,logicalExpressions:Rr,mathematical:Hi,positional:Ki,positionalExpressions:Ki,properties:qr,propertiesExpressions:qr,references:lt,referencesExpressions:lt,special:Ni,specialExpressions:Ni});function Qi(e,t,r,n,s,i){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,c=n.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?n.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),m=!1,p=r.length-1;p>=0;p--){var h={};for(var f in n)h[f]="access"===f?{}:n[f];for(var f in n.access)h.access[f]=n.access[f];h.addInitializer=function(e){if(m)throw new TypeError("Cannot add initializers after decoration has completed");i.push(a(e||null))};var y=(0,r[p])("accessor"===c?{get:d.get,set:d.set}:d[l],h);if("accessor"===c){if(void 0===y)continue;if(null===y||"object"!=typeof y)throw new TypeError("Object expected");(o=a(y.get))&&(d.get=o),(o=a(y.set))&&(d.set=o),(o=a(y.init))&&s.unshift(o)}else(o=a(y))&&("field"===c?s.unshift(o):d[l]=o)}u&&Object.defineProperty(u,n.name,d),m=!0}function Ji(e,t,r){for(var n=arguments.length>2,s=0;t.length>s;s++)r=n?t[s].call(e,r):t[s].call(e);return n?r:void 0}function Yi(e,t,r){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:r?"".concat(r," ",t):t})}function Xi(e){return function(t,r){Object.defineProperty(t.prototype,"name",{value:e.name,writable:!1,enumerable:!0})}}function ea(e){return{...e}}function ta(e){return()=>new e}function ra(e,t){return e?`[${e}] ${t}`:t}function na(e,t,r){if(xe(e))return e;if(!e){const e=t.me;if(!e)throw Error(ra(r,"No target element \u2014 provide explicit target or ensure context.me is set"));return ia(e)}if("string"==typeof e){const n=e.trim();if("me"===n){if(!t.me)throw Error(ra(r,'Context reference "me" is not available'));return ia(t.me)}if("it"===n){if(!xe(t.it))throw Error(ra(r,'Context reference "it" is not an HTMLElement'));return t.it}if("you"===n){if(!t.you)throw Error(ra(r,'Context reference "you" is not available'));return ia(t.you)}const s=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!s)throw Error(ra(r,"DOM not available \u2014 cannot resolve element selector"));const i=s.querySelector(n);if(!i)throw Error(ra(r,"Element not found with selector: "+n));if(!xe(i))throw Error(ra(r,"Element found but is not an HTMLElement: "+n));return i}throw Error(ra(r,"Invalid target type: "+typeof e))}function sa(e,t){if(Array.isArray(e))return e.filter(xe);if(Ae(e))return Array.from(e).filter(xe);if(xe(e))return[e];if(!e){const e=t.me;return e&&xe(e)?[e]:[]}if("string"==typeof e){const r=e.trim();if("me"===r)return t.me&&xe(t.me)?[t.me]:[];if("it"===r)return xe(t.it)?[t.it]:[];if("you"===r)return t.you&&xe(t.you)?[t.you]:[];const n=t.me?.ownerDocument??("undefined"!=typeof document?document:null);if(n){let e=r;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=n.querySelectorAll(e);return Array.from(t).filter(xe)}}return[]}function ia(e){if(xe(e))return e;throw Error("Value is not an HTMLElement")}function aa(e,t,r){switch(e.toLowerCase()){case"my":case"me":if(!t.me)throw Error(ra(r,'No "me" element in context'));if(!xe(t.me))throw Error(ra(r,"context.me is not an HTMLElement"));return t.me;case"its":case"it":if(!t.it)throw Error(ra(r,'No "it" value in context'));if(!xe(t.it))throw Error(ra(r,"context.it is not an HTMLElement"));return t.it;case"your":case"you":if(!t.you)throw Error(ra(r,'No "you" element in context'));if(!xe(t.you))throw Error(ra(r,"context.you is not an HTMLElement"));return t.you;default:throw Error(ra(r,"Unknown possessive: "+e))}}async function oa(e,t,r,n,s={},i){let a=e;if((!a||0===a.length)&&s.fallbackModifierKey&&i){const e=i[s.fallbackModifierKey];e&&(a=[e])}if(!a||0===a.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!xe(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}const o=[];for(const e of a){const s=await t.evaluate(e,r);if(""!==s&&("string"!=typeof s||""!==s.trim()))if(xe(s))o.push(s);else if(Ae(s)){const e=Array.from(s).filter(xe);o.push(...e)}else if(Array.isArray(s)){const e=s.filter(xe);o.push(...e)}else{if("string"!=typeof s){if(null==s)continue;throw Error(`Invalid ${n} target: expected HTMLElement or CSS selector, got ${typeof s}`)}try{let e=s;e.startsWith("<")&&e.endsWith("/>")&&(e=e.slice(1,-2).trim());const t=r.me?.ownerDocument??("undefined"!=typeof document?document:null);if(!t)throw Error("DOM not available - cannot resolve element selector");const n=t.querySelectorAll(e),i=Array.from(n).filter(xe);o.push(...i)}catch(e){throw Error(`Invalid CSS selector: "${s}" - ${e instanceof Error?e.message:e+""}`)}}}if(0===o.length){if(!r.me)throw Error(n+" command: no target specified and context.me is null");if(!xe(r.me))throw Error(n+" command: context.me must be an HTMLElement");return[r.me]}return o}"function"==typeof SuppressedError&&SuppressedError;class ca{constructor(){this.ownsConditionalModifier=!0}async parseInput(e,t,r){const{targets:n}=await async function(e,t,r,n){return{targets:await oa(e.args,t,r,n)}}(e,t,r,this.mode),s=e.modifiers?.when??e.modifiers?.where,{matched:i,unmatched:a}=s?await async function(e,t,r,n){const s=[],i=[],a=n.it;try{for(const a of e)n.it=a,(await r.evaluate(t,n)?s:i).push(a)}finally{n.it=a}return{matched:s,unmatched:i}}(n,s,t,r):{matched:n,unmatched:void 0};return{targets:i,...void 0!==a&&{inverse:a},mode:this.mode,defaultDisplay:"show"===this.mode?"block":void 0}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&(!!t.targets.every(e=>xe(e))&&(("show"===t.mode||"hide"===t.mode)&&("show"!==t.mode||"string"==typeof t.defaultDisplay)))}showElement(e,t="block"){const r=e.dataset.originalDisplay;void 0!==r?(e.style.display=r||t,delete e.dataset.originalDisplay):"none"===e.style.display&&(e.style.display=t),e.classList.add("show")}hideElement(e){if(!e.dataset.originalDisplay){const t=e.style.display;e.dataset.originalDisplay="none"===t?"":t}e.style.display="none",e.classList.remove("show")}}const la=ta((()=>{let e,t,r=[Xi({name:"hide"})],n=[],s=ca;var i=t=class extends s{constructor(){super(...arguments),this.mode="hide"}get metadata(){return i.metadata}async execute(e,t){for(const t of e.targets)this.hideElement(t);for(const t of e.inverse??[])this.showElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&!!t.targets.every(e=>xe(e))}};return Yi(t,"HideCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Hide elements by setting display to none",syntax:"hide [<target>] [when <condition>]",examples:["hide me","hide #modal","hide .warnings","hide <button/>","hide <li/> when its textContent is empty"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),i=t})());const ua=ta((()=>{let e,t,r=[Xi({name:"show"})],n=[],s=ca;var i=t=class extends s{constructor(){super(...arguments),this.mode="show"}get metadata(){return i.metadata}async execute(e,t){const r=e.defaultDisplay||"block";for(const t of e.targets)this.showElement(t,r);for(const t of e.inverse??[])this.hideElement(t)}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&(!!t.targets.every(e=>xe(e))&&"string"==typeof t.defaultDisplay)}};return Yi(t,"ShowCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Show elements by restoring display property",syntax:"show [<target>] [when <condition>]",examples:["show me","show #modal","show .hidden","show <button/>","show <li/> when its textContent contains my value"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),i=t})());function da(e){const t=e.trim();return!(!t.startsWith("[@")||!t.endsWith("]"))||!!t.startsWith("@")}function ma(e){const t=e.trim();if(t.startsWith("[@")&&t.endsWith("]")){const e=t.slice(2,-1),r=e.indexOf("=");if(-1===r)return{name:e.trim()};const n=e.slice(0,r).trim();let s=e.slice(r+1).trim();return(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),{name:n,value:s}}if(t.startsWith("@"))return{name:t.substring(1).trim()};throw Error("Invalid attribute syntax: "+e)}function pa(e,t){for(const r of e)t(r);return e}function ha(e,t,r){for(const n of e)for(const e of t)r(n,e);return e}function fa(e,t,r){const n=e.hasAttribute(t);void 0!==r?n&&e.getAttribute(t)===r?e.removeAttribute(t):e.setAttribute(t,r):n?e.removeAttribute(t):e.setAttribute(t,"")}function ya(e){if(!e)return[];if("string"==typeof e)return e.trim().split(/[\s,]+/).map(e=>{const t=e.trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&va(e));if(Array.isArray(e))return e.map(e=>{const t=(e+"").trim();return t.startsWith(".")?t.substring(1):t}).filter(e=>e.length>0&&va(e));const t=(e+"").trim(),r=t.startsWith(".")?t.substring(1):t;return r.length>0&&va(r)?[r]:[]}function ga(e){const t=e.trim();return/^\{[^}]+\}$/.test(t)}function va(e){if(!e||0===e.trim().length)return!1;const t=e.trim();if(ga(t))return!0;return/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t)}function ba(e,t){return e.map(e=>{if(ga(e)){const r=function(e){const t=e.trim(),r=t.match(/^\{(.+)\}$/);return r?r[1].trim():t}(e),n=t.locals.get(r)??t.globals.get(r);return null!=n?n+"":""}return e}).filter(e=>e.length>0)}function wa(e){return"string"==typeof e&&e.trim().startsWith("*")}function Ea(e){const t=function(e){const t=e.trim();if(!t.startsWith("*"))return null;const r=t.substring(1).trim();return r?{property:r}:null}(e);if(!t)return null;const r=t.property.toLowerCase();return["display","visibility","opacity"].includes(r)?r:null}function ka(e,t,r){e.style.setProperty(t,r)}const xa=["dialog","details","summary","select"];function Ca(e){if(!e||"object"!=typeof e)return null;return"string"==typeof e.selector?e.selector:"string"==typeof e.value?e.value:"string"==typeof e.name?e.name:null}function Aa(e){if(!e||"object"!=typeof e)return!1;if("identifier"!==e.type)return!1;const t=e.name;return"string"==typeof t&&function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return xa.includes(t)}(t)}async function Sa(e,t,r){return function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"classSelector"!==t)return!1;const r=Ca(e);return"string"==typeof r&&r.startsWith(".")}(e)||function(e){if(!e||"object"!=typeof e)return!1;const t=e.type;if("selector"!==t&&"cssSelector"!==t&&"cssProperty"!==t)return!1;const r=Ca(e);return"string"==typeof r&&r.startsWith("*")}(e)?{value:Ca(e),extractedFromNode:!0}:function(e){if(!e||"object"!=typeof e)return!1;if("attributeAccess"===e.type)return!0;if("selector"===e.type||"cssSelector"===e.type){const t=Ca(e);return"string"==typeof t&&t.startsWith("@")}return!1}(e)?{value:(n=e,"attributeAccess"===n.type?"@"+n.attributeName:Ca(n)),extractedFromNode:!0}:{value:await t.evaluate(e,r),extractedFromNode:!1};var n}class Ta{async resolveTargets(e,t,r){const n=r?.[this.preposition];return oa(n?[n]:[],e,t,this.mode)}async evaluateFirst(e,t,r){return Sa(e,t,r)}parseClassNames(e){return ya(e)}isAttribute(e){return da(e.trim())}isCSSProperty(e){return wa(e.trim())}validateTargets(e){return Array.isArray(e)&&function(e){return Array.isArray(e)&&e.length>0&&e.every(e=>xe(e))}(e)}validateType(e,t){return function(e,t){return"string"==typeof e&&t.includes(e)}(e,t)}validateStringArray(e,t=1){return Array.isArray(e)&&function(e,t=1){return Array.isArray(e)&&e.length>=t&&e.every(e=>"string"==typeof e&&e.length>0)}(e,t)}}let La=(()=>{let e,t,r=[Xi({name:"add"})],n=[],s=Ta;var i=t=class extends s{constructor(){super(...arguments),this.mode="add",this.preposition="to"}get metadata(){return i.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("add command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if("object"==typeof n&&null!==n&&!Array.isArray(n)){return{type:"styles",styles:n,targets:await this.resolveTargets(t,r,e.modifiers)}}if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){const{name:n,value:i}=function(e){const t=ma(e);return{name:t.name,value:t.value??""}}(s);return{type:"attribute",name:n,value:i,targets:await this.resolveTargets(t,r,e.modifiers)}}if(this.isCSSProperty(s)){const n=s.substring(1).trim(),i=e.args[1];if(!i)throw Error("add *property requires a value argument");const a=await t.evaluate(i,r);return{type:"styles",styles:{[n]:a+""},targets:await this.resolveTargets(t,r,e.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("add command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t,r,e.modifiers)}}async execute(e,t){switch(e.type){case"classes":{const r=ba(e.classes,t);r.length>0&&ha(e.targets,r,(e,t)=>{e.classList.contains(t)||e.classList.add(t)});break}case"attribute":!function(e,t,r){pa(e,e=>{e.setAttribute(t,r)})}(e.targets,e.name,e.value);break;case"styles":!function(e,t){ha(e,Object.entries(t),(e,[t,r])=>{e.style.setProperty(t,r)})}(e.targets,e.styles)}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1;if("string"!=typeof e.value)return!1}else if("styles"===t.type){const t=e;if("object"!=typeof t.styles||null===t.styles)return!1;if(Array.isArray(t.styles))return!1;const r=t.styles;if(0===Object.keys(r).length)return!1;if(!Object.values(r).every(e=>"string"==typeof e))return!1}return!0}};return Yi(t,"AddCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Add CSS classes, attributes, or styles to elements",syntax:"add <classes|@attr|{styles}> [to <target>]",examples:["add .active to me",'add "active selected" to <button/>',"add .highlighted to #modal",'add [@data-test="value"] to #element'],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),i=t})();const Oa=ta(La),Na={before:"beforebegin",prepend:"afterbegin",append:"beforeend",after:"afterend",into:"replace"};function Pa(e){const t=Na[e];if(void 0===t)throw Error(`Unknown semantic position '${e}'. Valid positions: ${Object.keys(Na).join(", ")}.`);return t}function Ia(e){return e.includes("<")&&e.includes(">")}function ja(e,t,r){"replace"!==r?Ce(t)?function(e,t,r){switch(r){case"beforebegin":e.parentElement?.insertBefore(t,e);break;case"afterbegin":e.insertBefore(t,e.firstChild);break;case"beforeend":e.appendChild(t);break;case"afterend":e.parentElement?.insertBefore(t,e.nextSibling)}}(e,t,r):function(e,t,r){const n=r,s=["beforebegin","afterbegin","beforeend","afterend"];if(!s.includes(n))throw Error(`Invalid insert position '${r}'. Expected one of ${s.join(", ")} (or 'replace').`);Ia(t)?e.insertAdjacentHTML(n,t):e.insertAdjacentText(n,t)}(e,t,r):function(e,t){Ce(t)?(e.innerHTML="",e.appendChild(t)):Ia(t)?e.innerHTML=t:e.textContent=t}(e,t)}function Ra(e,t,r){ja(e,t,Pa(r))}function Ma(e,t,r){const n=e;if("function"==typeof n.moveBefore&&t.isConnected&&e.isConnected)try{return void n.moveBefore(t,r)}catch{}e.insertBefore(t,r)}function $a(e,t,r){switch(r){case"beforeend":for(const r of t)Ma(e,r,null);break;case"afterbegin":for(let r=t.length-1;r>=0;r--)Ma(e,t[r],e.firstChild);break;case"beforebegin":{const r=e.parentElement;if(!r)return;for(const n of t)Ma(r,n,e);break}case"afterend":{const r=e.parentElement;if(!r)return;for(let n=t.length-1;n>=0;n--)Ma(r,t[n],e.nextSibling);break}case"replace":e.innerHTML="";for(const r of t)Ma(e,r,null)}}function Ha(e){return!!e.parentNode&&(e.remove(),!0)}const qa=ta((()=>{let e,t,r=[Xi({name:"remove"})],n=[],s=Ta;var i=t=class extends s{constructor(){super(...arguments),this.mode="remove",this.preposition="from"}get metadata(){return i.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("remove command requires an argument");const{value:n}=await this.evaluateFirst(e.args[0],t,r);if(xe(n))return{type:"element",targets:[n]};if(Array.isArray(n)&&n.length>0&&xe(n[0]))return{type:"element",targets:n.filter(e=>xe(e))};if("string"==typeof n){const s=n.trim();if(this.isAttribute(s)){return{type:"attribute",name:ma(s).name,targets:await this.resolveTargets(t,r,e.modifiers)}}if(this.isCSSProperty(s)){return{type:"styles",properties:[s.substring(1).trim()],targets:await this.resolveTargets(t,r,e.modifiers)}}}const s=this.parseClassNames(n);if(0===s.length)throw Error("remove command: no valid class names found");return{type:"classes",classes:s,targets:await this.resolveTargets(t,r,e.modifiers)}}execute(e,t){switch(e.type){case"classes":{const r=ba(e.classes,t);r.length>0&&ha(e.targets,r,(e,t)=>{e.classList.remove(t)});break}case"attribute":!function(e,t){pa(e,e=>{e.removeAttribute(t)})}(e.targets,e.name);break;case"styles":!function(e,t){ha(e,t,(e,t)=>{e.style.removeProperty(t)})}(e.targets,e.properties);break;case"element":for(const t of e.targets)Ha(t)}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;if(!this.validateType(t.type,["classes","attribute","styles","element"]))return!1;if(!this.validateTargets(t.targets))return!1;if("classes"===t.type){if(!this.validateStringArray(e.classes,1))return!1}else if("attribute"===t.type){if("string"!=typeof e.name||0===e.name.length)return!1}else if("styles"===t.type){if(!this.validateStringArray(e.properties,1))return!1}return!0}};return Yi(t,"RemoveCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Remove CSS classes, attributes, styles, or elements from the DOM",syntax:"remove <classes|@attr|*prop|element> [from <target>]",examples:["remove .active from me",'remove "active selected" from <button/>',"remove .highlighted from #modal","remove me","remove closest .item"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),i=t})());function Wa(e){const t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|ms|sec|seconds?|milliseconds?)?$/i);if(!t)return null;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();return"ms"===n||"millisecond"===n||"milliseconds"===n?{number:r,milliseconds:Math.floor(r)}:"s"===n||"sec"===n||"second"===n||"seconds"===n?{number:r,milliseconds:Math.floor(1e3*r)}:null}function Va(e,t=300){if("number"==typeof e)return Math.max(0,Math.floor(e));if("string"==typeof e){const r=Wa(e);return r?r.milliseconds:t}return t}function Da(e){if("number"==typeof e){if(0>e)throw Error("Duration must be >= 0");return Math.floor(e)}if("string"==typeof e){const t=Wa(e);if(!t)throw Error(`Invalid duration format: "${e}"`);return t.milliseconds}throw Error("Invalid duration type: "+typeof e)}function Ba(e){return e&&"none"!==e?e.split(",").map(e=>{const t=parseFloat(e.trim());return isNaN(t)?0:e.includes("s")&&!e.includes("ms")?1e3*t:t}):[0]}function Fa(e,t){let r=0;for(let n=0;e.length>n;n++){r=Math.max(r,(e[n]||0)+(t[n]||0))}return r}function _a(e){if(0===e.length)return[];return"SUMMARY"===e[0].tagName?e.map(e=>e.closest("details")).filter(e=>null!==e):e}function Ua(e){return"DIALOG"===e.tagName}function za(e){return"DETAILS"===e.tagName}function Ka(e,t,r){return()=>{"class"===t?e.classList.toggle(r):"attribute"===t&&fa(e,r)}}function Za(e,t,r,n){const s=Ka(e,t,r),i=setTimeout(s,n);return()=>{clearTimeout(i)}}function Ga(e,t,r,n){const s=Ka(e,t,r),i=()=>{s(),e.removeEventListener(n,i)};return e.addEventListener(n,i,{once:!0}),()=>{e.removeEventListener(n,i)}}function Qa(e,t,r){if(t.startsWith("@")){const n=t.substring(1);return void(!1===r?e.removeAttribute(n):e.setAttribute(n,!0===r?"":r+""))}const n=r+"";switch(t){case"textContent":return void(e.textContent=n);case"innerHTML":return void(e.innerHTML=n);case"innerText":return void(e.innerText=n);case"id":return void(e.id=n);case"className":return void(e.className=n);case"value":return void("value"in e&&(e.value=n));case"checked":return void("checked"in e&&(e.checked=!!r))}if(t.includes(".")){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++)if(s=s[n[e]],null==s)return;return void(s[n[n.length-1]]=r)}if(t.includes("-")||t in e.style)e.style.setProperty(t,n);else try{e[t]=r}catch(e){if(!(e instanceof TypeError&&(e.message.includes("only a getter")||e.message.includes("read only"))))throw Error(`Cannot set property '${t}': ${e instanceof Error?e.message:"Unknown error"}`)}}function Ja(e){return null==e||""===e}function Ya(e,t){return function(e){return!!e&&"object"==typeof e&&"string"==typeof e.type}(e)&&e.type===t}function Xa(e){return Ya(e,"literal")}const eo=/^the\s+(.+?)\s+of\s+(.+)$/i,to=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"]),ro=function(e){if(!Ya(e,"propertyOfExpression"))return!1;const t=e.property;return"object"==typeof t&&null!==t},no=function(e){if(!Ya(e,"propertyAccess"))return!1;const t=e.property;return"string"==typeof t||"object"==typeof t&&null!==t&&"string"==typeof t.name};function so(e){return"string"==typeof e&&eo.test(e)}function io(e,t){const r=e.match(eo);if(!r)return null;try{return{element:na(r[2].trim(),t),property:r[1].trim()}}catch{return null}}async function ao(e,t,r){if(ro(e))return async function(e,t,r){const n=e.property?.name;if(!n)return null;let s=await t.evaluate(e.target,r);return Array.isArray(s)&&(s=s[0]),xe(s)?{element:s,property:n}:null}(e,t,r);if(no(e))return async function(e,t,r){const n="string"==typeof e.property?e.property:e.property?.name;if(!n)return null;let s=await t.evaluate(e.object,r);return Array.isArray(s)&&(s=s[0]),xe(s)?{element:s,property:n}:null}(e,t,r);const n=e;if("possessiveExpression"===n?.type||"memberExpression"===n?.type){const e=n.object,s=n.property;let i=await t.evaluate(e,r);if(Array.isArray(i)&&(i=i[0]),!xe(i))return null;const a=s?.name||s?.value;return a?{element:i,property:a}:null}return null}function oo(e){const{element:t,property:r}=e;if(r.startsWith("*")){return function(e,t){return window.getComputedStyle(e).getPropertyValue(t)}(t,r.substring(1))}return Ke(t,r)}function co(e,t){const{element:r,property:n}=e;if(n.startsWith("*")){return void ka(r,n.substring(1),t+"")}Qa(r,n,t)}async function lo(e,t,r){let n,s;if(e?.for){const s=await t.evaluate(e.for,r);n="number"==typeof s?s:"string"==typeof s?Va(s):void 0}if(e?.until){const n=await t.evaluate(e.until,r);"string"==typeof n&&(s=n)}return{duration:n,untilEvent:s}}function uo(e,t){const r=t?.name,n=Aa(t);if(xe(e)||Array.isArray(e)&&e.every(e=>xe(e)))return{type:"element",expression:""};if(n&&r)return{type:"element",expression:r};if("string"==typeof e){const t=e.trim();return t.startsWith("@")||t.startsWith("[@")?{type:"attribute",expression:t}:t.startsWith("*")?{type:"css-property",expression:t}:t.startsWith(".")?{type:"class",expression:t}:t.startsWith("#")||function(e){if("string"!=typeof e)return!1;const t=e.toLowerCase();return xa.some(e=>t.includes(e))}(t)?{type:"element",expression:t}:{type:"class",expression:t}}return{type:"class",expression:""}}const mo=ta((()=>{let e,t,r=[Xi({name:"toggle"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.modifiers?.between;if(Ya(n,"arrayLiteral")&&n.elements.length>=2){const{duration:s,untilEvent:i}=await lo(e.modifiers,t,r),a=async e=>Ya(e,"selector")?e.value:t.evaluate(e,r);return{type:"classes-between",classA:(await a(n.elements[0])+"").replace(/^\./,""),classB:(await a(n.elements[1])+"").replace(/^\./,""),targets:await oa([],t,r,"toggle",{fallbackModifierKey:"on"},e.modifiers),duration:s,untilEvent:i}}if(!e.args?.length)throw Error("toggle command requires an argument");const s=e.args[0],i=await ao(s,t,r);if(i)return{type:"property",target:i};if("selector"===s.type&&"string"==typeof s.value&&s.value.startsWith("*")){let n=s.value,i=1;if("*"===n&&"identifier"===e.args[1]?.type&&(n="*"+e.args[1].name,i=2),"*"===n&&e.modifiers?.on){const s=e.modifiers.on?.name;if(s&&["display","visibility","opacity"].includes(s)){n="*"+s;const{duration:i,untilEvent:a}=await lo(e.modifiers,t,r),o=Ea(n);if(o){const e=r.me;return{type:"css-property",property:o,targets:e?[e]:[],duration:i,untilEvent:a}}}}const a=Ea(n);if(a){const{duration:n,untilEvent:s}=await lo(e.modifiers,t,r),o={fallbackModifierKey:"on"};return{type:"css-property",property:a,targets:await oa(e.args.slice(i),t,r,"toggle",o,e.modifiers),duration:n,untilEvent:s}}}const{duration:a,untilEvent:o}=await lo(e.modifiers,t,r),{value:c}=await Sa(s,t,r);if(so(c)){const e=io(c,r);if(e)return{type:"property",target:e}}const{type:l,expression:u}=uo(c,s),d={fallbackModifierKey:"on"};switch(l){case"attribute":{const{name:n,value:s}=ma(u);return{type:"attribute",name:n,value:s,targets:await oa(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}case"css-property":{const n=Ea(u);if(!n)throw Error("Invalid CSS property: "+u);return{type:"css-property",property:n,targets:await oa(e.args.slice(1),t,r,"toggle",d,e.modifiers)}}case"element":{let n;if(xe(c))n=[c];else if(Array.isArray(c)&&c.every(e=>xe(e)))n=c;else if(u){const e=document.querySelectorAll(u);n=Array.from(e).filter(e=>xe(e))}else n=await oa([s],t,r,"toggle",d,e.modifiers);const i=function(e){if(0===e.length)return null;const t=e[0].tagName;if(!e.every(e=>e.tagName===t))return null;switch(t){case"DIALOG":return"dialog";case"DETAILS":return"details";case"SELECT":return"select";case"SUMMARY":return e.map(e=>e.closest("details")).filter(e=>null!==e).length>0?"details":null;default:return null}}(n);if("dialog"===i){const s=await async function(e,t,r){if(!e?.as)return"non-modal";const n=await t.evaluate(e.as,r);return"string"==typeof n&&"modal"===n.toLowerCase()?"modal":"non-modal"}(e.modifiers,t,r);return{type:"dialog",mode:s,targets:n}}if("details"===i)return{type:"details",targets:_a(n)};if("select"===i)return{type:"select",targets:n};return{type:"classes",classes:ya(u),targets:n,duration:a,untilEvent:o}}default:{const n=ya(u||c);if(!n.length)throw Error("toggle command: no valid class names found");return{type:"classes",classes:n,targets:await oa(e.args.slice(1),t,r,"toggle",d,e.modifiers),duration:a,untilEvent:o}}}}async execute(e,t){switch(e.type){case"classes":{const r=ba(e.classes,t);if(0===r.length)return[...e.targets];if(ha(e.targets,r,(e,t)=>{e.classList.toggle(t)}),(e.duration||e.untilEvent)&&r.length)for(const t of e.targets)e.duration&&Za(t,"class",r[0],e.duration),e.untilEvent&&Ga(t,"class",r[0],e.untilEvent);return[...e.targets]}case"attribute":if(function(e,t,r){pa(e,e=>{fa(e,t,r)})}(e.targets,e.name,e.value),e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Za(t,"attribute",e.name,e.duration),e.untilEvent&&Ga(t,"attribute",e.name,e.untilEvent);return[...e.targets];case"css-property":return pa(e.targets,t=>function(e,t){const r=window.getComputedStyle(e);switch(t){case"display":"none"===r.display?(e.style.display=e.dataset.previousDisplay||"block",delete e.dataset.previousDisplay):(e.dataset.previousDisplay=r.display,e.style.display="none");break;case"visibility":e.style.visibility="hidden"===r.visibility?"visible":"hidden";break;case"opacity":e.style.opacity=0===parseFloat(r.opacity)?"1":"0"}}(t,e.property));case"property":return function(e){const t=oo(e),r=e.property,n=r.startsWith("@")?r.substring(1):r;if("boolean"==typeof t||to.has(n)||to.has(n.toLowerCase())){const r=!t;return co(e,r),r}if("number"==typeof t){const r=0===t?1:0;return co(e,r),r}if("string"==typeof t){const n="__ht_"+r,s=e.element[n];return""===t&&void 0!==s?(co(e,s),s):(e.element[n]=t,co(e,""),"")}const s=!t;co(e,s)}(e.target),[e.target.element];case"dialog":return pa(e.targets,t=>{return n=e.mode,void((r=t).open?r.close():"modal"===n?r.showModal():r.show());var r,n});case"details":return pa(e.targets,e=>{var t;(t=e).open=!t.open});case"select":return pa(e.targets,e=>function(e){if(document.activeElement===e)e.blur();else{if(e.focus(),"showPicker"in e&&"function"==typeof e.showPicker)try{return void e.showPicker()}catch{}const t=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!0});e.dispatchEvent(t)}}(e));case"classes-between":for(const t of e.targets){const r=t.classList.contains(e.classA),n=t.classList.contains(e.classB);r?(t.classList.remove(e.classA),t.classList.add(e.classB)):n?(t.classList.remove(e.classB),t.classList.add(e.classA)):t.classList.add(e.classA)}if(e.duration||e.untilEvent)for(const t of e.targets)e.duration&&Za(t,"class",e.classA,e.duration),e.untilEvent&&Ga(t,"class",e.classA,e.untilEvent);return[...e.targets]}}};return Yi(t,"ToggleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({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","toggle between .expanded and .collapsed","toggle .loading until click from #done"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());let po=(()=>{let e,t,r=[Xi({name:"put"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args?.length)throw Error("put requires arguments");const n=["into","before","after","at","at start of","at end of"].find(t=>e.modifiers?.[t]);let s=e.args[0]??null,i=null,a=null;if(n)i=n,a=e.modifiers[n];else{if(!e.args[1])throw Error("put requires content and position");i="into",a=e.args[1]}if(!s)throw Error("put requires content");if(!i)throw Error("put requires position keyword");const o=await t.evaluate(s,r),c=this.mapPosition(i);let l,u,d=null;if(a){const e=(m=a,m?.type||"unknown"),n=await ao(a,t,r);if(n)return{value:o,targets:[n.element],position:"into",memberPath:n.property};if("memberExpression"===e){const e=a.object,n=a.property;if("selector"===e?.type)d=e.value;else if("identifier"===e?.type){const s=e.name;if("my"===s||"me"===s||"I"===s){if(r.me&&n?.name)return{value:o,targets:[r.me],position:"into",memberPath:n.name}}else if("its"===s||"it"===s){const e=await t.evaluate(a,r);"string"==typeof e&&(d=e)}else d=s}if(d&&n?.name)l=n.name;else if(!d&&!l){const e=await t.evaluate(a,r);"string"==typeof e&&(d=e)}}else if("identifier"===e&&"me"===a.name)d=null;else if("selector"===e||"cssSelector"===e)d=a.value||a.selector;else if("literal"===e){const e=a.value;if("string"==typeof e&&so(e)){const t=io(e,r);if(t)return{value:o,targets:[t.element],position:"into",memberPath:t.property}}"string"==typeof e&&this.looksLikeCss(e)?d=e:u=e+""}else if("identifier"===e){const e=a.name;if(this.looksLikeCss(e))d=e;else{const n=Re(await t.evaluate(a,r));if(n)return{value:o,targets:n,position:c,memberPath:l};u=e}}else{const e=await t.evaluate(a,r),n=Re(e);if(n)return{value:o,targets:n,position:c,memberPath:l};"string"==typeof e&&(this.looksLikeCss(e)?d=e:u=e)}}var m;if(u)return{value:o,targets:[],position:c,memberPath:l,variableName:u};return{value:o,targets:await this.resolveTargets(d,r),position:c,memberPath:l}}async execute(e,t){const{value:r,targets:n,position:s,memberPath:i,variableName:a}=e;if(a)return t.locals&&t.locals.set(a,r),t[a]=r,void Object.assign(t,{it:r});if(i)for(const e of n)this.setProperty(e,i,r);else for(const e of n){const t=this.parseValue(r);Array.isArray(t)?$a(e,t,Pa(s)):Ra(e,t,s)}return n}mapPosition(e){switch(e){case"into":return"into";case"before":return"before";case"after":return"after";case"at start of":return"prepend";case"at end of":return"append";default:throw Error("Invalid position: "+e)}}async resolveTargets(e,t){if(!e||"me"===e){if(!t.me||!xe(t.me))throw Error("put: no target and context.me is null");return[t.me]}return je(e)}parseValue(e){return xe(e)||Array.isArray(e)&&e.length>0&&e.every(xe)||Ce(e)?e:null==e?"":e+""}looksLikeCss(e){if(!e)return!1;if(/^[#.\[]/.test(e))return!0;if(/[>+~\s]/.test(e)&&e.length>1)return!0;return["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(e.toLowerCase())}setProperty(e,t,r){const n=t.split(".");let s=e;for(let e=0;n.length-1>e;e++){if(!s[n[e]])throw Error(`Property path "${t}" does not exist`);s=s[n[e]]}s[n[n.length-1]]=r}};return Yi(t,"PutCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Insert content into elements or properties",syntax:["put <value> into <target>","put <value> before <target>","put <value> after <target>"],examples:['put "Hello World" into me',"put <div>Content</div> before #target","put value into #elem's innerHTML"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})();const ho=ta(po),fo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function yo(e){return e.replace(/[&<>"']/g,e=>fo[e])}let go=(()=>{let e,t,r=[Xi({name:"make"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.modifiers.an??e.modifiers.a??e.args[0];if(!n)throw Error("Make command requires class name or DOM element expression");const s=n.raw;let i="string"==typeof s&&s.startsWith("<")?s:await t.evaluate(n,r);if(null==i)throw Error("Make command requires class name or DOM element expression");"string"==typeof i&&i.startsWith("<")&&(i=await async function(e,t){if(!e.includes("{"))return e;const r=/\{([^{}]+)\}/g,n=[];let s;for(;null!==(s=r.exec(e));){let e=s[0];try{const r=await Hs(s[1].trim(),t);null!=r&&(e=yo(r+""))}catch{}n.push({index:s.index,length:s[0].length,text:e})}let i=e;for(let e=n.length-1;e>=0;e--){const{index:t,length:r,text:s}=n[e];i=i.slice(0,t)+s+i.slice(t+r)}return i}(i,r));const a=void 0!==e.modifiers.an?"an":"a",o=await async function(e,t,r){if(!e)return[];if("arrayLiteral"===e.type&&Array.isArray(e.args)){const n=[];for(const s of e.args)n.push(await t.evaluate(s,r));return n}const n=await t.evaluate(e,r);return Array.isArray(n)?n:[n]}(e.modifiers.from,t,r),c=await async function(e,t,r){if(!e)return;if(("symbol"===e.type||"identifier"===e.type)&&"string"==typeof e.name)return e.name;const n=await t.evaluate(e,r);return"string"==typeof n?n:void 0}(e.modifiers.called,t,r);return{article:a,expression:i,constructorArgs:o,variableName:c}}async execute(e,t){const{expression:r,constructorArgs:n=[],variableName:s}=e,i="string"==typeof r&&r.startsWith("<"),a=i&&r.endsWith("/>")?function(e){const t=e.slice(1,-2);let r="div",n=t;const s=t.match(/^([a-zA-Z][a-zA-Z0-9]*)/);s&&(r=s[1],n=t.slice(s[0].length));const i=document.createElement(r),a=n.split(/(?=[.#])/);for(const e of a)if(e.startsWith("#")){const t=e.slice(1);t&&(i.id=t)}else if(e.startsWith(".")){const t=e.slice(1);t&&i.classList.add(t)}return i}(r):i&&/<\/[a-zA-Z]/.test(r)?function(e){const t=document.createElement("template");t.innerHTML=e.trim();const r=t.content.firstElementChild;if(r&&xe(r))return r;const n=document.createElement("div");n.innerHTML=e.trim();const s=n.firstElementChild;return s&&xe(s)?s:n}(r):function(e,t,r){if(xe(e))return e;if("function"==typeof e){const r=e;return 0===t.length?new r:new r(...t)}const n=e+"";let s;if("undefined"!=typeof window&&(s=window[n]),s||"undefined"==typeof global||(s=global[n]),!s&&r.variables?.has(n)&&(s=r.variables.get(n)),!s||"function"!=typeof s)throw Error(`Constructor '${n}' not found or is not a function`);return 0===t.length?new s:new s(...t)}(r,n,t);return Object.assign(t,{it:a}),s&&Le(s,a,t),a}};return Yi(t,"MakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Create DOM elements or class instances",syntax:["make a <tag#id.class1.class2/>","make a <ClassName> from <args> called <identifier>"],examples:["make an <a.navlink/> called linkElement",'make a URL from "/path/", "https://origin.example.com"'],sideEffects:["dom-creation","data-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})();const vo=ta(go);const bo=ta((()=>{let e,t,r=[Xi({name:"empty"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:await oa(e.args,t,r,"empty",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.innerHTML=""}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"EmptyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Remove all children from an element (sets innerHTML to empty)",syntax:["empty","empty <target>","empty the <target>"],examples:["empty me","empty #list","empty .results"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());function wo(e){if("string"!=typeof e)return;const t=e.toLowerCase().trim();return"non-modal"===t||"nonmodal"===t?"non-modal":"modal"===t?"modal":void 0}function Eo(e){return e.hasAttribute("popover")}const ko=ta((()=>{let e,t,r=[Xi({name:"open"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=(e.args??[]).filter(e=>{const t=e;if("identifier"!==t?.type)return!0;const r=t.name?.toLowerCase();return"as"!==r&&"modal"!==r&&"non-modal"!==r&&"nonmodal"!==r}),s=_a(await oa(n,t,r,"open",{fallbackModifierKey:"on"},e.modifiers)),i=await async function(e,t,r,n){if(t?.as){const e=wo(await r.evaluate(t.as,n));if(e)return e}for(const t of e){const e=t;if("asExpression"!==e?.type)continue;const r=e.targetType,n=wo(r?.name??r?.value);if(n)return n}for(let t=0;e.length-1>t;t++){const s=e[t];if("identifier"===s?.type&&"as"===s.name?.toLowerCase()){const s=await r.evaluate(e[t+1],n);if("string"==typeof s){const e=s.toLowerCase().trim();if("non-modal"===e||"nonmodal"===e)return"non-modal";if("modal"===e)return"modal"}}}return"modal"}(e.args??[],e.modifiers??{},t,r);return{targets:s,dialogMode:i}}async execute(e,t){for(const t of e.targets)if(Ua(t))t.open||("modal"===e.dialogMode?t.showModal():t.show());else if(za(t))t.open=!0;else if(Eo(t)){const e=t;if("function"==typeof e.showPopover)try{e.showPopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&(!!t.targets.every(e=>xe(e))&&("modal"===t.dialogMode||"non-modal"===t.dialogMode))}};return Yi(t,"OpenCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Open a dialog, details element, or popover",syntax:["open [<target>]","open <dialog> as modal","open <dialog> as non-modal"],examples:["open","open #myDialog","open #details","open #popup as non-modal"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());function xo(e){return e.hasAttribute("popover")}const Co=ta((()=>{let e,t,r=[Xi({name:"close"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:_a(await oa(e.args,t,r,"close",{fallbackModifierKey:"on"},e.modifiers))}}async execute(e,t){for(const t of e.targets)if(Ua(t))t.open&&t.close();else if(za(t))t.open=!1;else if(xo(t)){const e=t;if("function"==typeof e.hidePopover)try{e.hidePopover()}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"CloseCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Close a dialog, details element, or popover",syntax:["close","close <target>"],examples:["close","close #myDialog","close #details","close #popup"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());function Ao(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t}const So=ta((()=>{let e,t,r=[Xi({name:"select"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:await oa(e.args,t,r,"select",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if(0!==e.targets.length)for(const t of e.targets){if(Ao(t)){t.select();continue}const e=t.ownerDocument??("undefined"!=typeof document?document:null),r=e?.defaultView;if(!e||!r)continue;const n=r.getSelection?.();if(n)try{const r=e.createRange();r.selectNodeContents(t),n.removeAllRanges(),n.addRange(r)}catch{}}}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"SelectCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Select the contents of a text field, or select the contents of a DOM element",syntax:["select","select <target>"],examples:["select #search","select <textarea/>","select me"],sideEffects:["focus","dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());function To(e){return"FORM"===e.tagName}const Lo=ta((()=>{let e,t,r=[Xi({name:"reset"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:await oa(e.args,t,r,"reset",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)To(t)&&t.reset()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"ResetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Reset a <form> element to its default values (HTMLFormElement.reset())",syntax:["reset","reset <target>"],examples:["reset","reset #myForm","reset <form/>"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})());void 0===globalThis.Element&&(globalThis.Element=class{});var Oo="moveBefore"in Element.prototype,No=[0,1,0,0,0,0,0,0,0,1,0,1,0],Po=0,Io=1,jo=2,Ro=new Set,Mo=new Set,$o=new Set,Ho=new Set,qo=new Set,Wo=new Set;function Vo(e){for(const t of e.querySelectorAll("input"))(t.name&&t.value!==t.defaultValue||t.checked!==t.defaultChecked)&&t.setAttribute("morphlex-dirty","");for(const t of e.querySelectorAll("option"))t.value&&t.selected!==t.defaultSelected&&t.setAttribute("morphlex-dirty","");for(const t of e.querySelectorAll("textarea"))t.value!==t.defaultValue&&t.setAttribute("morphlex-dirty","")}function Do(e){const t=document.createElement("template");return t.innerHTML=e.trim(),t.content}function Bo(e,t,r){if(t!==r){if(t.parentNode===e){if(t.nextSibling===r)return;if(Oo)return void e.moveBefore(t,r)}e.insertBefore(t,r)}}class Fo{#e=new WeakMap;#t=new WeakMap;#r;constructor(e={}){this.#r=e}morph(e,t){zo(e)&&this.#n(e),t instanceof NodeList?(this.#s(t),this.#i(e,t)):zo(t)&&(this.#a(t),this.#o(e,t))}#i(e,t){const r=t.length;if(0===r)this.#c(e);else if(1===r)this.#o(e,t[0]);else if(r>1){const r=[...t];this.#o(e,r.shift());const n=e.nextSibling,s=e.parentNode||document;for(let e=0;r.length>e;e++){const t=r[e];(this.#r.beforeNodeAdded?.(s,t,n)??1)&&(s.insertBefore(t,n),this.#r.afterNodeAdded?.(t))}}}#o(e,t){e!==t&&(e.isEqualNode(t)||(1===e.nodeType&&1===t.nodeType?e.localName===t.localName?this.#l(e,t):this.#u(e,t):this.#d(e,t)))}#l(e,t){(this.#r.beforeNodeVisited?.(e,t)??1)&&((e.hasAttributes()||t.hasAttributes())&&this.#m(e,t),"textarea"===e.localName&&"textarea"===t.localName?this.#p(e,t):(e.hasChildNodes()||t.hasChildNodes())&&this.visitChildNodes(e,t),this.#r.afterNodeVisited?.(e,t))}#u(e,t){(this.#r.beforeNodeVisited?.(e,t)??1)&&(this.#h(e,t),this.#r.afterNodeVisited?.(e,t))}#d(e,t){(this.#r.beforeNodeVisited?.(e,t)??1)&&(e.nodeType===t.nodeType&&null!==e.nodeValue&&null!==t.nodeValue?e.nodeValue=t.nodeValue:this.#h(e,t),this.#r.afterNodeVisited?.(e,t))}#m(e,t){e.hasAttribute("morphlex-dirty")&&e.removeAttribute("morphlex-dirty");for(const{name:r,value:n}of t.attributes){"value"===r&&_o(e)&&e.value!==n&&(this.#r.preserveChanges&&e.value!==e.defaultValue||(e.value=n)),"selected"===r&&Uo(e)&&!e.selected&&(this.#r.preserveChanges&&e.selected!==e.defaultSelected||(e.selected=!0)),"checked"===r&&_o(e)&&!e.checked&&(this.#r.preserveChanges&&e.checked!==e.defaultChecked||(e.checked=!0));const t=e.getAttribute(r);t!==n&&(this.#r.beforeAttributeUpdated?.(e,r,n)??1)&&(e.setAttribute(r,n),this.#r.afterAttributeUpdated?.(e,r,t))}for(const{name:r,value:n}of e.attributes)t.hasAttribute(r)||("selected"===r&&Uo(e)&&e.selected&&(this.#r.preserveChanges&&e.selected!==e.defaultSelected||(e.selected=!1)),"checked"===r&&_o(e)&&e.checked&&(this.#r.preserveChanges&&e.checked!==e.defaultChecked||(e.checked=!1)),(this.#r.beforeAttributeUpdated?.(e,r,null)??1)&&(e.removeAttribute(r),this.#r.afterAttributeUpdated?.(e,r,n)))}#p(e,t){const r=t.textContent||"",n=e.value!==e.defaultValue;e.textContent!==r&&(e.textContent=r),this.#r.preserveChanges&&n||(e.value=e.defaultValue)}visitChildNodes(e,t){if(!(this.#r.beforeChildrenVisited?.(e)??1))return;const r=e,n=[...e.childNodes],s=[...t.childNodes];Ro.clear(),Mo.clear(),$o.clear(),Ho.clear(),qo.clear(),Wo.clear();const i=[],a=[],o=[],c=[],l=[],u=[];for(let e=0;n.length>e;e++){const t=n[e],r=t.nodeType;c[e]=r,1===r?(u[e]=t.localName,""!==t.id?$o.add(e):Mo.add(e)):3===r&&""===t.textContent?.trim()?Wo.add(e):Ro.add(e)}for(let e=0;s.length>e;e++){const t=s[e],r=t.nodeType;if(o[e]=r,1===r)l[e]=t.localName,qo.add(e);else{if(3===r&&""===t.textContent?.trim())continue;Ho.add(e)}}for(const e of qo){const t=l[e],r=s[e];for(const s of Mo){if(t!==u[s])continue;if(n[s].isEqualNode(r)){i[e]=s,a[e]=Po,Mo.delete(s),qo.delete(e);break}}}for(const e of qo){const t=s[e],r=t.id,o=this.#e.get(t);if(""!==r||o)e:for(const t of $o){const s=n[t];if(l[e]===u[t]){if(""!==r&&r===s.id){i[e]=t,a[e]=Io,$o.delete(t),qo.delete(e);break e}if(o){const r=this.#t.get(s);if(r)for(let n=0;o.length>n;n++){if(r.has(o[n])){i[e]=t,a[e]=Io,$o.delete(t),qo.delete(e);break e}}}}}}for(const e of qo){const t=s[e],r=t.getAttribute("name"),o=t.getAttribute("href"),c=t.getAttribute("src");for(const t of Mo){const s=n[t];if(l[e]===u[t]&&(r&&r===s.getAttribute("name")||o&&o===s.getAttribute("href")||c&&c===s.getAttribute("src"))){i[e]=t,a[e]=Io,Mo.delete(t),qo.delete(e);break}}}for(const e of qo){const t=s[e],r=l[e];for(const s of Mo){if(r===u[s]){if("input"===r&&n[s].type!==t.type)continue;i[e]=s,a[e]=Io,Mo.delete(s),qo.delete(e);break}}}for(const e of Ho){const t=s[e];for(const r of Ro){if(n[r].isEqualNode(t)){i[e]=r,a[e]=Po,Ro.delete(r),Ho.delete(e);break}}}for(const e of Ho){const t=o[e];for(const r of Ro)if(t===c[r]){i[e]=r,a[e]=jo,Ro.delete(r),Ho.delete(e);break}}for(const e of Ro)this.#c(n[e]);for(const e of Wo)this.#c(n[e]);for(const e of Mo)this.#c(n[e]);for(const e of $o)this.#c(n[e]);const d=function(e){const t=e.length;if(0===t)return[];const r=[],n=[],s=Array(t);for(let i=0;t>i;i++){const t=e[i];if(void 0===t)continue;let a=0,o=r.length;for(;o>a;){const e=Math.floor((a+o)/2);t>r[e]?a=e+1:o=e}s[i]=a>0?n[a-1]:-1,a===r.length?(r.push(t),n.push(i)):(r[a]=t,n[a]=i)}const i=[];if(0===n.length)return i;let a=n[n.length-1];for(;void 0!==a&&-1!==a;)i.unshift(a),a=s[a];return i}(i),m=Array(n.length);for(let e=0;d.length>e;e++)m[i[d[e]]]=!0;let p=r.firstChild;for(let e=0;s.length>e;e++){const t=s[e],o=i[e];if(void 0!==o){const s=n[o],i=a[e];m[o]||Bo(r,s,p),i===Po||(i===Io?this.#l(s,t):this.#o(s,t)),p=s.nextSibling}else(this.#r.beforeNodeAdded?.(r,t,p)??1)&&(r.insertBefore(t,p),this.#r.afterNodeAdded?.(t),p=t.nextSibling)}this.#r.afterChildrenVisited?.(e)}#h(e,t){const r=e.parentNode||document,n=e;(this.#r.beforeNodeRemoved?.(e)??1)&&(this.#r.beforeNodeAdded?.(r,t,n)??1)&&(r.insertBefore(t,n),this.#r.afterNodeAdded?.(t),e.remove(),this.#r.afterNodeRemoved?.(e))}#c(e){(this.#r.beforeNodeRemoved?.(e)??1)&&(e.remove(),this.#r.afterNodeRemoved?.(e))}#s(e){for(const t of e)zo(t)&&this.#a(t)}#a(e){const t=this.#e;for(const r of e.querySelectorAll("[id]")){const n=r.id;if(""===n)continue;let s=r;for(;s;){const r=t.get(s);if(r?r.push(n):t.set(s,[n]),s===e)break;s=s.parentElement}}}#n(e){const t=this.#t;for(const r of e.querySelectorAll("[id]")){const n=r.id;if(""===n)continue;let s=r;for(;s;){const r=t.get(s);if(r?r.add(n):t.set(s,new Set([n])),s===e)break;s=s.parentElement}}}}function _o(e){return"input"===e.localName}function Uo(e){return"option"===e.localName}function zo(e){return!!No[e.nodeType]}function Ko(e){return{preserveChanges:e?.preserveChanges??!0}}const Zo={morph(e,t,r){!function(e,t,r={}){"string"==typeof t&&(t=Do(t).childNodes),!r.preserveChanges&&zo(e)&&Vo(e),new Fo(r).morph(e,t)}(e,t,Ko(r))},morphInner(e,t,r){let n;if("string"==typeof t){const r=document.createElement(e.tagName);r.innerHTML=t,n=r}else n=t;!function(e,t,r={}){if("string"==typeof t){const e=Do(t);if(!e.firstChild||1!==e.childNodes.length||1!==e.firstChild.nodeType)throw Error("[Morphlex] The string was not a valid HTML element.");t=e.firstChild}if(1!==e.nodeType||1!==t.nodeType||e.localName!==t.localName)throw Error("[Morphlex] You can only do an inner morph with matching elements.");zo(e)&&Vo(e),new Fo(r).visitChildNodes(e,t)}(e,n,Ko(r))}};function Go(){if("undefined"==typeof document)return;const e=document.startViewTransition;return"function"==typeof e?e.bind(document):void 0}function Qo(){return"function"==typeof Go()}const Jo=[];let Yo=!1;async function Xo(e,t){const r=Go();if(!r)return void await e();const n=async()=>{await e()};let s;if(t?.transitionName)try{s=r({update:n,types:[t.transitionName]})}catch{s=r(n)}else s=r(n);await s.finished}function ec(e,t){return new Promise((r,n)=>{Jo.push({callback:e,options:t,resolve:r,reject:n}),async function(){if(!Yo){Yo=!0;try{for(;Jo.length>0;){const e=Jo.shift();try{await Xo(e.callback,e.options),e.resolve()}catch(t){e.reject(t)}}}finally{Yo=!1}}}().catch(n)})}const tc={into:"innerHTML",over:"outerHTML",innerhtml:"innerHTML",outerhtml:"outerHTML",beforebegin:"beforeBegin",afterbegin:"afterBegin",beforeend:"beforeEnd",afterend:"afterEnd",delete:"delete",none:"none",morph:"morph",innermorph:"morph",outermorph:"morphOuter"};function rc(e,t,r,n){const s=null===t||xe(t)?"":t,i=xe(t)?t:null;switch(r){case"morph":if(null!==t)try{Zo.morphInner(e,i||s,n)}catch(t){console.warn("[HyperFixi] Morph failed, falling back to innerHTML:",t),i?(e.innerHTML="",e.appendChild(i)):e.innerHTML=s}break;case"morphOuter":if(null!==t)try{Zo.morph(e,i||s,n)}catch(t){console.warn("[HyperFixi] Morph failed, falling back to outerHTML:",t),i?e.replaceWith(i):e.outerHTML=s}break;case"innerHTML":i?(e.innerHTML="",e.appendChild(i)):e.innerHTML=s;break;case"outerHTML":i?e.replaceWith(i):e.outerHTML=s;break;case"beforeBegin":i?e.parentElement?.insertBefore(i,e):e.insertAdjacentHTML("beforebegin",s);break;case"afterBegin":i?e.insertBefore(i,e.firstChild):e.insertAdjacentHTML("afterbegin",s);break;case"beforeEnd":i?e.appendChild(i):e.insertAdjacentHTML("beforeend",s);break;case"afterEnd":i?e.parentElement?.insertBefore(i,e.nextSibling):e.insertAdjacentHTML("afterend",s);break;case"delete":e.remove();break;case"none":break;default:throw Error(`[HyperFixi] swap: unknown strategy "${r}"`)}}async function nc(e,t,r,n={}){const{morphOptions:s,useViewTransition:i=!1}=n,a=()=>{for(const n of e)rc(n,t,r,s)};i&&Qo()?await ec(a):a()}function sc(e){if(null==e)return null;if(xe(e))return e;if(function(e){return null!==e&&"object"==typeof e&&"nodeType"in e&&11===e.nodeType&&"childNodes"in e}(e)){const t=e,r=document.createElement("div");return r.appendChild(t.cloneNode(!0)),r.innerHTML}return e+""}function ic(e){return Ya(e,"literal")&&"string"==typeof e.value||Ya(e,"string")?e.value:Ya(e,"identifier")?e.name:void 0}async function ac(e,t){const r=sa(e||void 0,t);if(0===r.length){throw Error("[HyperFixi] swap: no elements found"+(e?` matching "${e}"`:""))}return r}let oc=(()=>{let e,t,r=[Xi({name:"swap"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.args??[],s=e.modifiers??{};if(0===n.length)throw Error("[HyperFixi] swap: command requires arguments");const i=ic(s.strategy)?.toLowerCase();let a=i&&tc[i]||"morph";const o=void 0!==s.viewTransition;let c,l;if(void 0!==s.with||1===n.length)c=n[0],l=s.with;else{const e=ic(n[0])?.toLowerCase();n.length>=3&&e&&tc[e]&&(a=tc[e]),c=n[n.length-2],l=n[n.length-1]}if("morph"===a&&!i&&Ya(c,"identifier")){const e=new Set(["me","you","it","result","window","document"]),t=c.name,r=Ya(l,"identifier")?l.name:void 0;if(void 0!==r&&!e.has(t.toLowerCase())&&!e.has(r.toLowerCase())&&!tc[t.toLowerCase()])return{variant:"variable",leftName:t,rightName:r}}if(!c||!l&&"delete"!==a)throw Error('[HyperFixi] swap: could not parse arguments. Expected "swap <target> with <content>"');const u=Ya(c,"selector")?c.value:await t.evaluate(c,r),d=l?await t.evaluate(l,r):null;if(xe(u))return{targets:[u],content:sc(d),strategy:a,morphOptions:{preserveChanges:!0},useViewTransition:o};return{targets:await ac("string"==typeof u?u:null,r),content:sc(d),strategy:a,morphOptions:{preserveChanges:!0},useViewTransition:o}}async execute(e,t){if("variable"===e.variant){const{leftName:r,rightName:n}=e,s=e=>t.locals?.has(e)?t.locals.get(e):t.globals?.has(e)?t.globals.get(e):void 0,i=(e,r)=>{t.locals?.has(e)?t.locals.set(e,r):t.globals?.has(e)?t.globals.set(e,r):t.locals&&t.locals.set(e,r)},a=s(r);return i(r,s(n)),void i(n,a)}const{targets:r,content:n,strategy:s,morphOptions:i,useViewTransition:a}=e;if(!r||!s)throw Error("[HyperFixi] swap: DOM swap requires targets and strategy");await nc(r,n??null,s,{morphOptions:i,useViewTransition:a})}};return Yi(t,"SwapCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Swap content into target elements with intelligent morphing support",syntax:["swap <target> with <content>","swap [strategy] of <target> with <content>","swap into <target> with <content>","swap over <target> with <content>","swap delete <target>","swap <target> with <content> using view transition"],examples:["swap #target with it","swap innerHTML of #target with it","swap over #modal with fetchedContent","swap delete #notification"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})(),cc=(()=>{let e,t,r=[Xi({name:"morph"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.args??[],s=e.modifiers??{};if(0===n.length&&void 0===s.with)throw Error("[HyperFixi] morph: command requires arguments");const i="over"===ic(s.strategy)?.toLowerCase()?"morphOuter":"morph",a=void 0!==s.viewTransition,o=void 0!==s.on?s.on:n[0],c=void 0!==s.with?s.with:void 0!==s.on?n[0]:n[1];if(!o||!c)throw Error("[HyperFixi] morph: could not determine target");const l=Ya(o,"selector")?o.value:await t.evaluate(o,r),u=c?await t.evaluate(c,r):null;if(!l)throw Error("[HyperFixi] morph: could not determine target");let d;if("string"==typeof l)d=await ac(l,r);else{if(!xe(l))throw Error("[HyperFixi] morph: target must be a selector or element");d=[l]}return{targets:d,content:sc(u),strategy:i,morphOptions:{preserveChanges:!0},useViewTransition:a}}async execute(e,t){const{targets:r,content:n,strategy:s,morphOptions:i,useViewTransition:a}=e;if(!r||!s)throw Error("[HyperFixi] morph: requires targets and strategy");await nc(r,n??null,s,{morphOptions:i,useViewTransition:a})}};return Yi(t,"MorphCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Morph content into target elements (intelligent diffing, preserves state)",syntax:["morph <target> with <content>","morph over <target> with <content>","morph <target> with <content> using view transition"],examples:["morph #target with it","morph over #modal with fetchedContent"],sideEffects:["dom-mutation"],category:"dom",compatibility:"standard"}),Ji(t,n),s=t})();const lc=ta(oc),uc=ta(cc);lc(),uc();const dc={html:{category:"document-root",message:"The <html> element is the document root and cannot be part of a partial",suggestion:"Remove the <html> element. Return only the content that should replace the target."},body:{category:"document-root",message:"The <body> element is the document body and cannot be part of a partial",suggestion:"Remove the <body> element. Return only the content for the target."},head:{category:"document-root",message:"The <head> element contains document metadata and cannot be part of a partial",suggestion:"Remove the <head> element. Styles/scripts should be loaded separately."}},mc={header:{category:"semantic-landmark",message:"The <header> element is a semantic landmark. Swapping may create duplicate landmarks.",suggestion:"Consider if <header> is appropriate in this partial, or if the page already has this landmark."},footer:{category:"semantic-landmark",message:"The <footer> element is a semantic landmark. Swapping may create duplicate landmarks.",suggestion:"Consider if <footer> is appropriate in this partial, or if the page already has this landmark."},main:{category:"semantic-landmark",message:"The <main> element should be unique per page. Swapping may create duplicates.",suggestion:"Consider if <main> is appropriate. Pages should have exactly one <main> element."},nav:{category:"semantic-landmark",message:"The <nav> element is a semantic landmark. Consider if navigation should be in a partial.",suggestion:"Consider if <nav> is appropriate in this partial, or if navigation should be static."},aside:{category:"semantic-landmark",message:"The <aside> element is a semantic landmark. Swapping may affect accessibility.",suggestion:"Consider if <aside> is appropriate in this partial."}},pc={title:{category:"metadata",message:"The <title> element should only appear in <head>. This may be ignored by browsers.",suggestion:"Move <title> to the document <head> or remove from partial."},meta:{category:"metadata",message:"The <meta> element should only appear in <head>. This may be ignored by browsers.",suggestion:"Move <meta> to the document <head> or remove from partial."},link:{category:"metadata",message:"The <link> element for stylesheets should typically be in <head>.",suggestion:"Consider if <link> should be in document <head> for proper loading order."},base:{category:"metadata",message:"The <base> element should only appear once in <head>.",suggestion:"Remove <base> from partial. It must be in document <head>."}};let hc={...{enabled:!("undefined"!=typeof window&&window.__HYPERFIXI_PROD__||"undefined"!=typeof process&&"production"===process.env?.NODE_ENV),showWarnings:!0,strictness:"standard",additionalCriticalElements:[],additionalStructuralElements:[],ignoredElements:[],ignoredTargets:[],targetOverrides:[]}};function fc(e,t){if("*"===t)return!0;if(t.includes("*")){const r=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return RegExp("^"+r+"$").test(e)}return e===t}function yc(e,t=""){const r=function(e){const t={...hc};if(hc.targetOverrides)for(const r of hc.targetOverrides)if(fc(e,r.target))return{...t,...r.config};return t}(t);if(!r.enabled)return{valid:!0,issues:[],bySeverity:{critical:[],structural:[],warning:[]},totalIssues:0,shouldProceed:!0};if(r.ignoredTargets?.some(e=>fc(t,e)))return{valid:!0,issues:[],bySeverity:{critical:[],structural:[],warning:[]},totalIssues:0,shouldProceed:!0};const n=[];if(e.match(/<!DOCTYPE[^>]*>/i)&&!r.ignoredElements?.includes("doctype")&&n.push({severity:"critical",category:"document-root",element:"DOCTYPE",message:"DOCTYPE declarations cannot be part of a partial",suggestion:"Remove DOCTYPE declaration. Partials should only contain content fragments.",targetSelector:t,count:1}),"undefined"==typeof document)return function(e,t,r){const n=[];for(const[s,i]of Object.entries(dc)){if(r.ignoredElements?.includes(s))continue;const a=RegExp(`<${s}[\\s>]`,"gi"),o=e.match(a),c=o?.length||0;c>0&&n.push({severity:"critical",category:i.category,element:s,message:i.message,suggestion:i.suggestion||`Remove the <${s}> element from the partial.`,targetSelector:t,count:c})}if("relaxed"!==r.strictness)for(const[s,i]of Object.entries(mc)){if(r.ignoredElements?.includes(s))continue;const a=RegExp(`<${s}[\\s>]`,"gi"),o=e.match(a),c=o?.length||0;c>0&&n.push({severity:"strict"===r.strictness?"critical":"structural",category:i.category,element:s,message:i.message,suggestion:i.suggestion||`Consider if <${s}> is appropriate in this partial.`,targetSelector:t,count:c})}return gc(n)}(e,t,r);for(const[s,i]of Object.entries(dc)){if(r.ignoredElements?.includes(s))continue;const a=RegExp(`<${s}[\\s>]`,"gi"),o=e.match(a),c=o?.length||0;c>0&&n.push({severity:"critical",category:i.category,element:s,message:i.message,suggestion:i.suggestion||`Remove the <${s}> element from the partial.`,targetSelector:t,count:c})}const s=document.createElement("div");if(s.innerHTML=e,"relaxed"!==r.strictness)for(const[e,i]of Object.entries(mc)){if(r.ignoredElements?.includes(e))continue;const a=s.querySelectorAll(e).length;a>0&&n.push({severity:"strict"===r.strictness?"critical":"structural",category:i.category,element:e,message:i.message,suggestion:i.suggestion||`Consider if <${e}> is appropriate in this partial.`,targetSelector:t,count:a})}if("strict"===r.strictness)for(const[e,i]of Object.entries(pc)){if(r.ignoredElements?.includes(e))continue;const a=s.querySelectorAll(e).length;a>0&&n.push({severity:"warning",category:i.category,element:e,message:i.message,suggestion:i.suggestion||`Move <${e}> to document <head> or remove from partial.`,targetSelector:t,count:a})}if(r.additionalCriticalElements)for(const e of r.additionalCriticalElements){if(r.ignoredElements?.includes(e))continue;const i=s.querySelectorAll(e).length;i>0&&n.push({severity:"critical",category:"document-root",element:e,message:`The <${e}> element is configured as a critical layout element.`,suggestion:`Remove <${e}> from the partial content.`,targetSelector:t,count:i})}if(r.additionalStructuralElements)for(const e of r.additionalStructuralElements){if(r.ignoredElements?.includes(e))continue;const i=s.querySelectorAll(e).length;i>0&&n.push({severity:"structural",category:"semantic-landmark",element:e,message:`The <${e}> element is configured as a structural element.`,suggestion:`Consider if <${e}> is appropriate in this partial.`,targetSelector:t,count:i})}if(r.customValidator){const s=r.customValidator(e,t);n.push(...s)}return gc(n)}function gc(e){const t={critical:e.filter(e=>"critical"===e.severity),structural:e.filter(e=>"structural"===e.severity),warning:e.filter(e=>"warning"===e.severity)};return{valid:0===t.critical.length,issues:e,bySeverity:t,totalIssues:e.length,shouldProceed:!0}}const vc="font-weight: bold; font-size: 13px; color: #6366f1;",bc="color: #dc2626; font-weight: bold;",wc="color: #ea580c; font-weight: bold;",Ec="color: #ca8a04; font-weight: bold;",kc="color: inherit;",xc={critical:"\ud83d\udea8",structural:"\u26a0\ufe0f",warning:"\ud83d\udca1"},Cc={critical:"CRITICAL",structural:"STRUCTURAL",warning:"WARNING"};function Ac(e){0!==e.totalIssues&&("undefined"!=typeof window&&void 0!==console?function(e){if(console.groupCollapsed(`%c[HyperFixi] Partial Template Validation: ${e.totalIssues} issue(s) found`,vc),function(e){const t=[],r=[];e.bySeverity.critical.length>0&&(t.push(`%c${e.bySeverity.critical.length} critical%c`),r.push(bc,kc));e.bySeverity.structural.length>0&&(t.length>0&&t.push(", "),t.push(`%c${e.bySeverity.structural.length} structural%c`),r.push(wc,kc));e.bySeverity.warning.length>0&&(t.length>0&&t.push(", "),t.push(`%c${e.bySeverity.warning.length} warning(s)%c`),r.push(Ec,kc))}(e),e.bySeverity.critical.length>0){console.group(`%c${xc.critical} Critical Issues (${e.bySeverity.critical.length})`,bc);for(const t of e.bySeverity.critical)Sc(t);console.groupEnd()}if(e.bySeverity.structural.length>0){console.group(`%c${xc.structural} Structural Issues (${e.bySeverity.structural.length})`,wc);for(const t of e.bySeverity.structural)Sc(t);console.groupEnd()}if(e.bySeverity.warning.length>0){console.group(`%c${xc.warning} Warnings (${e.bySeverity.warning.length})`,Ec);for(const t of e.bySeverity.warning)Sc(t);console.groupEnd()}console.groupEnd()}(e):function(e){console.warn(`[HyperFixi] Partial Template Validation: ${e.totalIssues} issue(s) found`);const t=[];e.bySeverity.critical.length>0&&t.push(e.bySeverity.critical.length+" critical");e.bySeverity.structural.length>0&&t.push(e.bySeverity.structural.length+" structural");e.bySeverity.warning.length>0&&t.push(e.bySeverity.warning.length+" warning(s)");console.warn(" Found: "+t.join(", "));for(const t of e.issues){console.warn(` ${xc[t.severity]} [${Cc[t.severity]}] <${t.element}>${t.count>1?` (${t.count}x)`:""}${t.targetSelector?` [target: ${t.targetSelector}]`:""}`),console.warn(" "+t.message),console.warn(" Fix: "+t.suggestion)}}(e))}function Sc(e){}function Tc(e){return`${xc[e.severity]} [${Cc[e.severity]}] <${e.element}>${e.count>1?` (${e.count}x)`:""}${e.targetSelector?` [target: ${e.targetSelector}]`:""}: ${e.message}`}function Lc(e){return e.issues.map(Tc)}function Oc(e,t,r={}){return new CustomEvent(e,{detail:void 0!==t?t:{},bubbles:void 0===r.bubbles||r.bubbles,cancelable:void 0===r.cancelable||r.cancelable,composed:void 0!==r.composed&&r.composed})}function Nc(e){const t=e.trim();return/^\d+$/.test(t)?parseInt(t,10):/^\d*\.\d+$/.test(t)?parseFloat(t):"true"===t||"false"!==t&&("null"===t?null:"undefined"!==t?t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t:void 0)}function Pc(e,t,r={},n={}){const s=Oc(t,r,n);return e.dispatchEvent(s),s}function Ic(e,t,r={},n={}){return{lokascript:Pc(e,"lokascript:"+t,r,n),hyperfixi:Pc(e,"hyperfixi:"+t,r,n)}}const jc={morph:"morph",morphouter:"morphOuter",innerhtml:"innerHTML",outerhtml:"outerHTML",beforebegin:"beforeBegin",afterbegin:"afterBegin",beforeend:"beforeEnd",afterend:"afterEnd",delete:"delete",none:"none"};function Rc(e,t){const{target:r,strategy:n,content:s}=e,i=document.querySelector(r);if(!i||!xe(i))return{success:!1,error:`Target "${r}" not found`};try{switch(n){case"morph":Zo.morphInner(i,s,t);break;case"morphOuter":Zo.morph(i,s,t);break;case"innerHTML":i.innerHTML=s;break;case"outerHTML":i.outerHTML=s;break;case"beforeBegin":i.insertAdjacentHTML("beforebegin",s);break;case"afterBegin":i.insertAdjacentHTML("afterbegin",s);break;case"beforeEnd":i.insertAdjacentHTML("beforeend",s);break;case"afterEnd":i.insertAdjacentHTML("afterend",s);break;case"delete":i.remove();break;case"none":break;default:return{success:!1,error:`Unknown strategy "${n}"`}}return{success:!0}}catch(e){return{success:!1,error:e+""}}}function Mc(e,t){const r=function(e){const t=[],r=document.createElement("div");r.innerHTML=e;const n=r.querySelectorAll("hx-partial");for(const e of n){const r=e.getAttribute("target");if(!r)continue;const n=e.getAttribute("strategy")?.toLowerCase()||"morph";t.push({target:r,strategy:jc[n]||"morph",content:e.innerHTML})}return t}(e),n={...hc},s={count:0,targets:[],errors:[],validationWarnings:[],validationDetails:{}};for(const e of r){if(n.enabled){const t=yc(e.content,e.target);t.totalIssues>0&&(n.showWarnings&&Ac(t),s.validationWarnings.push(...Lc(t)),s.validationDetails[e.target]=t)}const r=Rc(e,t);r.success?(s.count++,s.targets.push(e.target)):r.error&&s.errors.push(`${e.target}: ${r.error}`)}return s}const $c=ta((()=>{let e,t,r=[Xi({name:"process"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.args;if(!n||0===n.length)throw Error("process partials command requires content argument");const s=n[0],i=s?await t.evaluate(s,r):void 0;let a;if("string"==typeof i)a=i;else if(xe(i))a=i.outerHTML;else{if(!i||"function"!=typeof i.text)throw Error("process partials: content must be an HTML string or element");a=await i.text()}return{html:a,useViewTransition:void 0!==e.modifiers?.viewTransition,morphOptions:{preserveChanges:!0}}}async execute(e,t){const{html:r,useViewTransition:n,morphOptions:s}=e,i=()=>Mc(r,s);let a;return n&&Qo()?await ec(()=>{a=i()}):a=i(),t.it=a,Ic(window,"partials",a),a}};return Yi(t,"ProcessPartialsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Process <hx-partial> elements for multi-target swaps",syntax:["process partials in <content>","process partials in <content> using view transition"],examples:["process partials in it","process partials in fetchedHtml","process partials in it using view transition"],sideEffects:["dom-mutation"],category:"dom",compatibility:"lokascript-extension"}),Ji(t,n),s=t})());function Hc(e,t,r,n){return e?new Promise(r=>{const s=()=>{i({event:null,timedOut:!1,cancelled:!0})},i=Wc(()=>{e.removeEventListener(t,a),n&&n.removeEventListener("abort",s)},r),a=e=>{i({event:e,timedOut:!1,cancelled:!1})};n?.aborted?r({event:null,timedOut:!1,cancelled:!0}):(e.addEventListener(t,a),n&&n.addEventListener("abort",s))}):Promise.reject(Error("waitForEvent: no target provided"))}function qc(e){return new Promise(t=>setTimeout(t,e))}function Wc(e,t){let r=!1;return n=>{r||(r=!0,e(),t(n))}}$c();const Vc=ta((()=>{let e,t,r=[Xi({name:"wait"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args?.length)throw Error("wait command requires an argument");const n=e.args[0];return"arrayLiteral"===n.type&&n.elements?this.parseEventArrayWait(n.elements,e.args[1],t,r):this.parseTimeWait(e.args[0],t,r)}async execute(e,t){const r=Date.now();if("time"===e.type)return await qc(e.milliseconds),{type:"time",result:e.milliseconds,duration:Date.now()-r};if("event"===e.type){const n=e.target??t.me??document,s=(await Hc(n,e.eventName)).event;if(Object.assign(t,{it:s}),e.destructure)for(const r of e.destructure)r in s&&t.locals.set(r,s[r]);return{type:"event",result:s,duration:Date.now()-r}}const{result:n,winningCondition:s}=await this.executeRace(e.conditions,t);if(Object.assign(t,{it:n}),n instanceof Event&&"event"===s?.type&&s.destructure)for(const e of s.destructure)e in n&&t.locals.set(e,n[e]);return{type:n instanceof Event?"event":"time",result:n,duration:Date.now()-r}}async parseTimeWait(e,t,r){return{type:"time",milliseconds:Da(await t.evaluate(e,r))}}async parseEventArrayWait(e,t,r,n){let s;if(t){const e=await r.evaluate(t,n);if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("wait for from: target must be an EventTarget");s=e}s||(s=n.me??void 0);const i=[];for(const t of e){const e=t;if("objectLiteral"!==e.type||!e.properties)continue;let a,o="",c=[];for(const t of e.properties){const e=t.key?.name||t.key?.value;if("name"===e&&t.value){if("string"!=typeof t.value.value)throw Error("wait for: event name must be a string");o=t.value.value}else"args"===e&&t.value?.elements?c=t.value.elements.map(e=>e.value||e.name||""):"duration"===e&&t.value&&(a=t.value)}if(a){const e=await r.evaluate(a,n);i.push({type:"time",milliseconds:Da(e)})}else o&&i.push({type:"event",eventName:o,target:s,destructure:c.length>0?c:void 0})}return 1===i.length?i[0]:{type:"race",conditions:i}}async executeRace(e,t){const r=new AbortController,n=r.signal,s=e.map(e=>{if("time"===e.type)return qc(e.milliseconds).then(()=>({result:e.milliseconds,winningCondition:e}));return Hc(e.target??t.me??document,e.eventName,0,n).then(t=>({result:t.event,winningCondition:e}))});try{return await Promise.race(s)}finally{r.abort()}}};return Yi(t,"WaitCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Wait for time delay, event, or race condition",syntax:["wait <time>","wait for <event>","wait for <event> or <condition>"],examples:["wait 2s","wait for click","wait for click or 1s","wait for mousemove(clientX, clientY)"],sideEffects:["time","event-listening"],category:"async",compatibility:"standard"}),Ji(t,n),s=t})()),Dc=new Map;let Bc=[/^4\d{2}$/,/^5\d{2}$/];let Fc=(()=>{let e,t,r=[Xi({name:"fetch"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args?.length)throw Error("fetch requires a URL");const n=await this.parseURL(e.args[0],t,r),s=this.parseResponseType(e.modifiers.as);return{url:n,responseType:s,options:await this.parseRequestOptions(e.modifiers.with,t,r),throwOnError:!!!e.modifiers.doNotThrow&&"response"!==s}}async execute(e,t){const r=Date.now(),{url:n,responseType:s,options:i}=e,a=new AbortController;let o;t.me&&(o=()=>a.abort(),t.me.addEventListener("fetch:abort",o,{once:!0}));const c={...i,signal:a.signal},l=Dc.get(s);if(l?.accept){const e=new Headers(c.headers);e.has("Accept")||e.set("Accept",l.accept),c.headers=e}if(t.me){const e={...c,sender:t.me,headers:c.headers||{}};this.dispatchEvent(t.me,"fetch:beforeRequest",e),c.headers=e.headers}let u;i.timeout&&(u=setTimeout(()=>a.abort(),i.timeout));try{let i=await fetch(n,c);if(t.me){const e={response:i};this.dispatchEvent(t.me,"fetch:afterResponse",e),i=e.response}if(e.throwOnError&&function(e){const t=e+"";return Bc.some(e=>e.test(t))}(i.status)){const e=Error(`Fetch failed for ${n}: HTTP ${i.status} ${i.statusText}`.trim());throw e.response=i,e.isFetchStatusError=!0,e}const a=await this.handleResponse(i,s,t);t.me&&this.dispatchEvent(t.me,"fetch:afterRequest",{result:a});const o={status:i.status,statusText:i.statusText,headers:i.headers,data:a,url:i.url,duration:Date.now()-r};return Object.assign(t,{it:a}),o}catch(e){if(t.me&&this.dispatchEvent(t.me,"fetch:error",{reason:e instanceof Error?e.message:e+"",error:e}),e instanceof Error&&"AbortError"===e.name)throw Error("Fetch aborted for "+n);if(e instanceof Error&&!0===e.isFetchStatusError)throw e;throw Error(`Fetch failed for ${n}: ${e instanceof Error?e.message:e+""}`)}finally{u&&clearTimeout(u),t.me&&o&&t.me.removeEventListener("fetch:abort",o)}}async parseURL(e,t,r){const n=await t.evaluate(e,r);if("string"!=typeof n||!n){const t=e;if(null==n&&"identifier"===t?.type&&t.name)throw Error(`fetch: URL expression "${t.name}" evaluated to ${n+""} \u2014 check the variable is set, or quote it if you meant a literal URL (fetch 'https://example.com/path')`);throw Error("fetch: URL must be a non-empty string")}return n}parseResponseType(e){if(!e)return"text";if(("identifier"===e.type||"expression"===e.type)&&e.name){const t=e.name.toLowerCase();if("object"===t)return"json";if(["text","json","html","response","blob","arraybuffer"].includes(t))return"arraybuffer"===t?"arrayBuffer":t;if(Dc.has(t))return t;throw Error(`fetch: invalid response type "${t}"`)}return"text"}async parseRequestOptions(e,t,r){if(!e)return{};const n=await t.evaluate(e,r);if("object"!=typeof n||null===n)throw Error('fetch: "with" options must be an object');const s={};return"method"in n&&(s.method=(n.method+"").toUpperCase()),"headers"in n&&(s.headers=this.parseHeaders(n.headers)),"body"in n&&(s.body=this.parseBody(n.body)),"credentials"in n&&(s.credentials=n.credentials),"mode"in n&&(s.mode=n.mode),"cache"in n&&(s.cache=n.cache),s}parseHeaders(e){if(e instanceof Headers)return e;const t=new Headers;if("object"==typeof e&&null!==e)for(const[r,n]of Object.entries(e))t.set(r,n+"");return t}parseBody(e){return null==e?null:e instanceof FormData||e instanceof Blob||e instanceof ArrayBuffer||e instanceof URLSearchParams||"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e+""}async handleResponse(e,t,r){switch(t){case"response":return e;case"json":return e.json();case"html":return this.parseHTML(await e.text());case"blob":return e.blob();case"arrayBuffer":return e.arrayBuffer();case"text":return e.text();default:{const n=Dc.get(t);return n?n.handler(e,r):e.text()}}}parseHTML(e){const t=(new DOMParser).parseFromString(e,"text/html"),r=document.createDocumentFragment();return Array.from(t.body.childNodes).forEach(e=>r.appendChild(e.cloneNode(!0))),1===r.childNodes.length&&xe(r.firstChild)?r.firstChild:r}dispatchEvent(e,t,r){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!0}))}};return Yi(t,"FetchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Make HTTP requests with lifecycle event support",syntax:["fetch <url>","fetch <url> as <type>","fetch <url> with <options>"],examples:['fetch "/api/data"','fetch "/api/users" as json','fetch "/api/save" with { method:"POST" }','fetch "/api/optional" as json do not throw'],sideEffects:["network","event-dispatching"],category:"async",compatibility:"standard"}),Ji(t,n),s=t})();const _c=ta(Fc);async function Uc(e,t,r){const n=await t.evaluate(e,r),s=Array.isArray(n)?n[0]:n;return xe(s)?s:null}async function zc(e,t,r,n){if(!e)return null;const s=e,i=s.type;if(n.nodeWriters&&i){const t=he(i);if(t)return{kind:"node-write",node:e,writer:t}}if(n.selectorSource&&"selector"===i&&"string"==typeof s.value)return{kind:"selector",selector:s.value};const a=await async function(e,t,r,n){const s=e;if("attributeAccess"===s?.type)return{elements:await n(),name:s.attributeName};if("binaryExpression"===s?.type&&"of"===s.operator&&"attributeAccess"===s.left?.type){const e=await Uc(s.right,t,r);if(e)return{elements:[e],name:s.left.attributeName}}if("memberExpression"===s?.type&&"attributeAccess"===s.property?.type){const e=await Uc(s.object,t,r);if(e)return{elements:[e],name:s.property.attributeName}}return null}(e,t,r,n.scopeElements);if(a)return{kind:"attribute",elements:a.elements,name:a.name};const o=await ao(e,t,r);if(o)return n.styleSplit&&o.property.startsWith("*")?{kind:"style",element:o.element,property:o.property.substring(1)}:{kind:"property",target:o};if(n.bareReference&&("identifier"===i||"variable"===i||"symbol"===i)&&"string"==typeof s.name){const e=s.scope;return{kind:"variable",name:s.name,scope:"element"===e||"global"===e?e:void 0}}return null}const Kc=ta((()=>{let e,t,r=[Xi({name:"set"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args?.length)throw Error("set command requires a target");const n=e.args[0],s=n?.name||n?.value,i=n?.scope,a=await zc(n,t,r,{scopeElements:()=>this.resolveTargets(e.modifiers.on,t,r),nodeWriters:!0,styleSplit:!0});if(a)return function(e,t){switch(e.kind){case"node-write":return{type:"node-write",node:e.node,value:t,writer:e.writer};case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"style":return{type:"style",element:e.element,property:e.property,value:t+""};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};default:throw Error(`set: unrequested write-target rung '${e.kind}'`)}}(a,await this.extractValue(e,t,r));if("memberExpression"===n?.type||"propertyAccess"===n?.type){const s=await this.tryParseMemberExpression(n,e,t,r);if(s)return s}let o;if(o="identifier"!==n?.type&&"variable"!==n?.type||"string"!=typeof s?await t.evaluate(n,r):s,function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if(xe(e)||e instanceof Node)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(o)){return{type:"object-literal",properties:o,targets:await this.resolveTargets(e.modifiers.on,t,r)}}if(so(o)){const n=io(o,r);if(n){const s=await this.extractValue(e,t,r);return{type:"property",element:n.element,property:n.property,value:s}}return this.parseTheXofY(o,e,t,r)}if("string"==typeof o&&wa(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"style",element:await this.resolveElement(e.modifiers.on,t,r),property:n,value:s+""}}if("string"==typeof o&&da(o)){const n=o.substring(1).trim(),s=await this.extractValue(e,t,r);return{type:"attribute",elements:await this.resolveTargets(e.modifiers.on,t,r),name:n,value:s}}if("string"==typeof o){const n=o.match(/^(my|me|its?|your?)\s+(.+)$/i);if(n){const s=aa(n[1],r),i=await this.extractValue(e,t,r);return{type:"property",element:s,property:n[2],value:i}}}if(xe(o)){return{type:"property",element:o,property:"textContent",value:await this.extractValue(e,t,r)}}if(Array.isArray(o)&&o.length>0&&xe(o[0])){const n=await this.extractValue(e,t,r);return{type:"property",element:o[0],property:"textContent",value:n}}if("string"!=typeof o){throw Error("set command target must be a string or object literal"+("memberExpression"===n?.type||"propertyAccess"===n?.type?` (a property chain evaluated to ${null===o?"null":typeof o} \u2014 check that all intermediate objects exist)`:""))}return{type:"variable",name:o,value:await this.extractValue(e,t,r),scope:"element"===i||"global"===i?i:void 0}}async execute(e,t){switch(e.type){case"variable":return"element"===e.scope?we(t,e.name,e.value):"global"===e.scope?Le(e.name,e.value,t,"global"):Le(e.name,e.value,t),"result"!==e.name&&"it"!==e.name||Object.assign(t,{[e.name]:e.value}),Object.assign(t,{it:e.value}),{target:e.name,value:e.value,targetType:"variable"};case"attribute":for(const t of e.elements)t.setAttribute(e.name,e.value+"");return Object.assign(t,{it:e.value}),{target:"@"+e.name,value:e.value,targetType:"attribute"};case"property":return Qa(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"style":return ka(e.element,e.property,e.value),Object.assign(t,{it:e.value}),{target:e.element,value:e.value,targetType:"property"};case"object-literal":for(const t of e.targets)for(const[r,n]of Object.entries(e.properties))Qa(t,r,n);return Object.assign(t,{it:e.properties}),{target:e.targets[0]||"unknown",value:e.properties,targetType:"property"};case"member-assignment":return e.container[e.property]=e.value,Object.assign(t,{it:e.value}),{target:e.property,value:e.value,targetType:"property"};case"node-write":return await e.writer(e.node,e.value,t),Object.assign(t,{it:e.value}),{target:e.node.name??"",value:e.value,targetType:"variable"};default:throw Error("Unknown input type: "+e.type)}}async tryParseMemberExpression(e,t,r,n){const s=e.object,i=e.property;if(s?.name&&i?.name){const e=s.name.toLowerCase();if(["me","my","it","its","you","your"].includes(e)){const s=aa(e,n),a=await this.extractValue(t,r,n);return{type:"property",element:s,property:i.name,value:a}}}const a=e.object,o=e.computed;if(a){const s=a;let c;if("memberExpression"===s.type&&!s.computed&&"style"===s.property?.name&&s.object){const e=await r.evaluate(s.object,n);c=(e&&"object"==typeof e&&"style"in e?e.style:void 0)??await r.evaluate(a,n)}else c=await r.evaluate(a,n);if(null!=c&&"object"==typeof c){const s=o?await r.evaluate(e.property,n)+"":i?.name||"";if(s){return{type:"member-assignment",container:c,property:s,value:await this.extractValue(t,r,n)}}}}return null}async extractValue(e,t,r){if(e.modifiers.to)return t.evaluate(e.modifiers.to,r);const n=e.args[1];if(n)return t.evaluate(n,r);throw Error('set command requires a value (use "to" keyword)')}async resolveElement(e,t,r){if(!e)return na(void 0,r);return na(await t.evaluate(e,r),r)}async resolveTargets(e,t,r){if(!e)return sa(void 0,r);return sa(await t.evaluate(e,r),r)}async parseTheXofY(e,t,r,n){const s=e.match(/^the\s+(.+?)\s+of\s+(.+)$/i);if(!s)throw Error('Invalid "the X of Y" syntax');const[,i,a]=s,o=na(a,n),c=await this.extractValue(t,r,n);return{type:"property",element:o,property:i.trim(),value:c}}validate(e){if(!e||"object"!=typeof e)return!1;const t=e;if(!t.type||"string"!=typeof t.type)return!1;if(!["variable","attribute","property","style","object-literal"].includes(t.type))return!1;switch(t.type){case"variable":return"string"==typeof t.name&&"value"in t;case"attribute":return"string"==typeof t.name&&Array.isArray(t.elements)&&t.elements.every(xe)&&"value"in t;case"property":return"string"==typeof t.property&&xe(t.element)&&"value"in t;case"style":return"string"==typeof t.property&&""!==t.property&&xe(t.element)&&"string"==typeof t.value;case"object-literal":return null!==t.properties&&"object"==typeof t.properties&&Array.isArray(t.targets)&&t.targets.length>0;default:return!1}}};return Yi(t,"SetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Set values to variables, attributes, or properties",syntax:["set <target> to <value>"],examples:['set myVar to "value"','set @data-theme to "dark"','set my innerHTML to "content"'],sideEffects:["state-mutation","dom-mutation"],category:"data",compatibility:"standard"}),Ji(t,n),s=t})());const Zc=ta((()=>{let e,t,r=[Xi({name:"get"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error("get command requires an expression argument");const n=e.args[0],s=await t.evaluate(n,r);return s instanceof NodeList&&1===s.length||Array.isArray(s)&&1===s.length?{value:s[0]}:{value:s}}execute(e,t){return t.it=e.value,Object.assign(t,{result:e.value}),{value:e.value}}validate(e){return"object"==typeof e&&null!==e&&"value"in e}};return Yi(t,"GetCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Evaluate an expression and store the result in it",syntax:"get <expression>",examples:["get #my-dialog","get <button/>","get me.parentElement"],sideEffects:["context-mutation"],category:"data",compatibility:"standard"}),Ji(t,n),s=t})());function Gc(e){return e&&"object"==typeof e&&e.type||"unknown"}const Qc=ta((()=>{let e,t,r=[Xi({name:"increment"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n="decrement"===e.commandName?.toLowerCase()?"decrement":"increment",s=await async function(e,t,r,n){if(!e.args||0===e.args.length)throw Error(n+" command requires a target");const s=e.args[0];let i,a,o;const c=Gc(s);if("identifier"===c)i=s.name,s.scope&&(a=s.scope);else if("literal"===c)i=s.value;else{const e=he(c);if(e){const n=await t.evaluate(s,r),a="number"==typeof n?n:null==n?0:Number(n)||0;i=a,o={node:s,writer:e,currentValue:a}}else{const e=await t.evaluate(s,r);i=Array.isArray(e)&&e.length>0?e[0]:e}}let l=1,u=a;for(let n=1;e.args.length>n;n++){const s=e.args[n];if(Xa(s)){const e=s.value;"global"===e?u="global":"number"==typeof e&&(l=e)}else if(s){const e=await t.evaluate(s,r);"number"==typeof e&&(l=e)}}const d=e.modifiers?.by;if(d){const e=d.value;if("literal"===Gc(d)&&"number"==typeof e)l=e;else if("literal"!==Gc(d)){const e=await t.evaluate(d,r);"number"==typeof e&&(l=e)}}return{target:i,amount:l,...u&&{scope:u},...o&&{customWrite:o}}}(e,t,r,n);return{...s,operation:n}}async execute(e,t){const{target:r,property:n,scope:s,amount:i=1,operation:a="increment",customWrite:o}=e;if(o){const e=isFinite(i)?i:1,r="increment"===a?o.currentValue+e:o.currentValue-e;return await o.writer(o.node,r,t),Object.assign(t,{it:r}),r}const c=Ne(r,n,s,t);let l;if(isNaN(c))l=NaN;else{const e=isFinite(i)?i:1;l="increment"===a?c+e:c-e}return Pe(r,n,s,l,t),Object.assign(t,{it:l}),l}};return Yi(t,"NumericModifyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Modify a variable or property by a specified amount (default: 1)",syntax:["increment <target> [by <number>]","decrement <target> [by <number>]"],examples:["increment counter","increment counter by 5","decrement counter","decrement counter by 5"],sideEffects:["data-mutation","context-modification"],aliases:["decrement"],category:"data",compatibility:"standard"}),Ji(t,n),s=t})());function Jc(e){const t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}const Yc=ta((()=>{let e,t,r=[Xi({name:"clear"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.args?.[0],s=function(e){if(!e)return null;const t=e.type,r=e.name;if("string"!=typeof r||""===r)return null;if("variable"===t||"identifier"===t)return{name:r,scope:e.scope};if("contextReference"===t){if(r.startsWith(":"))return{name:r.slice(1),scope:"element"};if(r.startsWith("$"))return{name:r.slice(1),scope:"global"}}return null}(n);if(s)try{const e=await t.evaluate(n,r);if(!xe(e)&&!Array.isArray(e))return{type:"variable",...s}}catch{return{type:"variable",...s}}return{type:"form-fields",targets:await oa(e.args,t,r,"clear",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){if("variable"===e.type)return Le(e.name,null,t,e.scope),void Object.assign(t,{it:null});for(const t of e.targets)Jc(t)&&("SELECT"===t.tagName?t.selectedIndex=-1:t.value="")}validate(e){if("object"!=typeof e||null===e)return!1;if("variable"===e.type)return"string"==typeof e.name;if("form-fields"===e.type){const t=e.targets;return Array.isArray(t)&&t.every(e=>xe(e))}return!1}};return Yi(t,"ClearCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Reset a variable to null or clear the value of a form field (<input>, <textarea>, <select>)",syntax:["clear <var>","clear :var","clear <target>"],examples:["clear :count","clear myVar","clear #search","clear <textarea/>"],sideEffects:["state-mutation","dom-mutation"],category:"data",compatibility:"standard"}),Ji(t,n),s=t})());const Xc=ta((()=>{let e,t,r=[Xi({name:"log"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)return{values:[]};return{values:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r="undefined"!=typeof window?window.console:console;0===e.values.length?r.log():r.log(...e.values)}validate(e){if("object"!=typeof e||null===e)return!1;return Array.isArray(e.values)}};return Yi(t,"LogCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Log values to the console",syntax:"log [<values...>]",examples:['log "Hello World"',"log me.value","log x y z",'log "Result:" result'],sideEffects:["console-output"],category:"utility",compatibility:"standard"}),Ji(t,n),s=t})());let el=(()=>{let e,t,r=[Xi({name:"trigger"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n="send"===e.commandName?.toLowerCase()?"send":"trigger",s=n;if(!e.args?.length)throw Error(s+" command requires an event name");const i=e=>e?.type||"unknown",a=e.args[0];let o,c,l;if("functionCall"===i(a)||"callExpression"===i(a)){o=a.name||a.callee?.name;const e=a.args||a.arguments;e?.length&&(c=await this.parseEventDetail(e,t,r))}else if("identifier"===i(a)||"keyword"===i(a))o=a.name;else{const e=await t.evaluate(a,r);o="string"==typeof e?e:e+""}const u=e.modifiers?.on||e.modifiers?.to;if(u)l=await this.resolveTargets([u],t,r,s);else{if(!r.me)throw Error(s+": no target specified and context.me is null");l=[r.me]}return{eventName:o,detail:c,targets:l,options:await this.parseEventOptions(e.modifiers?.with,t,r),mode:n}}async execute(e,t){const r=Oc(e.eventName,e.detail,e.options);for(const t of e.targets)t.dispatchEvent(r);t.it=r}async resolveTargets(e,t,r,n){const s=[];for(const n of e){const e=await t.evaluate(n,r);if("window"!==e&&e!==window)if("document"!==e&&e!==document)if("me"===e&&r.me)s.push(r.me);else if("you"===e&&r.you)s.push(r.you);else if("it"===e&&r.it)s.push(r.it);else if(xe(e))s.push(e);else if(e instanceof NodeList)s.push(...Array.from(e).filter(xe));else if(Array.isArray(e))s.push(...e.filter(xe));else{if("string"==typeof e){const t=document.querySelectorAll(e);if(0===t.length)throw Error(`No elements found: "${e}"`);s.push(...Array.from(t).filter(xe));continue}if(!e||"object"!=typeof e||!("addEventListener"in e))throw Error("Invalid target: "+typeof e);s.push(e)}else s.push(document);else s.push(window)}if(!s.length)throw Error(n+": no valid targets");return s}async parseEventDetail(e,t,r){if(!e?.length)return;if(1===e.length){const n=e[0];if("objectLiteral"!==n?.type)return await t.evaluate(n,r)}const n={};for(const s of e){const e=await t.evaluate(s,r);if("object"!=typeof e||null===e||Array.isArray(e)){if("string"==typeof e&&e.includes(":")){const[t,r]=e.split(":",2);n[t.trim()]=Nc(r.trim())}}else Object.assign(n,e)}return Object.keys(n).length?n:void 0}async parseEventOptions(e,t,r){const n={bubbles:!0,cancelable:!0,composed:!1};if(!e)return n;const s=e,i=Ya(s,"arrayLiteral")?s.elements:[e];for(const e of i){const s=await t.evaluate(e,r);if("string"==typeof s){const e=s.toLowerCase();"bubbles"===e?n.bubbles=!0:"nobubbles"===e?n.bubbles=!1:"cancelable"===e?n.cancelable=!0:"nocancelable"===e?n.cancelable=!1:"composed"===e&&(n.composed=!0)}}return n}};return Yi(t,"EventDispatchCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({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","send saved to #form with bubbles cancelable"],sideEffects:["event-dispatch"],aliases:["send"],category:"event",compatibility:"standard"}),Ji(t,n),s=t})();const tl=ta(el);const rl=ta((()=>{let e,t,r=[Xi({name:"go"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.modifiers;if(n.back)return{kind:"back"};if(n.forward)return{kind:"forward"};const s=void 0!==n.in;if(void 0!==n.url){const e=await t.evaluate(n.url,r)+"";if(!this.isValidUrl(e))throw Error(`Invalid URL: "${e}"`);return{kind:"url",url:e,newWindow:s}}const i=n.of??e.args[0];if(!i&&!n.position)throw Error("Go command requires arguments");const a=i?await t.evaluate(i,r):"body";if("string"==typeof a&&this.isBareUrl(a)&&!n.of&&!n.position)return{kind:"url",url:a,newWindow:s};const o=this.resolveScrollTarget(a,r);if(!o)throw Error("Target element not found: "+(a+""));const c=n.position?await t.evaluate(n.position,r)+"":void 0,l={vertical:"top",horizontal:"nearest"};"top"===c||"middle"===c||"bottom"===c?l.vertical=c:"left"!==c&&"center"!==c&&"right"!==c||(l.horizontal=c,l.vertical="nearest");const u="instant"===(n.behavior?await t.evaluate(n.behavior,r):void 0)?"instant":"smooth";let d=0;if(void 0!==n.by){const e=Number((await t.evaluate(n.by,r)+"").replace(/px$/,""));Number.isNaN(e)||(d=e)}return{kind:"scroll",target:o,position:l,offset:d,behavior:u}}async execute(e,t){if("back"===e.kind||"forward"===e.kind)return await this.goHistory(e.kind),{result:e.kind,type:"back"};if("url"===e.kind)return this.navigate(e.url,e.newWindow),{result:e.url,type:"url"};const{target:r,position:n,offset:s,behavior:i}=e;if("undefined"!=typeof window){const e=this.mapVerticalPosition(n.vertical),t=this.mapHorizontalPosition(n.horizontal);if(r.scrollIntoView?.({behavior:i,block:e,inline:t}),0!==s){const{x:e,y:t}=this.calculateScrollPosition(r,n,s);window.scrollTo?.({left:e,top:t,behavior:i})}}return{result:r,type:"scroll"}}isBareUrl(e){return!!e.startsWith("/")||/^[a-z][a-z0-9+.-]*:/i.test(e)}navigate(e,t){if(t){if("undefined"!=typeof window&&window.open){const t=window.open(e,"_blank");t?.focus&&t.focus()}}else e.startsWith("#")?"undefined"!=typeof window&&(window.location.hash=e):"undefined"!=typeof window&&(window.location.assign?.(e)??(window.location.href=e))}async goHistory(e){if("undefined"==typeof window||!window.history)throw Error("Browser history API not available");"back"===e?window.history.back():window.history.forward()}isValidUrl(e){try{return e.startsWith("/")||e.startsWith("#")||new URL(e),!0}catch{return!1}}mapVerticalPosition(e){return{top:"start",middle:"center",bottom:"end",nearest:"nearest"}[e]||"start"}mapHorizontalPosition(e){return{left:"start",center:"center",right:"end",nearest:"nearest"}[e]||"nearest"}calculateScrollPosition(e,t,r){if("undefined"==typeof window||!e.getBoundingClientRect)return{x:0,y:0};const n=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement?.scrollLeft||0,i=window.pageYOffset||document.documentElement?.scrollTop||0,a=window.innerWidth||800,o=window.innerHeight||600;let c=s,l=i;switch(t.horizontal){case"left":c=n.left+s;break;case"center":c=n.left+s+n.width/2-a/2;break;case"right":c=n.right+s-a}switch(t.vertical){case"top":l=n.top+i+r;break;case"middle":l=n.top+i+n.height/2-o/2+r;break;case"bottom":l=n.bottom+i-o+r}return{x:Math.max(0,c),y:Math.max(0,l)}}resolveScrollTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;const r="string"==typeof e?e:e+"";if("body"===r&&"undefined"!=typeof document)return document.body;if("html"===r&&"undefined"!=typeof document)return document.documentElement;if("me"===r&&xe(t.me))return t.me;if("it"===r&&xe(t.it))return t.it;if("you"===r&&xe(t.you))return t.you;const n=Te(r,t);if(xe(n))return n;if("undefined"!=typeof document)try{const e=document.querySelector(r);if(e)return e}catch{try{const e=document.getElementsByTagName(r);if(e.length>0)return e[0]}catch{}}return null}};return Yi(t,"GoCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Navigation functionality including URL navigation, element scrolling, and browser history",syntax:["go back","go to url <url> [in new window]","go to [position] [of] <element>"],examples:["go back",'go to url "https://example.com"','go to url "https://example.com" in new window',"go to top of #header","go to bottom of #footer smoothly"],sideEffects:["navigation","scrolling"],category:"navigation",compatibility:"standard"}),Ji(t,n),s=t})());async function nl(e,t,r,n){const{args:s,modifiers:i}=e;if(!s||0===s.length)throw Error(n+" command requires a URL argument");const a=await t.evaluate(s[0],r)+"",o=i?.title?await t.evaluate(i.title,r)+"":void 0,c=function(e,t,r){const n=r?" Debug: "+r:"";if(null==e)throw Error(`[HyperFixi] ${t}: URL is required.${n}`);if("string"!=typeof e)throw Error(`[HyperFixi] ${t}: URL must be a string (got ${typeof e}: ${e+""}).${n}`);if(""===e.trim())throw Error(`[HyperFixi] ${t}: URL cannot be empty.${n}`);if("undefined"===e)throw Error(`[HyperFixi] ${t}: URL evaluated to string 'undefined' - check your expression.${n}`);if("null"===e)throw Error(`[HyperFixi] ${t}: URL evaluated to string 'null' - check your expression.${n}`);return e}(a,n,"argCount="+s.length);return{url:c,title:o}}const sl=ta((()=>{let e,t,r=[Xi({name:"push"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.commandName?.toLowerCase().includes("replace")?"replace":"push";return{...await nl(e,t,r,n+" url"),mode:n}}async execute(e,t){const{url:r,title:n,state:s,mode:i}=e;"push"===i?window.history.pushState(s||null,"",r):window.history.replaceState(s||null,"",r),n&&(document.title=n);return Ic(window,"push"===i?"pushurl":"replaceurl",{url:r,title:n,state:s}),{url:r,title:n,mode:i}}};return Yi(t,"HistoryCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Modify browser history URL without page reload",syntax:["push url <url>","push url <url> with title <title>","replace url <url>","replace url <url> with title <title>"],examples:['push url "/page/2"','push url "/search" with title "Search Results"','replace url "/search?q=test"','replace url "/page" with title "Updated Page"'],sideEffects:["navigation"],aliases:["replace"],category:"navigation",compatibility:"lokascript-extension"}),Ji(t,n),s=t})());const il=ta((()=>{let e,t,r=[Xi({name:"scroll"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.modifiers,s=n.of??e.args[0];if(!s&&!(void 0!==n.by||void 0!==n.direction))throw Error("scroll command requires a target");const i=s?this.resolveTarget(await t.evaluate(s,r),r):"undefined"!=typeof document?document.documentElement:null;if(!i)throw Error("scroll: target element not found");const a={target:i},o=async e=>e?await t.evaluate(e,r)+"":void 0,c=await o(n.position);c&&(a.position=c);const l=await o(n.behavior);"smooth"!==l&&"instant"!==l||(a.behavior=l);const u=await o(n.direction);if("up"!==u&&"down"!==u&&"left"!==u&&"right"!==u||(a.direction=u),void 0!==n.by){const e=await t.evaluate(n.by,r),s="number"==typeof e?e:parseFloat((e+"").replace(/px$/,""));a.offset=Number.isNaN(s)?0:s}return a}async execute(e,t){const{target:r,behavior:n}=e;if(void 0!==e.offset||void 0!==e.direction)return this.executeScrollBy(e);const s=this.scrollOptions(e.position);return n&&(s.behavior=n),"function"==typeof r.scrollIntoView&&r.scrollIntoView(s),{element:r,position:s.block??"start",smooth:"smooth"===n}}executeScrollBy(e){const{target:t,behavior:r}=e,n=e.direction??"down",s=e.offset??0,i={top:"up"===n?-s:"down"===n?s:0,left:"left"===n?-s:"right"===n?s:0};return r&&(i.behavior=r),"function"==typeof t.scrollBy&&t.scrollBy(i),{element:t,position:"start",smooth:"smooth"===r}}scrollOptions(e){const t={block:"start",inline:"nearest"};return"top"===e?t.block="start":"middle"===e?t.block="center":"bottom"===e?t.block="end":"nearest"===e?t.block="nearest":"left"===e?t.inline="start":"center"===e?t.inline="center":"right"===e&&(t.inline="end"),t}resolveTarget(e,t){if("object"==typeof e&&e&&e.nodeType)return e;if("string"!=typeof e)return null;if("me"===e&&xe(t.me))return t.me;if("it"===e&&xe(t.it))return t.it;if("you"===e&&xe(t.you))return t.you;if("body"===e&&"undefined"!=typeof document)return document.body;if("html"===e&&"undefined"!=typeof document)return document.documentElement;const r=Te(e,t);if(xe(r))return r;if("undefined"!=typeof document)try{const t=document.querySelector(e);if(xe(t))return t}catch{}return null}};return Yi(t,"ScrollCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Scroll an element into view (upstream _hyperscript 0.9.90)",syntax:["scroll to <target>","scroll to top of <target>","scroll to <target> smoothly","scroll [<target>] [up|down|left|right] by <n> [px]"],examples:["scroll to #top","scroll to bottom of #chat","scroll to me smoothly","scroll down by 200"],sideEffects:["scrolling"],category:"navigation",compatibility:"standard"}),Ji(t,n),s=t})());function al(e,t){const r=e.bodies?.[t];if(!r){throw Error(`${e.commandName??"command"}: argument ${t} is a body but was not compiled \u2014 run it through the runtime`)}return r}function ol(e,t){const r=[];for(let n=t;e.args.length>n;n++)r.push(al(e,n));return r}function cl(e,t){if("boolean"==typeof e)return e;if("function"==typeof e)return!0;if(e instanceof Promise)throw Error("Condition must be awaited - use await in the condition expression");if("string"==typeof e){if("me"===e)return!!t.me;if("it"===e)return!!t.it;if("you"===e)return!!t.you;const r=Te(e,t);return void 0!==r?!!r:!!e}return!!e}const ll=ta((()=>{let e,t,n=[Xi({name:"if"})],s=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,r){const n="unless"===e.commandName?.toLowerCase()?"unless":"if";if(!e.args||0===e.args.length)throw Error(n+" command requires a condition to evaluate");let s,i;if("unless"===n){if(2>e.args.length)throw Error("unless command requires a condition and at least one command");s=al(e,1)}else if(e.args.length>=2&&e.args[1]&&(s=al(e,1),i=3>e.args.length?void 0:al(e,2)),!s)throw Error('if command requires "then" branch with commands');return{mode:n,condition:await t.evaluate(e.args[0],r),thenCommands:s,elseCommands:i}}async execute(e,t){const{mode:n,condition:s,thenCommands:i,elseCommands:a}=e,o=cl(s,t);let c,l,u;if(("unless"===n?!o:o)?(c="then",u=i):a&&"if"===n?(c="else",u=a):c="none",u){const e=await u(t);if(!r(e))return e.error;l=e.value}return{mode:n,conditionResult:o,executedBranch:c,result:l}}};return Yi(t,"ConditionalCommand"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},n,{kind:"class",name:t.name,metadata:r},null,s),i=t=e.value,r&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),t.metadata=ea({description:"Conditional execution based on boolean expressions",syntax:["if <condition> then <commands>","if <condition> then <commands> else <commands>","unless <condition> <commands>"],examples:["if x > 5 then add .active","if user.isAdmin then show #adminPanel else hide #adminPanel","unless user.isLoggedIn showLoginForm"],sideEffects:["conditional-execution"],aliases:["unless"],category:"control-flow",compatibility:"standard"}),Ji(t,s),i=t})());let ul=(()=>{let t,n,s=[Xi({name:"repeat"})],i=[];var a=n=class{get metadata(){return a.metadata}async parseInput(e,t,r){let n,s,i;if(e.modifiers?.index){const s=await t.evaluate(e.modifiers.index,r);"string"==typeof s&&(n=s)}{const t=[];for(let r=e.args.length-1;r>=0;r--){const n=e.args[r];if("block"===n?.type&&n.commands&&(t.unshift(r),2===t.length))break}2===t.length?(s=al(e,t[0]),i=al(e,t[1])):1===t.length&&(s=al(e,t[0]))}const a=e.modifiers??{},o=e=>async function(e,t,r){if(!e)return;const n=e;if(Ya(n,"string"))return n.value;if(Ya(n,"literal")&&"string"==typeof n.value)return n.value;if(Ya(n,"identifier"))return n.name;const s=await t.evaluate(e,r);return"string"==typeof s?s:void 0}(e,t,r),c=await o(a.loopType)??null,l=!!a.bottomTested&&await t.evaluate(a.bottomTested,r);if("for"===c||a.for){const e=await o(a.for),c=a.in&&await t.evaluate(a.in,r);if(!e||void 0===c)throw Error("for loops require variable and collection");return{type:"for",variable:e,collection:Array.isArray(c)?c:[c],indexVariable:n,commands:s,elseCommands:i}}if("times"===c||a.times){const e=a.times&&await t.evaluate(a.times,r),o="number"==typeof e?e:parseInt(e+"",10);if(isNaN(o))throw Error("times loops require a count number");return{type:"times",count:o,indexVariable:n,commands:s,elseCommands:i}}if("while"===c||a.while){const e=a.while;if(!e)throw Error("while loops require a condition");return{type:"while",condition:e,indexVariable:n,commands:s,elseCommands:i,bottomTested:l}}if("until-event"===c||a.event){const e=await o(a.event);if(!e)throw Error("until-event loops require an event name");let c=r.me;if(a.from){const e=a.from,n=Ya(e,"identifier")?e.name:void 0;if("document"===n)c=document;else if("window"===n&&"undefined"!=typeof window)c=window;else{const e=await t.evaluate(a.from,r);e instanceof EventTarget?c=e:"document"===e?c=document:"undefined"!=typeof window&&e===window&&(c=window)}}return{type:"until-event",eventName:e,eventTarget:c,indexVariable:n,commands:s,elseCommands:i}}if("until"===c||a.until){const e=a.until;if(!e)throw Error("until loops require a condition");return{type:"until",condition:e,indexVariable:n,commands:s,elseCommands:i,bottomTested:l}}if("forever"===c)return{type:"forever",indexVariable:n,commands:s,elseCommands:i};throw Error("repeat command requires a loop type (for/times/while/until/forever)")}async execute(t,n){const{type:s,variable:i,collection:a,condition:o,count:c,indexVariable:l,commands:u,elseCommands:d,bottomTested:m,eventName:p,eventTarget:h}=t;let f,y;switch(s){case"for":({config:f,iterCtx:y}=function(e,t,r){return{config:{type:"for",shouldContinue:e=>(e.collection?.length??0)>e.index,beforeIteration:(e,t)=>{e.item=e.collection?.[e.index],e.itemVariable&&t.locals&&t.locals.set(e.itemVariable,e.item)}},iterCtx:{index:0,collection:e,itemVariable:t,indexVariable:r}}}(a,i,l));break;case"times":({config:f,iterCtx:y}=function(e,t){return{config:{type:"times",shouldContinue:e=>(e.count??0)>e.index,beforeIteration:(e,t)=>{Object.assign(t,{it:e.index+1})}},iterCtx:{index:0,count:e,indexVariable:t}}}(c,l));break;case"while":({config:f,iterCtx:y}=function(e,t,r,n){return{config:{type:"while",shouldContinue:()=>t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(o,cl,n,l));break;case"until":({config:f,iterCtx:y}=function(e,t,r,n){return{config:{type:"until",shouldContinue:()=>!t(e,r)},iterCtx:{index:0,conditionExpr:e,indexVariable:n}}}(o,cl,n,l));break;case"until-event":({config:f,iterCtx:y}=function(e,t,r){const n={index:0,eventFired:!1,indexVariable:r};return{config:{type:"until-event",shouldContinue:e=>!e.eventFired,eventSetup:{eventName:e,target:t,onEvent:()=>{n.eventFired=!0}}},iterCtx:n}}(p,h,l));break;case"forever":({config:f,iterCtx:y}=function(e,t=1e4){return{config:{type:"forever",maxIterations:t,shouldContinue:()=>!0},iterCtx:{index:0,indexVariable:e}}}(l));break;default:throw Error("Unknown repeat type: "+s)}if(m){const e=f.shouldContinue;f.shouldContinue=async t=>0===t.index||await e(t)}const g=await async function(e,t,n,s){const i=e.maxIterations??1e4;let a,o=0,c=!1;e.eventSetup&&e.eventSetup.target.addEventListener(e.eventSetup.eventName,e.eventSetup.onEvent,{once:!0});try{for(;i>o&&await e.shouldContinue(n);){e.beforeIteration&&await e.beforeIteration(n,t),n.indexVariable&&t.locals&&t.locals.set(n.indexVariable,o);const i=await s(t);if(!r(i)){const t=i.error;if("break"===t.type){c=!0;break}if("continue"===t.type){o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0));continue}return{iterations:o,lastResult:a,interrupted:c,signal:t}}a=i.value,o++,n.index=o,"until-event"===e.type&&await new Promise(e=>setTimeout(e,0))}}finally{e.eventSetup&&!n.eventFired&&e.eventSetup.target.removeEventListener(e.eventSetup.eventName,e.eventSetup.onEvent)}return{iterations:o,lastResult:a,interrupted:c}}(f,n,y,u??(async()=>e(void 0)));if(g.signal)return g.signal;if(0===g.iterations&&!g.interrupted&&d){const e=await d(n);if(!r(e))return e.error;const t=e.value;return Object.assign(n,{it:t}),{type:s,iterations:0,completed:!0,lastResult:t}}return Object.assign(n,{it:g.lastResult}),{type:s,iterations:g.iterations,completed:!g.interrupted,lastResult:g.lastResult,interrupted:g.interrupted}}};return Yi(n,"RepeatCommand"),(()=>{const e="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,t={value:n},s,{kind:"class",name:n.name,metadata:e},null,i),a=n=t.value,e&&Object.defineProperty(n,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:e})})(),n.metadata=ea({description:"Iteration in hyperscript - for-in, counted, conditional, event-driven, and infinite loops",syntax:["repeat for <var> in <collection> { <commands> }","repeat <count> times { <commands> }","repeat while <condition> { <commands> }","repeat until <condition> { <commands> }","repeat forever { <commands> }"],examples:["repeat for item in items { log item }",'repeat 5 times { log "hello" }',"repeat for item in items index i log i end"],sideEffects:["iteration","conditional-execution"],category:"control-flow",compatibility:"standard"}),Ji(n,i),a=n})();const dl=ta(ul);class ml{async parseInput(e,t,r){return{signalType:this.signalType}}async execute(e,t){return"exit"===this.signalType?{type:"exit",returnValue:void 0}:{type:this.signalType}}}const pl=ta((()=>{let e,t,r=[Xi({name:"break"})],n=[],s=ml;var i=t=class extends s{constructor(){super(...arguments),this.signalType="break"}get metadata(){return i.metadata}};return Yi(t,"BreakCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Exit from the current loop (repeat, for, while, until)",syntax:["break"],examples:["break","if found then break","repeat for item in items { if item == target then break }"],sideEffects:["control-flow"],category:"control-flow",compatibility:"standard"}),Ji(t,n),i=t})());const hl=ta((()=>{let e,t,r=[Xi({name:"continue"})],n=[],s=ml;var i=t=class extends s{constructor(){super(...arguments),this.signalType="continue"}get metadata(){return i.metadata}};return Yi(t,"ContinueCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Skip to the next iteration of the current loop",syntax:["continue"],examples:["continue","if item.isInvalid then continue","repeat for item in items { if item.skip then continue; process item }"],sideEffects:["control-flow"],category:"control-flow",compatibility:"standard"}),Ji(t,n),i=t})());const fl=ta((()=>{let e,t,r=[Xi({name:"halt"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(e.modifiers.the)return{target:r.event};const[n]=e.args;if(n){return{target:await t.evaluate(n,r)}}return{}}async execute(e,t){let r=e.target;if(("the"===r&&t.event||"object"==typeof r&&null!==r&&"the"===r.target&&t.event)&&(r=t.event),this.isEvent(r)){const e=r;return e.preventDefault(),e.stopPropagation(),{halted:!0,timestamp:Date.now(),eventHalted:!0}}return"halted"in t&&(t.halted=!0),{type:"halt"}}isEvent(e){return null!==e&&"object"==typeof e&&"preventDefault"in e&&"stopPropagation"in e}};return Yi(t,"HaltCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Stop command execution or prevent event defaults",syntax:["halt","halt the event"],examples:["halt","halt the event","if error then halt",'on click halt the event then log "clicked"'],sideEffects:["control-flow","event-prevention"],category:"control-flow",compatibility:"standard"}),Ji(t,n),s=t})());const yl=ta((()=>{let e,t,r=[Xi({name:"return"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)return{value:void 0};return{value:await t.evaluate(e.args[0],r)}}async execute(e,t){const{value:r}=e;return"returnValue"in t&&(t.returnValue=r),Object.assign(t,{it:r}),{type:"return",returnValue:r}}};return Yi(t,"ReturnCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Return a value from a command sequence or function, terminating execution",syntax:["return","return <value>"],examples:["return","return 42","return user.name","if found then return result"],sideEffects:["control-flow","context-mutation"],category:"control-flow",compatibility:"standard"}),Ji(t,n),s=t})());const gl=ta((()=>{let e,t,r=[Xi({name:"exit"})],n=[],s=ml;var i=t=class extends s{constructor(){super(...arguments),this.signalType="exit"}get metadata(){return i.metadata}};return Yi(t,"ExitCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Immediately terminate execution of the current event handler or behavior",syntax:["exit"],examples:["exit","if no draggedItem exit","on click if disabled exit"],sideEffects:["control-flow"],category:"control-flow",compatibility:"standard"}),Ji(t,n),i=t})());const vl=ta((()=>{let e,t,r=[Xi({name:"throw"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const[n]=e.args;if(!n)throw Error("throw command requires a message or error object");return{message:await t.evaluate(n,r)}}async execute(e,t){const{message:r}=e;let n;throw n=r instanceof Error?r:Error("string"==typeof r?r:r+""),n}};return Yi(t,"ThrowCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Throw an error with a specified message",syntax:["throw <message>"],examples:['throw "Invalid input"','if not valid then throw "Validation failed"'],sideEffects:["error-throwing","execution-termination"],category:"control-flow",compatibility:"standard"}),Ji(t,n),s=t})());const bl=ta((()=>{let e,t,r=[Xi({name:"call"})],n=[];var s=t=class{get metadata(){return s.metadata}parseInput(e,t,r){if(!e.args?.length)throw Error("call command requires an expression");return Promise.resolve({expression:e.args[0]})}async execute(e,t){const{expression:r}=e,n=t.locals?.get("__evaluator"),s=n?await n.evaluate(r,t):await Is(r,t);let i,a,o=!1;return"function"==typeof s?(a="function",i=s(),i instanceof Promise&&(o=!0,i=await i)):s instanceof Promise?(a="promise",o=!0,i=await s):(a="value",i=s),Object.assign(t,{it:i,result:i}),{result:i,wasAsync:o,expressionType:a}}};return Yi(t,"CallCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Evaluate an expression and store the result in the it variable",syntax:["call <expression>"],examples:["call myFunction()",'call fetch("/api/data")',"call element.focus()"],sideEffects:["function-execution","context-mutation"],category:"execution",compatibility:"standard"}),Ji(t,n),s=t})());const wl=ta((()=>{let e,t,r=[Xi({name:"focus"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:await oa(e.args,t,r,"focus",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.focus()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"FocusCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Focus an element (calls HTMLElement.focus())",syntax:["focus","focus <target>","focus on <target>"],examples:["focus","focus #search","focus on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),Ji(t,n),s=t})());const El=ta((()=>{let e,t,r=[Xi({name:"blur"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{targets:await oa(e.args,t,r,"blur",{fallbackModifierKey:"on"},e.modifiers)}}async execute(e,t){for(const t of e.targets)t.blur()}validate(e){if("object"!=typeof e||null===e)return!1;const t=e;return!!Array.isArray(t.targets)&&t.targets.every(e=>xe(e))}};return Yi(t,"BlurCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Remove focus from an element (calls HTMLElement.blur())",syntax:["blur","blur <target>","blur on <target>"],examples:["blur","blur #search","blur on <input/>"],sideEffects:["focus"],category:"execution",compatibility:"standard"}),Ji(t,n),s=t})());class kl{constructor(){this.name="pseudo-command"}get metadata(){return kl.metadata}async parseInput(e,t,r){if(1===e.args.length&&"objectLiteral"===e.args[0].type){const n=e.args[0].properties||[];let s,i,a="",o=[];for(const e of n){const n=e.value;switch(e.key?.name||e.key?.value){case"methodName":a=n?.value||await t.evaluate(n,r)+"";break;case"methodArgs":"arrayLiteral"===n?.type&&n.elements?o=await Promise.all(n.elements.map(e=>t.evaluate(e,r))):"literal"===n?.type&&Array.isArray(n.value)&&(o=await Promise.all(n.value.map(e=>t.evaluate(e,r))));break;case"preposition":const e=n?.value;e&&"null"!==e&&(s=e);break;case"target":case"targetExpression":i=await t.evaluate(n,r)}}if(!a)throw Error("pseudo-command requires method name");if(null==i)throw Error("pseudo-command requires a target expression");return{methodName:a,methodArgs:o,preposition:s,targetExpression:i}}if(2>e.args.length)throw Error("pseudo-command requires method name and target expression");const n=await t.evaluate(e.args[0],r)+"",s=Array.isArray(e.args[1])?await Promise.all(e.args[1].map(e=>t.evaluate(e,r))):[];let i,a;const o=["from","on","with","into","at","to"];for(const n of o)if(e.modifiers?.[n]){a=n,i=await t.evaluate(e.modifiers[n],r);break}if(!i&&e.args[2]&&(i=await t.evaluate(e.args[2],r)),!i)throw Error("pseudo-command requires a target expression");return{methodName:n,methodArgs:s,preposition:a,targetExpression:i}}async execute(e,t){const{methodName:r,methodArgs:n,targetExpression:s}=e;try{const e=await this.resolveTarget(s,t);if(null==e)throw Error("Target expression resolved to "+e);const i=this.resolveMethod(e,r);if(!i)throw Error(`Method "${r}" not found on target object`);if("function"!=typeof i)throw Error(`"${r}" is not a function (it's a ${typeof i})`);const a=await this.executeMethod(i,e,n);return t.locals.set("result",a),Object.assign(t,{it:a}),{result:a,methodName:r,target:e}}catch(e){throw Error("Pseudo-command failed: "+(e instanceof Error?e.message:e+""))}}async resolveTarget(e,t){return"object"==typeof e&&null!==e?e:"string"==typeof e?t.locals.has(e)?t.locals.get(e):t.variables?.has(e)?t.variables.get(e):t.globals.has(e)?t.globals.get(e):"me"===e&&t.me?t.me:"it"===e&&t.it?t.it:"document"===e?"undefined"!=typeof document?document:null:"window"===e?"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null:this.resolvePropertyPath(e,t):e}resolvePropertyPath(e,t){const r=e.split(".");let n="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:null;t.locals.has(r[0])?(n=t.locals.get(r[0]),r.shift()):t.variables?.has(r[0])?(n=t.variables.get(r[0]),r.shift()):t.globals.has(r[0])&&(n=t.globals.get(r[0]),r.shift());for(const e of r){if(null==n)return null;n=n[e]}return n}resolveMethod(e,t){if(!e)return null;if(t in e)return e[t];const r=t.split(".");let n=e;for(let e=0;r.length>e;e++){const t=r[e];if(null==n)return null;if(!(t in n))return null;if(n=n[t],e===r.length-1&&"function"==typeof n)return n}return null}async executeMethod(e,t,r){try{const n=e.apply(t,r);return n&&"object"==typeof n&&"then"in n?await n:n}catch(e){throw Error("Method execution failed: "+(e instanceof Error?e.message:e+""))}}}function xl(e){return xe(e)?e:e+""}kl.metadata=ea({description:"Treat a method on an object as a top-level command",syntax:["<method>(<args>) [(to|on|with|into|from|at)] <expression>"],examples:['getElementById("d1") from the document',"reload() the location of the window",'setAttribute("foo", "bar") on me',"foo() on me"],category:"execution",compatibility:"standard",sideEffects:["method-execution"]});class Cl{constructor(e){this.position=e}concat(e,t){const r=null==e?"":e+"",n=t+"";return"append"===this.position?r+n:n+r}pushInto(e,t){return"append"===this.position?e.push(t):e.unshift(t),e}async parseInput(e,t,r){if(!e.args?.length)throw Error(this.name+" requires content");const n=await t.evaluate(e.args[0],r),s=e.modifiers?.to??e.target;if(!s)return{kind:"implicit",content:n};const i=await zc(s,t,r,{scopeElements:async()=>xe(r.me)?[r.me]:[],selectorSource:!0,bareReference:!0});if(i)return function(e,t){switch(e.kind){case"selector":return{kind:"selector",selector:e.selector,content:t};case"attribute":return{kind:"attribute",elements:e.elements,name:e.name,content:t};case"property":return{kind:"property",property:e.target,content:t};case"variable":return{kind:"variable",name:e.name,scope:e.scope,content:t};default:throw Error(`unrequested write-target rung '${e.kind}'`)}}(i,n);const a=await t.evaluate(s,r),o=function(e){if(xe(e))return[e];if(Array.isArray(e)&&e.length>0&&e.every(e=>xe(e)))return e;if(e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item){const t=Array.from(e).filter(e=>xe(e));return t.length?t:null}return null}(a);return o?{kind:"elements",elements:o,content:n}:{kind:"value",target:a,content:n}}async execute(e,t){switch(e.kind){case"selector":return this.done(t,this.insertIntoSelector(e.selector,e.content));case"elements":return this.done(t,this.insertIntoEach(e.elements,e.content));case"attribute":{for(const t of e.elements)t.setAttribute(e.name,this.concat(t.getAttribute(e.name),e.content));const r=e.elements[0]?.getAttribute(e.name)??this.concat(null,e.content);return Object.assign(t,{it:r}),{target:"@"+e.name,value:r,targetType:"attribute"}}case"property":{const r=oo(e.property),n=this.combineValue(r,e.content);return xe(r)||co(e.property,n),Object.assign(t,{it:n}),{target:e.property.element,value:n,targetType:"property"}}case"variable":return this.executeVariable(e,t);case"value":{const r=this.combineValue(e.target,e.content,!0);return Object.assign(t,{it:r}),{target:e.target,value:r,targetType:this.targetTypeOf(e.target)}}case"implicit":return this.execImplicit(t,e.content)}}insertIntoSelector(e,t){return this.insertIntoEach(je(e),t)}insertIntoEach(e,t){const r=xl(t);for(const t of e)Ra(t,r,this.position);return e}combineValue(e,t,r=!1){if(Array.isArray(e))return this.pushInto(e,t);if(e instanceof Set)return e.add(t),e;if(xe(e))return Ra(e,xl(t),this.position),e;if(r&&null!=e&&"string"!=typeof e&&"number"!=typeof e)throw Error(`Unable to ${this.name} a value!`);return this.concat(e,t)}targetTypeOf(e){return Array.isArray(e)?"array":e instanceof Set?"set":xe(e)?"element":"result"}executeVariable(e,t){if("me"===e.name||"you"===e.name){const r="me"===e.name?t.me:t.you;if(xe(r))return Ra(r,xl(e.content),this.position),Object.assign(t,{it:r}),{target:r,value:r,targetType:"element"}}if("it"===e.name||"result"===e.name)return this.execImplicit(t,e.content);const r=Te(e.name,t,e.scope),n=this.combineValue(r,e.content);return Array.isArray(r)||r instanceof Set||xe(r)||Le(e.name,n,t,e.scope),Object.assign(t,{it:n}),{target:e.name,value:n,targetType:this.targetTypeOf(r)}}execImplicit(e,t){const r=e.it??e.result,n=this.combineValue(r,t);return Object.assign(e,{it:n,result:n}),{target:"result",value:n,targetType:this.targetTypeOf(r)}}done(e,t){const r=1===t.length?t[0]:t;return Object.assign(e,{it:r}),{target:r,value:r,targetType:"element"}}}const Al=ta((()=>{let e,t,r=[Xi({name:"append"})],n=[],s=Cl;var i=t=class extends s{get metadata(){return i.metadata}constructor(){super("append")}};return Yi(t,"AppendCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Add content to the end of a string, array, Set, or HTML element",syntax:["append <content>","append <content> to <target>"],examples:['append "Hello"','append "World" to greeting',"append item to myArray",'append "<p>New</p>" to #content','append " (edited)" to #title\'s textContent'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"standard"}),Ji(t,n),i=t})());const Sl=ta((()=>{let e,t,r=[Xi({name:"prepend"})],n=[],s=Cl;var i=t=class extends s{get metadata(){return i.metadata}constructor(){super("prepend")}};return Yi(t,"PrependCommand"),(()=>{const a="function"==typeof Symbol&&Symbol.metadata?Object.create(s[Symbol.metadata]??null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:a},null,n),i=t=e.value,a&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:a})})(),t.metadata=ea({description:"Add content to the start of a string, array, Set, or HTML element",syntax:["prepend <content>","prepend <content> to <target>"],examples:['prepend "Hello"','prepend "World" to greeting',"prepend item to myArray",'prepend "<p>First</p>" to #content'],sideEffects:["data-mutation","dom-mutation"],category:"content",compatibility:"lokascript-extension"}),Ji(t,n),i=t})());const Tl=ta((()=>{let e,t,r=[Xi({name:"transition"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args?.length)throw Error("transition requires property and value");let n,s;const i=await t.evaluate(e.args[0],r),a=e=>Array.isArray(e)||Ae(e)?e[0]:e,o=a(i);if(xe(o)||"string"==typeof i&&/^[#.]|^(?:me|it|you)$/.test(i))s=o,n=await t.evaluate(e.args[1],r)+"";else{if(e.args.length>=2)throw Error("transition: target element not found");if(null==i){const i=function(e){if(!e||"object"!=typeof e)return null;const t=e;if("identifier"===t.type&&"string"==typeof t.name&&t.name)return{property:t.name};if("propertyAccess"===t.type||"memberExpression"===t.type){const e=t.property,r="string"==typeof e?e:"string"==typeof e?.name?e.name:void 0;if(r)return{property:r,objectNode:t.object}}return null}(e.args[0]);if(!i)throw Error("transition requires a CSS property");if(n=i.property,void 0!==i.objectNode){const e=a(await t.evaluate(i.objectNode,r));xe(e)&&(s=e)}}else n=i+""}if(!n||"undefined"===n||"null"===n)throw Error("transition requires a CSS property");if(!e.modifiers?.to)throw Error('transition requires "to <value>"');let c=await t.evaluate(e.modifiers.to,r);void 0===c&&"identifier"===e.modifiers.to.type&&(c=e.modifiers.to.name);const l={property:n,value:c};return void 0!==s&&(l.target=s),e.modifiers?.over&&(l.duration=await t.evaluate(e.modifiers.over,r)),e.modifiers?.with&&(l.timingFunction=await t.evaluate(e.modifiers.with,r)+""),l}async execute(e,t){let{property:r}=e;const{target:n,value:s,duration:i,timingFunction:a}=e;r.startsWith("*")&&(r=r.substring(1)),r=r.replace(/([A-Z])/g,"-$1").toLowerCase();const o=na(n,t,"transition"),c=Va(i,300),l=getComputedStyle(o).getPropertyValue(r),u=o.style.transition,d=`${r} ${c}ms ${a||"ease"}`;o.style.transition=u?`${u}, ${d}`:d;let m=s+"",p=!1;if("initial"===m||"inherit"===m||"unset"===m||"revert"===m){const e=o.style.getPropertyValue(r);o.style.removeProperty(r),m=getComputedStyle(o).getPropertyValue(r),e&&o.style.setProperty(r,e),p=!0}o.style.setProperty(r,m);const h=await function(e,t,r){return new Promise(n=>{const s=r=>{r.target===e&&r.propertyName===t&&a({completed:!0,cancelled:!1})},i=r=>{r.target===e&&r.propertyName===t&&a({completed:!1,cancelled:!0})},a=Wc(()=>{e.removeEventListener("transitionend",s),e.removeEventListener("transitioncancel",i),clearTimeout(o)},n);e.addEventListener("transitionend",s),e.addEventListener("transitioncancel",i);const o=setTimeout(()=>{a({completed:!0,cancelled:!1})},r+50)})}(o,r,c);return o.style.transition=u,p&&o.style.removeProperty(r),{element:o,property:r,fromValue:l,toValue:m,duration:c,completed:h.completed}}};return Yi(t,"TransitionCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Animate CSS properties using CSS transitions",syntax:"transition [<target>] <property> to <value> [over <duration>] [with <timing>]",examples:["transition opacity to 0.5","transition my *opacity to 0 over 200ms","transition #box's *opacity to 0 over 200ms","transition left to 100px over 500ms","transition background-color to red over 1s with ease-in-out"],sideEffects:["style-change","timing"],category:"animation",compatibility:"standard"}),Ji(t,n),s=t})());const Ll=ta((()=>{let e,t,r=[Xi({name:"measure"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){let n,s,i;if(e.args?.length){const i=e.args[0];if("identifier"===i.type&&i.name){const a=i.name.toLowerCase();if("me"===a||"it"===a||"you"===a){const a=await t.evaluate(i,r);if(xe(a)&&(n=a,e.args.length>1)){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else s=i.name}else{const a=await t.evaluate(i,r);if(xe(a)||"string"==typeof a&&/^[#.]/.test(a)){if(n=a,e.args.length>1){const n=e.args[1];s="identifier"===n.type?n.name:await t.evaluate(n,r)+""}}else"string"==typeof a&&(s=a)}}e.modifiers?.set&&(i=await t.evaluate(e.modifiers.set,r)+"");const a={};return void 0!==n&&(a.target=n),void 0!==s&&(a.property=s),void 0!==i&&(a.variable=i),a}async execute(e,t){const r=na(e.target,t,"measure"),n=e.property||"width",s=this.getMeasurement(r,n);return e.variable&&t.locals&&t.locals.set(e.variable,s.value),Object.assign(t,{it:s.value}),{result:s.value,wasAsync:!1,element:r,property:n,value:s.value,unit:s.unit,stored:!!e.variable}}getMeasurement(e,t){const r=getComputedStyle(e);if(t.startsWith("*")){const e=r.getPropertyValue(t.substring(1)),n=parseFloat(e);if(!isNaN(n)){const t=e.match(/([a-zA-Z%]+)$/);return{value:n,unit:t?t[1]:""}}return{value:e,unit:""}}const n=t.toLowerCase(),s=e.getBoundingClientRect(),i={width:()=>s.width,height:()=>s.height,top:()=>s.top,left:()=>s.left,right:()=>s.right,bottom:()=>s.bottom,x:()=>e.offsetLeft,y:()=>e.offsetTop,clientwidth:()=>e.clientWidth,"client-width":()=>e.clientWidth,clientheight:()=>e.clientHeight,"client-height":()=>e.clientHeight,offsetwidth:()=>e.offsetWidth,"offset-width":()=>e.offsetWidth,offsetheight:()=>e.offsetHeight,"offset-height":()=>e.offsetHeight,scrollwidth:()=>e.scrollWidth,"scroll-width":()=>e.scrollWidth,scrollheight:()=>e.scrollHeight,"scroll-height":()=>e.scrollHeight,scrolltop:()=>e.scrollTop,"scroll-top":()=>e.scrollTop,scrollleft:()=>e.scrollLeft,"scroll-left":()=>e.scrollLeft,offsettop:()=>e.offsetTop,"offset-top":()=>e.offsetTop,offsetleft:()=>e.offsetLeft,"offset-left":()=>e.offsetLeft};if(i[n])return{value:i[n](),unit:"px"};const a=r.getPropertyValue(t),o=parseFloat(a);if(!isNaN(o)){const e=a.match(/([a-zA-Z%]+)$/);return{value:o,unit:e?e[1]:"px"}}return{value:0,unit:"px"}}};return Yi(t,"MeasureCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Measure DOM element dimensions, positions, and properties",syntax:["measure","measure <property>","measure <target> <property>"],examples:["measure","measure width","measure #element height","measure x and set dragX"],sideEffects:["data-mutation"],category:"animation",compatibility:"standard"}),Ji(t,n),s=t})());const Ol=ta((()=>{let e,t,r=[Xi({name:"settle"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){let n,s;const[i]=e.args;if(i){const e=await t.evaluate(i,r);(xe(e)||"string"==typeof e&&(e.startsWith("#")||e.startsWith(".")||"me"===e||"it"===e||"you"===e))&&(n=e)}e.modifiers?.for&&(s=await t.evaluate(e.modifiers.for,r));const a={};return void 0!==n&&(a.target=n),void 0!==s&&(a.timeout=s),a}async execute(e,t){const{target:r,timeout:n}=e,s=na(r,t,"settle"),i=Va(n,5e3),a=Date.now(),o=getComputedStyle(s),c=Ba(o.transitionDuration),l=Ba(o.transitionDelay),u=Ba(o.animationDuration),d=Ba(o.animationDelay),m=Fa(c,l),p=Fa(u,d),h=Math.max(m,p);var f,y,g;return{element:s,settled:(await(f=s,y=h,g=i,y>0?new Promise(e=>{const t=e=>{e.target===f&&n({completed:!0,type:"transition"})},r=e=>{e.target===f&&n({completed:!0,type:"animation"})},n=Wc(()=>{f.removeEventListener("transitionend",t),f.removeEventListener("animationend",r),clearTimeout(s),clearTimeout(i)},e);f.addEventListener("transitionend",t),f.addEventListener("animationend",r);const s=setTimeout(()=>{n({completed:!0,type:"timeout"})},y+50),i=setTimeout(()=>{n({completed:!1,type:"timeout"})},g)}):Promise.resolve({completed:!0,type:"timeout"}))).completed,timeout:i,duration:Date.now()-a}}};return Yi(t,"SettleCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Wait for CSS transitions and animations to complete",syntax:"settle [<target>] [for <timeout>]",examples:["settle","settle #animated-element","settle for 3000"],sideEffects:["timing"],category:"animation",compatibility:"standard"}),Ji(t,n),s=t})());const Nl=ta((()=>{let e,t,n=[Xi({name:"start"})],s=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,r){const n=ol(e,0);let s;if(e.modifiers?.transitionName){const n=await t.evaluate(e.modifiers.transitionName,r);s="string"==typeof n?n:(n??"")+""}return{transitionName:s,body:n}}async execute(e,t){let n,s=0;const i=async()=>{for(const i of e.body){const e=await i(t);if(!r(e)){n=e.error;break}s++}};if(!Qo())return await i(),n??{usedViewTransition:!1,commandsExecuted:s};const a=e.transitionName?{transitionName:e.transitionName}:void 0;return await ec(i,a),n??{usedViewTransition:!0,commandsExecuted:s}}};return Yi(t,"StartViewTransitionCommand"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},n,{kind:"class",name:t.name,metadata:r},null,s),i=t=e.value,r&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),t.metadata=ea({description:"Wrap a block of commands in document.startViewTransition()",syntax:["start view transition [using <type>] <body> end"],examples:["start view transition add .highlight to me end",'start view transition using "slide" add .active to #panel end','start view transition using "slide" then put result into #panel end'],sideEffects:["animation","dom-mutation"],category:"animation",compatibility:"standard"}),Ji(t,s),i=t})());let Pl=(()=>{let e,t,r=[Xi({name:"take"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(!e.args||0===e.args.length)throw Error('take requires property, "from", and source');const{value:n}=await Sa(e.args[0],t,r),s=n+"",i=e.modifiers?.from?await t.evaluate(e.modifiers.from,r):void 0;let a;if(!a&&e.modifiers?.for&&(a=await t.evaluate(e.modifiers.for,r)),void 0===i&&!s.startsWith("."))throw Error('take requires property, "from", and source');return{property:s,source:i,target:a}}async execute(e,t){const r=e.property.trim();if(r.startsWith(".")){const n=r.substring(1);let s;if(null!=e.source)s=sa(e.source,t);else{const e=t.me?.ownerDocument??("undefined"!=typeof document?document:null);s=e?Array.from(e.querySelectorAll("."+n)):[]}for(const e of s)e.classList.remove(n);const i=sa(e.target,t);if(0===i.length)throw Error("take: no recipient element found");for(const e of i)e.classList.add(n);return{targetElement:i[0],property:e.property,value:n}}const n=na(this.firstOf(e.source),t,"take"),s=na(e.target?this.firstOf(e.target):void 0,t,"take"),i=this.takeProperty(n,e.property);return this.putProperty(s,e.property,i),{targetElement:s,property:e.property,value:i}}firstOf(e){const t=null!==e&&"object"==typeof e&&"number"==typeof e.length&&"function"==typeof e.item;if(Array.isArray(e)||t){const t=e[0];if(void 0===t)throw Error("take: no matching elements");return t}return e}takeProperty(e,t){const r=t.trim(),n=r.toLowerCase();if("class"===n||"classes"===n){const t=Array.from(e.classList);return e.className="",t}if(r.startsWith(".")){const t=r.substring(1);return e.classList.contains(t)?(e.classList.remove(t),t):null}if(r.startsWith("@")){const t=r.substring(1),n=e.getAttribute(t);return e.removeAttribute(t),n}if(r.startsWith("data-")){const t=e.getAttribute(r);return e.removeAttribute(r),t}if("id"===n){const t=e.id;return e.id="",t}if("title"===n){const t=e.title;return e.title="",t}if("value"===n&&"value"in e){const t=e.value;return e.value="",t}const s=r.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());if(r.includes("-")||s in e.style||r in e.style){let t;return s in e.style?(t=e.style[s],e.style[s]=""):r in e.style?(t=e.style[r],e.style[r]=""):(t=e.style.getPropertyValue(r),e.style.removeProperty(r)),t}const i=e.getAttribute(t);return null!==i?(e.removeAttribute(t),i):null}putProperty(e,t,r){if(null==r)return;const n=t.trim(),s=n.toLowerCase();if("class"===s||"classes"===s)return void(Array.isArray(r)?r.forEach(t=>t&&"string"==typeof t&&e.classList.add(t)):"string"==typeof r&&(e.className=r));if(n.startsWith("."))return void(r&&e.classList.add(n.substring(1)));if(n.startsWith("@"))return void e.setAttribute(n.substring(1),r+"");if(n.startsWith("data-"))return void e.setAttribute(n,r+"");if("id"===s)return void(e.id=r+"");if("title"===s)return void(e.title=r+"");if("value"===s&&"value"in e)return void(e.value=r+"");const i=n.replace(/-([a-z])/g,(e,t)=>t.toUpperCase());n.includes("-")||i in e.style||n in e.style?i in e.style?e.style[i]=r+"":n in e.style?e.style[n]=r+"":e.style.setProperty(n,r+""):e.setAttribute(t,r+"")}};return Yi(t,"TakeCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Move classes, attributes, and properties from one element to another",syntax:["take <class> [from <source>] [for <recipient>]","take <property> from <source>","take <property> from <source> and put it on <target>"],examples:["take .active from .tab for me","take class from <#source/>","take @data-value from <.source/> and put it on <#target/>"],sideEffects:["dom-mutation","property-transfer"],category:"animation",compatibility:"standard"}),Ji(t,n),s=t})();const Il=ta(Pl);const jl=ta((()=>{let e,t,r=[Xi({name:"js"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){let n,s;if(0===e.args.length)throw Error("js command requires JavaScript code");const i=e.args[0],a=e.args[1];if(i&&"literal"===i.type&&"string"==typeof i.value)n=i.value;else{if(!i||void 0===i.value)throw Error("js command requires JavaScript code");n=i.value+""}a&&"arrayLiteral"===a.type&&Array.isArray(a.elements)&&(s=a.elements.map(e=>"string"==typeof e.value?e.value:e.value+"").filter(e=>e&&e.length>0));const o={code:n};return s&&s.length>0&&(o.parameters=s),o}async execute(e,t){const{code:r,parameters:n=[]}=e;if(!r.trim())return{result:void 0,executed:!1,codeLength:r.length,parameters:n,preserveArrayResult:!0};try{const e=this.createExecutionContext(t,n),s=Function(...Object.keys(e),r),i=await s(...Object.values(e));return void 0!==i&&Object.assign(t,{it:i}),{result:i,executed:!0,codeLength:r.length,parameters:n,preserveArrayResult:!0}}catch(e){throw Error("JavaScript execution failed: "+(e instanceof Error?e.message:"Unknown error"))}}createExecutionContext(e,t){return{me:e.me,it:e.it,you:e.you,locals:e.locals,globals:e.globals,variables:e.variables,console:console,document:"undefined"!=typeof document?document:void 0,window:"undefined"!=typeof window?window:void 0,...t.reduce((t,r)=>{let n=e.locals?.get(r);return void 0===n&&(n=e.variables?.get(r)),void 0===n&&(n=e[r]),t[r]=n,t},{})}}};return Yi(t,"JsCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Execute inline JavaScript code with access to hyperscript context",syntax:["js <code> end","js(param1, param2) <code> end"],examples:['js console.log("Hello") end',"js(x, y) return x + y end",'js me.style.color = "red" end'],sideEffects:["code-execution","data-mutation"],category:"advanced",compatibility:"standard"}),Ji(t,n),s=t})());const Rl=ta((()=>{let e,t,r=[Xi({name:"default"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("default command requires a target");const n=await this.extractValue(e,t,r),s=e.args[0],i=function(e){if("contextReference"!==e?.type)return null;const t=e.name;return"string"!=typeof t?null:t.startsWith(":")?{name:t.slice(1),scope:"element"}:t.startsWith("$")?{name:t.slice(1),scope:"global"}:null}(s);if(i)return{type:"variable",name:i.name,value:n,scope:i.scope};const a=await zc(s,t,r,{scopeElements:async()=>r.me?[r.me]:[],bareReference:!0});if(a)return function(e,t){switch(e.kind){case"attribute":return{type:"attribute",elements:e.elements,name:e.name,value:t};case"property":return{type:"property",element:e.target.element,property:e.target.property,value:t};case"variable":{const r=e.name.startsWith("$"),n=r?e.name.slice(1):e.name,s=r?"global":e.scope;return{type:"variable",name:n,value:t,...s?{scope:s}:{}}}default:throw Error(`default: unrequested write-target rung '${e.kind}'`)}}(a,n);const o=await t.evaluate(e.args[0],r);if(xe(o))return{type:"element",element:o,value:n};if(Array.isArray(o)&&xe(o[0]))return{type:"element",element:o[0],value:n};if("string"==typeof o)return{type:"variable",name:o,value:n};throw Error("Invalid target type: "+typeof o)}async extractValue(e,t,r){if(e.modifiers?.to)return t.evaluate(e.modifiers.to,r);const n=e.args[1];if(n)return t.evaluate(n,r);throw Error('default command requires a value (use "to <value>")')}async execute(e,t){switch(e.type){case"variable":return this.defaultVariable(t,e.name,e.value,e.scope);case"attribute":return this.defaultAttribute(t,e.elements,e.name,e.value);case"property":return this.defaultElementProperty(t,e.element,e.property,e.value);case"element":return this.defaultElementValue(t,e.element,e.value)}}defaultVariable(e,t,r,n){const s=Te(t,e,n);return null!=s?{target:t,value:r,wasSet:!1,existingValue:s,targetType:"variable"}:(Le(t,r,e,n),Object.assign(e,{it:r}),{target:t,value:r,wasSet:!0,targetType:"variable"})}defaultAttribute(e,t,r,n){if(0===t.length)throw Error("No element context available for attribute default");const s=t.filter(e=>null===e.getAttribute(r));if(0===s.length)return{target:"@"+r,value:n,wasSet:!1,existingValue:t[0].getAttribute(r),targetType:"attribute"};for(const e of s)e.setAttribute(r,n+"");return Object.assign(e,{it:n}),{target:"@"+r,value:n,wasSet:!0,targetType:"attribute"}}defaultElementProperty(e,t,r,n){const s=function(e,t){if(t.startsWith("@"))return e.getAttribute(t.substring(1));switch(t){case"textContent":return e.textContent;case"innerHTML":return e.innerHTML;case"innerText":return e.innerText;case"id":return e.id;case"className":return e.className;case"value":return"value"in e?e.value:void 0;case"checked":return"checked"in e?e.checked:void 0}if(t.includes(".")){const r=t.split(".");let n=e;for(const e of r){if(null==n)break;n=n[e]}return n}return t.includes("-")||t in e.style?e.style.getPropertyValue(t)||e.style[t]:e[t]}(t,r);return Ja(s)?(Qa(t,r,n),Object.assign(e,{it:n}),{target:r,value:n,wasSet:!0,targetType:"property"}):{target:r,value:n,wasSet:!1,existingValue:s,targetType:"property"}}defaultElementValue(e,t,r){const n=function(e){return"value"in e?e.value:e.textContent}(t);return Ja(n)?(function(e,t){"value"in e?e.value=t+"":e.textContent=t+""}(t,r),Object.assign(e,{it:r}),{target:"element",value:r,wasSet:!0,targetType:"element"}):{target:"element",value:r,wasSet:!1,existingValue:n,targetType:"element"}}};return Yi(t,"DefaultCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Set a value only if it doesn't already exist",syntax:["default <expression> to <expression>"],examples:['default myVar to "fallback"','default @data-theme to "light"','default my innerHTML to "No content"'],sideEffects:["data-mutation","dom-mutation"],category:"data",compatibility:"standard"}),Ji(t,n),s=t})());const Ml=ta((()=>{let e,t,n=[Xi({name:"tell"})],s=[];var i=t=class{get metadata(){return i.metadata}async parseInput(e,t,r){if(2>e.args.length)throw Error("tell command requires a target and at least one command");return{target:await t.evaluate(e.args[0],r),commands:ol(e,1)}}async execute(e,t){const{target:n,commands:s}=e,i=sa(n,t);if(0===i.length)throw Error("tell command found no target elements");const a=[];for(const e of i){const n={...t,me:e,you:e};for(const e of s){let t;try{t=await e(n)}catch(e){throw Error("Command execution failed in tell block: "+(e instanceof Error?e.message:"Unknown error"))}if(!r(t))return t.error;const s=t.value;a.push(s),Object.assign(n,{it:s})}}return{targetElements:i,commandResults:a,executionCount:i.length*s.length}}};return Yi(t,"TellCommand"),(()=>{const r="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},n,{kind:"class",name:t.name,metadata:r},null,s),i=t=e.value,r&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:r})})(),t.metadata=ea({description:"Execute commands in the context of target elements",syntax:["tell <target> <command> [<command> ...]"],examples:["tell #sidebar hide","tell .buttons add .disabled","tell closest <form/> submit"],sideEffects:["context-switching","command-execution"],category:"utility",compatibility:"standard"}),Ji(t,s),i=t})());const $l=ta((()=>{let e,t,r=[Xi({name:"copy"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const[n]=e.args;if(!n)throw Error("copy command requires a source (text or element)");return{source:await t.evaluate(n,r),format:"text"}}async execute(e,t){const{source:r,format:n="text"}=e,s=this.extractText(r,n,t);if("undefined"!=typeof navigator&&navigator.clipboard)try{return await navigator.clipboard.writeText(s),this.dispatchCopyEvent(t,"copy:success",{text:s,method:"clipboard-api"}),{success:!0,text:s,format:n,method:"clipboard-api"}}catch{}try{if(this.copyUsingExecCommand(s))return this.dispatchCopyEvent(t,"copy:success",{text:s,method:"execCommand"}),{success:!0,text:s,format:n,method:"execCommand"}}catch{}return this.dispatchCopyEvent(t,"copy:error",{text:s,error:"All copy methods failed"}),{success:!1,text:s,format:n,method:"fallback"}}extractText(e,t,r){if("string"==typeof e)return e;if(xe(e))return"html"===t?e.outerHTML:e.textContent||"";if(e===r.me&&xe(r.me)){const e=r.me;return"html"===t?e.outerHTML:e.textContent||""}return e+""}copyUsingExecCommand(e){if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.style.cssText="position:fixed;top:0;left:-9999px",t.setAttribute("readonly",""),document.body.appendChild(t);try{t.select(),t.setSelectionRange(0,e.length);const r=document.execCommand("copy");return document.body.removeChild(t),r}catch{return t.parentNode?.removeChild(t),!1}}dispatchCopyEvent(e,t,r){if(xe(e.me)){const n=new CustomEvent(t,{detail:r,bubbles:!0,cancelable:!1});e.me.dispatchEvent(n)}}};return Yi(t,"CopyCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Copy text or element content to the clipboard",syntax:["copy <source>","copy <source> to clipboard"],examples:['copy "Hello World"',"copy #code-snippet","copy my textContent"],sideEffects:["clipboard-write","custom-events"],category:"utility",compatibility:"lokascript-extension"}),Ji(t,n),s=t})());function Hl(e,t,r,n){return e.evaluate(function(e,t){if(!e)throw Error(t+" is required");return e}(r,n),t)}let ql=(()=>{let e,t,r=[Xi({name:"pick"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){const n=e.modifiers?.variant,s=n?.value;if("first"===s||"last"===s){const n=await t.evaluate(e.args[0],r),i=await Hl(t,r,e.modifiers.count,"pick: count");if(!Array.isArray(n))throw Error(`pick ${s}: source must be an array, got ${typeof n}`);if("number"!=typeof i||!Number.isFinite(i))throw Error(`pick ${s}: count must be a number, got ${typeof i}`);return{variant:s,array:n,count:i}}if("random"===s){const n=await t.evaluate(e.args[0],r);if(!Array.isArray(n))throw Error("pick random: source must be an array");let s;if(e.modifiers.count){const n=await t.evaluate(e.modifiers.count,r);if("number"!=typeof n||!Number.isFinite(n))throw Error("pick random: count must be a number, got "+typeof n);s=n}return{variant:"random",array:n,count:s}}if("range"===s){const n=await t.evaluate(e.args[0],r);if(!Array.isArray(n)&&"string"!=typeof n)throw Error("pick items: source must be an array or string");const s=e.modifiers.rangeStart,i="start"===s?.value?"start":await Hl(t,r,e.modifiers.rangeStart,"pick: start"),a="start"===i?"start":Number(i);let o;if(e.modifiers.rangeEnd){if("end"===e.modifiers.rangeEnd.value)o="end";else{const n=await t.evaluate(e.modifiers.rangeEnd,r);o=Number(n)}}const c=e.modifiers.rangeMode;return{variant:"range",array:n,rangeStart:a,rangeEnd:o,rangeMode:c?.value??"default"}}if("match"===s||"matches"===s){const n=await t.evaluate(e.args[0],r);if("string"!=typeof n)throw Error(`pick ${s}: source must be a string, got ${typeof n}`);const i=await Hl(t,r,e.modifiers.regex,"pick: regex"),a="string"==typeof i?i:i+"",o=e.modifiers.flags,c=o?.value;return{variant:s,source:n,regex:a,flags:c}}if(0===e.args.length)throw Error("pick command requires items to choose from");return{variant:"random",items:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.variant??"random";if("first"===r){const r=e.array??[],n=r.slice(0,e.count??0);return Object.assign(t,{it:n}),{selectedItem:n,sourceLength:r.length,sourceType:"array",variant:"first"}}if("last"===r){const r=e.array??[],n=e.count??0,s=n>0?r.slice(-n):[];return Object.assign(t,{it:s}),{selectedItem:s,sourceLength:r.length,sourceType:"array",variant:"last"}}if("range"===r){const r=e.array??[];let n="start"===e.rangeStart?0:e.rangeStart??0,s=void 0===e.rangeEnd?n+1:"end"===e.rangeEnd?r.length:e.rangeEnd;"inclusive"===e.rangeMode?s++:"exclusive"===e.rangeMode&&n++;const i=r.slice(n,s);return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:r.length,sourceType:"array",variant:"range"}}if("match"===r){const r=e.source??"",n=RegExp(e.regex??"",e.flags).exec(r);return Object.assign(t,{it:n}),{selectedItem:n,sourceLength:r.length,sourceType:"string",variant:"match"}}if("matches"===r){const r=e.source??"",n=e.flags??"g",s=RegExp(e.regex??"",n.includes("g")?n:"g"+n),i=Array.from(r.matchAll(s));return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:r.length,sourceType:"string",variant:"matches"}}const n=e.items??e.array??[];if(0===n.length)throw Error("Cannot pick from empty collection");if(void 0===e.count){const r=Math.floor(Math.random()*n.length),s=n[r];return Object.assign(t,{it:s}),{selectedItem:s,selectedIndex:r,sourceLength:n.length,sourceType:e.items?"items":"array",variant:"random"}}const s=n.slice(),i=[];for(let t=0;e.count>t&&s.length>0;t++){const e=Math.floor(Math.random()*s.length);i.push(s.splice(e,1)[0])}return Object.assign(t,{it:i}),{selectedItem:i,sourceLength:n.length,sourceType:e.items?"items":"array",variant:"random"}}};return Yi(t,"PickCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Select from a collection (first/last/random/range/regex match)",syntax:["pick first <count> of <expr>","pick last <count> of <expr>","pick random [<count>] of <expr>","pick items <i> to <j> of <expr>","pick match of <regex> from <expr>","pick from <array>","pick <item1>, <item2>, ..."],examples:["pick first 3 of items","pick last 2 of items","pick random 2 of items","pick items 1 to 3 of items",'pick match of "[0-9]+" from text',"pick from colors",'pick "red", "green", "blue"'],sideEffects:["random-selection"],category:"utility",compatibility:"standard"}),Ji(t,n),s=t})();const Wl=ta(ql);let Vl=(()=>{let e,t,r=[Xi({name:"beep"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){if(0===e.args.length)return{expressions:[]};return{expressions:await Promise.all(e.args.map(e=>t.evaluate(e,r)))}}async execute(e,t){const r=e.expressions||[];if(0===r.length)return this.debugContext(t),{expressionCount:0,debugged:!0,outputs:[]};const n=[];console.group("\ud83d\udd14 beep! Debug Output");for(const e of r){const t=this.debugExpression(e);n.push(t)}return console.groupEnd(),{expressionCount:r.length,debugged:!0,outputs:n}}debugContext(e){console.group("\ud83d\udd14 beep! Context Debug"),console.groupEnd()}debugExpression(e){return{value:e,type:this.getType(e),representation:this.getRepresentation(e)}}getType(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":xe(e)?"HTMLElement":e instanceof Element?"Element":e instanceof Node?"Node":e instanceof Error?"Error":e instanceof Date?"Date":e instanceof RegExp?"RegExp":typeof e}getRepresentation(e){if(null===e)return"null";if(void 0===e)return"undefined";if(Array.isArray(e))return`Array(${e.length}) [${e.slice(0,3).map(e=>this.getRepresentation(e)).join(", ")}${e.length>3?"...":""}]`;if(xe(e)){const t=e;return`<${t.tagName.toLowerCase()}${t.id?"#"+t.id:""}${t.className?"."+t.className.split(" ").join("."):""}/>`}if(e instanceof Error)return"Error: "+e.message;if("string"==typeof e)return e.length>50?`"${e.substring(0,47)}..."`:`"${e}"`;if("object"==typeof e)try{const t=Object.keys(e);return`Object {${t.slice(0,3).join(", ")}${t.length>3?"...":""}}`}catch{return"[Object]"}return e+""}};return Yi(t,"BeepCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Debug output for expressions with type information",syntax:["beep!","beep! <expression>","beep! <expression>, <expression>, ..."],examples:["beep!","beep! myValue","beep! me.id, me.className"],sideEffects:["console-output","debugging"],category:"utility",compatibility:"lokascript-extension"}),Ji(t,n),s=t})();const Dl=ta(Vl);const Bl=ta((()=>{let e,t,r=[Xi({name:"breakpoint"})],n=[];var s=t=class{get metadata(){return s.metadata}async parseInput(e,t,r){return{}}async execute(e,t){}validate(e){return"object"==typeof e&&null!==e}};return Yi(t,"BreakpointCommand"),(()=>{const i="function"==typeof Symbol&&Symbol.metadata?Object.create(null):void 0;Qi(null,e={value:t},r,{kind:"class",name:t.name,metadata:i},null,n),s=t=e.value,i&&Object.defineProperty(t,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:i})})(),t.metadata=ea({description:"Drop into the debugger (emits a debugger; statement)",syntax:["breakpoint"],examples:["breakpoint","on click breakpoint"],sideEffects:["debugging"],category:"utility",compatibility:"standard"}),Ji(t,n),s=t})());class Fl{constructor(){this.name="install"}get metadata(){return Fl.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("install command requires a behavior name");const n=e.args[0];let s,i;if(s="identifier"===n?.type&&"string"==typeof n.name?n.name:await t.evaluate(n,r)+"",!/^[A-Z][a-zA-Z0-9_]*$/.test(s))throw Error(`Behavior name must be PascalCase (start with uppercase): "${s}"`);const a=e.args[1];if(a){const e=await t.evaluate(a,r);if(e&&"object"==typeof e&&!Array.isArray(e)){i=e;for(const e of Object.keys(i))if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid parameter name: "${e}"`)}}let o;return e.modifiers?.on&&(o=await t.evaluate(e.modifiers.on,r)),{behaviorName:s,parameters:i,target:o}}async execute(e,t){const{behaviorName:r,parameters:n={},target:s}=e;try{const e=this.resolveTarget(s,t);if(0===e.length)throw Error("No target elements found to install behavior on");if(!this.behaviorExists(r,t))throw Error(`Behavior "${r}" is not defined. Define it using the 'behavior' keyword before installing.`);const i=[];for(const s of e){const e=await this.installBehavior(r,s,n,t);i.push(e)}return{success:!0,behaviorName:r,installedCount:i.length,instances:i}}catch(e){throw Error(`Failed to install behavior "${r}": ${e instanceof Error?e.message:e+""}`)}}resolveTarget(e,t){if(null==e){const e=t.me||t.locals.get("me");if(xe(e))return[e];throw Error('No target specified and "me" is not available in context')}if(xe(e))return[e];if(Array.isArray(e)){const t=e.filter(e=>xe(e));if(0===t.length)throw Error("Target array contains no valid HTMLElements");return t}if("string"==typeof e){if("me"===e){const e=t.me||t.locals.get("me");if(xe(e))return[e];throw Error('"me" is not available in context')}if("undefined"!=typeof document){const t=document.querySelectorAll(e),r=Array.from(t).filter(e=>xe(e));if(0===r.length)throw Error(`No elements found matching selector: "${e}"`);return r}throw Error("document is not available (not in browser environment)")}if(e&&"object"==typeof e&&"length"in e){const t=Array.from(e).filter(e=>xe(e));if(0===t.length)throw Error("Target collection contains no valid HTMLElements");return t}if("object"==typeof e&&"element"in e){const t=e.element;if(xe(t))return[t]}throw Error("Cannot resolve target to HTMLElement(s): "+(e+""))}behaviorExists(e,t){const r=t.locals.get("_behaviors");if(r&&"object"==typeof r){const t=r;if(t.has(e))return!0;if(t.resolve&&t.resolve(e))return!0}if("undefined"!=typeof globalThis){const t=globalThis._hyperscript;if(t?.behaviors){if(t.behaviors.has(e))return!0;if(t.behaviors.resolve&&t.behaviors.resolve(e))return!0}}return!1}async installBehavior(e,t,r,n){const s=n.locals.get("_behaviors");if(s&&"object"==typeof s){const n=s;if(n.install&&"function"==typeof n.install)return await n.install(e,t,r)}if("undefined"!=typeof globalThis){const n=globalThis._hyperscript;if(n?.behaviors?.install)return await n.behaviors.install(e,t,r)}throw Error("Behavior system not available in context")}}Fl.metadata=ea({description:"Install a behavior on an element with optional parameters",syntax:["install <BehaviorName>","install <BehaviorName> on <element>","install <BehaviorName>(param: value)","install <BehaviorName>(param: value) on <element>"],examples:["install Removable","install Draggable on #box",'install Tooltip(text: "Help", position: "top")','install Sortable(axis: "y") on .list',"install MyBehavior(foo: 42) on the first <div/>"],category:"behaviors",compatibility:"standard",sideEffects:["behavior-installation","element-modification"]});class _l{constructor(){this.name="render"}get metadata(){return _l.metadata}async parseInput(e,t,r){if(1>e.args.length)throw Error("render command requires a template");const n=await t.evaluate(e.args[0],r);let s;if(!s&&e.modifiers?.with){const n=await t.evaluate(e.modifiers.with,r);n&&"object"==typeof n&&(s=n)}return{template:n,variables:s}}async execute(e,t){const{template:r,variables:n={}}=e,s=this.extractTemplateContent(r,t),i=this.createTemplateContext(t,n),a=[],o=await this.processTemplate(s,i,a),c=this.createDOMElement(o);return Object.assign(t,{it:c}),{element:c,rendered:o,directivesProcessed:a}}extractTemplateContent(e,t){if(e instanceof HTMLTemplateElement)return e.innerHTML;if("string"==typeof e){let r=e;if(!r.includes("<")&&!r.includes("$")){const e=this.resolveVariable(r,t);if(e instanceof HTMLTemplateElement)return e.innerHTML;"string"==typeof e&&(r=e)}const n=r.match(/<template[^>]*>([\s\S]*?)<\/template>/i);return n?n[1]:r}if(e&&"object"==typeof e&&"innerHTML"in e)return e.innerHTML;throw Error("Invalid template format")}createTemplateContext(e,t){return{...e,locals:new Map([...Array.from(e.locals.entries()),...Object.entries(t)])}}async processTemplate(e,t,r){const n=e.split("\n"),s=[];let i=0;for(;n.length>i;){const e=n[i].trim();if(e.startsWith("@repeat ")){const{nextIndex:e,rendered:a}=await this.processRepeatDirective(n,i,t);s.push(a),i=e,r.push("@repeat")}else if(e.startsWith("@if ")){const{nextIndex:e,rendered:a}=await this.processIfDirective(n,i,t,r);s.push(a),i=e,r.push("@if")}else if("@else"===e||"@end"===e)i++;else{const r=this.processVariableInterpolation(e,t);s.push(r),i++}}return s.join("\n")}async processRepeatDirective(e,t,r){const n=e[t].trim(),s=n.match(/^@repeat\s+in\s+(.+)$/);if(!s)throw Error("Invalid @repeat syntax: "+n);const i=this.evaluateExpression(s[1],r),{endIndex:a,blockContent:o}=this.extractDirectiveBlock(e,t+1),c=[];if(Array.isArray(i))for(const e of i){const t={...r,locals:new Map([...r.locals.entries(),["it",e]])},n=await this.processTemplate(o.join("\n"),t,[]);c.push(n)}return{nextIndex:a+1,rendered:c.join("\n")}}async processIfDirective(e,t,r,n){const s=e[t].trim(),i=s.match(/^@if\s+(.+)$/);if(!i)throw Error("Invalid @if syntax: "+s);const a=!!this.evaluateExpression(i[1],r),{endIndex:o,blockContent:c,elseContent:l}=this.extractIfElseBlock(e,t+1);let u="";return a?u=await this.processTemplate(c.join("\n"),r,[]):l.length>0&&(u=await this.processTemplate(l.join("\n"),r,[]),n.push("@else")),{nextIndex:o+1,rendered:u}}extractDirectiveBlock(e,t){const r=[];let n=1,s=t;for(;e.length>s&&n>0;){const t=e[s].trim();t.startsWith("@repeat ")||t.startsWith("@if ")?(n++,r.push(e[s])):"@end"===t?(n--,n>0&&r.push(e[s])):r.push(e[s]),s++}return{endIndex:s-1,blockContent:r}}extractIfElseBlock(e,t){const r=[],n=[];let s=1,i=t,a=!1;for(;e.length>i&&s>0;){const t=e[i].trim();if(t.startsWith("@if "))s++;else{if("@else"===t&&1===s){a=!0,i++;continue}if("@end"===t&&(s--,0===s))break}a?n.push(e[i]):r.push(e[i]),i++}return{endIndex:i,blockContent:r,elseContent:n}}processVariableInterpolation(e,t){return e.replace(/\$\{([^}]+)\}/g,(e,r)=>{try{const e=r.trim();if(e.startsWith("unescaped ")){const r=e.substring(10).trim();return(this.evaluateExpression(r,t)||"")+""}const n=this.evaluateExpression(e,t);return this.escapeHtml((n||"")+"")}catch(t){return e}})}evaluateExpression(e,t){if("true"===e)return!0;if("false"===e)return!1;if("null"===e)return null;if("undefined"===e)return;const r=Number(e);if(!isNaN(r)&&""!==e.trim())return r;if(e.startsWith("[")&&e.endsWith("]"))try{return JSON.parse(e)}catch{}if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);if(e.includes(".")){const r=e.split(".");let n=this.resolveVariable(r[0],t);for(let e=1;r.length>e&&null!=n;e++){if("object"!=typeof n||null===n)return;n=n[r[e]]}return n}return this.resolveVariable(e,t)}resolveVariable(e,t){return t.locals?.has(e)?t.locals.get(e):"me"===e?t.me:"it"===e?t.it??t.result:"you"===e?t.you:"result"===e?t.result??t.it:t.globals?.has(e)?t.globals.get(e):void 0}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;")}createDOMElement(e){if("undefined"==typeof document)return null;const t=document.createElement("div");return t.innerHTML=e,1===t.children.length?t.firstElementChild:t}}_l.metadata=ea({description:"Render templates with @if, @else, and @repeat directives",syntax:["render <template>","render <template> with <variables>","render <template> with (key: value, ...)"],examples:["render myTemplate",'render myTemplate with (name: "Alice")','render "<template>Hello ${name}!</template>" with (name: "World")',"render template with (items: data)"],category:"templates",compatibility:"standard",sideEffects:["dom-creation","template-execution"]});const Ul={hide:la,show:ua,add:Oa,remove:qa,toggle:mo,put:ho,make:vo,empty:bo,open:ko,close:Co,select:So,reset:Lo,swap:lc,morph:uc,process:$c,wait:Vc,fetch:_c,set:Kc,get:Zc,increment:Qc,clear:Yc,default:Rl,trigger:tl,go:rl,push:sl,scroll:il,if:ll,repeat:dl,break:pl,continue:hl,halt:fl,return:yl,exit:gl,throw:vl,call:bl,focus:wl,blur:El,"pseudo-command":function(){return new kl},append:Al,prepend:Sl,transition:Tl,measure:Ll,settle:Ol,start:Nl,take:Il,js:jl,log:Xc,tell:Ml,copy:$l,pick:Wl,beep:Dl,breakpoint:Bl,install:function(){return new Fl},render:function(){return new _l}};class zl extends bi{constructor(e={}){const t=e.registry||new ui;e.registry||function(e){for(const t of n){if(t.consolidationAliasOf)continue;const r=Ul[t.name];if(!r)throw Error(`Command manifest names '${t.name}' but runtime.ts has no factory for it. Add it to COMMAND_FACTORIES, or give the manifest row a consolidationAliasOf.`);e.register(r())}}(t);const r={registry:t,expressionRegistry:e.expressionRegistry??Zi()};void 0!==e.enableAsyncCommands&&(r.enableAsyncCommands=e.enableAsyncCommands),void 0!==e.commandTimeout&&(r.commandTimeout=e.commandTimeout),void 0!==e.enableErrorReporting&&(r.enableErrorReporting=e.enableErrorReporting),super(r)}getRegistry(){return this.registry}}function Kl(e){if(e&&"object"==typeof e.locals&&e.locals instanceof Map)return e;const t=e?.globals,r=t instanceof Map?t:ke(),n={me:e?.me||null,you:e?.you||null,it:e?.it||e?.result,result:e?.result,locals:new Map,globals:r};if(!e)return n;if(e.locals&&"object"==typeof e.locals)for(const[t,r]of Object.entries(e.locals))n.locals.set(t,r);if(e.globals&&"object"==typeof e.globals&&!(e.globals instanceof Map))for(const[t,r]of Object.entries(e.globals))le(n,t,r);const s=new Set(["me","you","it","result","locals","globals","language"]);for(const[t,r]of Object.entries(e))s.has(t)||void 0===r||n.locals.set(t,r);return n}async function Zl(e,t){if(!e||""===e.trim())throw Error("Cannot evaluate empty script");try{const r=Kl(t),n=t?.language||"en";if(function(e){const t=e.trim().toLowerCase();if([/^set\s+.+\s+to\s+.+/,/^put\s+.+\s+(into|before|after)\s+.+/,/^add\s+.+(\s+to\s+.+)?/,/^remove\s+.+(\s+from\s+.+)?/,/^show\s+.+/,/^hide\s+.+/,/^toggle\s+.+/,/^log\s+.*/,/^wait\s+.+/,/^call\s+.+/,/^send\s+.+/,/^make\s+.+/,/^increment\s+.+/,/^decrement\s+.+/,/^fetch\s+.+/,/^throw\s+.+/,/^return\s+.+/,/^break/,/^continue/,/^halt/,/^go\s+.+/,/^if\s+.+/,/^repeat\s+.+/,/^on\s+.+/,/^render\s+.+/].some(e=>e.test(t)))return!0;const r=t.split(/\s/)[0];if(r&&j.has(r))return!0;return!1}(e))return await async function(e,t,r="en"){let n;if("en"!==r){const{hyperscript:t}=await Promise.resolve().then(function(){return Ru}),s=await t.compile(e,{language:r});if(!s.ok||!s.ast)throw Error("Parse error: "+(s.errors?.[0]?.message||"Unknown parse error"));n=s.ast}else{const t=new Ss(St(e)).parse();if(!t.success||!t.node)throw Error("Parse error: "+(t.error?.message||"Unknown parse error"));n=t.node}const s=new zl,i=await s.execute(n,t);return i}(e,r,n);return await Hs(e,r)}catch(e){if(e instanceof Error)throw Error("HyperScript evaluation error: "+e.message);throw e}}async function Gl(e,t){if(!e||""===e.trim())throw Error("Cannot evaluate empty expression");try{const r=Kl(t);return await Hs(e,r)}catch(e){if(e instanceof Error)throw Error("HyperScript evaluation error: "+e.message);throw e}}async function Ql(e,t){if(function(e){const t=e.toLowerCase();return["fetch","wait","settle","promise"].some(e=>t.includes(e))}(e))return Gl(e,t);try{return Zl(e,t)}catch(r){if(r instanceof Error&&r.message.includes("Async expressions not yet supported"))return Gl(e,t);throw r}}const Jl=.5;let Yl=!1,Xl=null;if("undefined"!=typeof window&&"undefined"!=typeof URLSearchParams)try{"semantic"===new URLSearchParams(window.location.search).get("debug")&&(Yl=!0,Xl=window)}catch{}let eu={totalParses:0,semanticSuccesses:0,semanticFallbacks:0,traditionalParses:0,averageConfidence:0,confidenceHistory:[]};function tu(e){const{target:t,strategy:r="morph",useViewTransition:n=!1,fetchOptions:s={},transformUrl:i,onBeforeFetch:a,onAfterSwap:o,onError:c}=e,l=async e=>{const l=(()=>{if("string"==typeof t){const e=document.querySelector(t);return xe(e)?e:null}return xe(t)?t:null})();if(!l)return void console.warn(`HistorySwap: target "${t}" not found`);let u=window.location.href;i&&(u=i(u));try{a&&await a(u),l.classList.add("hx-swapping");const e=await fetch(u,{method:"GET",headers:{Accept:"text/html","HX-Request":"true","HX-History-Restore-Request":"true"},...s});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);const i=await e.text();await nc([l],i,r,{useViewTransition:n}),l.classList.remove("hx-swapping"),o&&await o(u,i),Ic(window,"historyswap",{url:u,strategy:r,target:t})}catch(e){l.classList.remove("hx-swapping"),c?c(e,u):console.error("HistorySwap fetch failed:",e)}};return window.addEventListener("popstate",l),{destroy:()=>{window.removeEventListener("popstate",l)},config:e}}const ru={name:"HistorySwap",init:(e,t={})=>tu({target:t.target||e,strategy:t.strategy||"morph",useViewTransition:!!t.useViewTransition}),destroy(e){e.destroy()}};function nu(e){return!function(e){try{return new URL(e,window.location.origin).origin!==window.location.origin}catch{return!1}}(e.href)&&((!e.target||"_self"===e.target)&&(!e.hasAttribute("download")&&(!e.hasAttribute("data-no-boost")&&!e.hasAttribute("hx-boost-off")&&("javascript:"!==e.protocol&&"mailto:"!==e.protocol))))}function su(e){const{container:t,target:r,linkSelector:n="a[href]",formSelector:s="form",boostForms:i=!1,strategy:a="morph",pushUrl:o=!0,useViewTransition:c=!1,fetchOptions:l={},onBeforeFetch:u,onAfterSwap:d,onError:m}=e,p=async(e,n="GET",s=null)=>{const i=(()=>{if(!r)return document.body;if("string"==typeof r){const e=document.querySelector(r);return xe(e)?e:null}return xe(r)?r:null})();if(i)try{if(u){if(!1===await u(e,n))return}i.classList.add("hx-swapping"),t.classList.add("hx-boosting");const m={method:n,headers:{Accept:"text/html","HX-Request":"true","HX-Boosted":"true"},...l};s&&"GET"!==n&&(m.body=s);const p=await fetch(e,m);if(!p.ok)throw Error(`HTTP ${p.status}: ${p.statusText}`);const h=await p.text();await nc([i],h,a,{useViewTransition:c}),i.classList.remove("hx-swapping"),t.classList.remove("hx-boosting"),o&&"GET"===n&&window.history.pushState(null,"",e),d&&await d(e,h),Ic(window,"boosted",{url:e,method:n,strategy:a,target:r})}catch(r){i.classList.remove("hx-swapping"),t.classList.remove("hx-boosting"),m?m(r,e):(console.error("Boosted fetch failed:",r),window.location.href=e)}else console.warn(`Boosted: target "${r}" not found`)},h=async e=>{const t=e.target.closest(n);t&&function(e){return!(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)&&0===e.button}(e)&&nu(t)&&(e.preventDefault(),e.stopPropagation(),await p(t.href))},f=async e=>{if(!i)return;const t=e.target.closest(s);if(!t)return;if(t.hasAttribute("data-no-boost")||t.hasAttribute("hx-boost-off"))return;if(t.target&&"_self"!==t.target)return;e.preventDefault(),e.stopPropagation();const r=(t.method||"GET").toUpperCase(),n=new FormData(t);let a,o=null;if("GET"===r){const e=new URLSearchParams;n.forEach((t,r)=>{e.append(r,t+"")}),a=`${t.action||window.location.pathname}?${""+e}`}else a=t.action||window.location.pathname,o=n;await p(a,r,o)};return t.addEventListener("click",h),i&&t.addEventListener("submit",f),{destroy:()=>{t.removeEventListener("click",h),t.removeEventListener("submit",f)},config:e,boost:p}}const iu={name:"Boosted",init:(e,t={})=>su({container:e,target:t.target,linkSelector:t.linkSelector||"a[href]",formSelector:t.formSelector||"form",boostForms:!!t.boostForms,strategy:t.strategy||"morph",pushUrl:!1!==t.pushUrl,useViewTransition:!!t.useViewTransition}),destroy(e){e.destroy()}};const au="click";let ou,cu,lu,uu=null;function du(e,t,r){r.errors?.length&&r.errors.forEach((e,t)=>{}),t.split("\n")}async function mu(e,t){try{return await lu().execute(e,t)}catch(e){throw e}}function pu(e,t,r){try{const n=function(e){try{if(function(e){return"eventHandler"===e.type}(e)){return{eventType:e.event||au,body:{type:"CommandSequence",commands:e.commands||[],start:e.start||0,end:e.end||0,line:e.line||1,column:e.column||1}}}if(function(e){return"FeatureNode"===e.type}(e)&&"on"===e.name){return{eventType:e.args?.[0]?.value||au,body:e.body||e}}return"CommandSequence"===e.type||"Block"===e.type?{eventType:au,body:e}:null}catch(e){return null}}(t);if(!n)return;const s=async e=>{try{r.locals.set("event",e),r.locals.set("target",e.target),await mu(n.body,r)}catch(e){}};e.addEventListener(n.eventType,s);try{const t=lu?.();t?.trackListener?.(e,e,n.eventType,s)}catch{}}catch(e){}}function hu(e){return Ee(e)}function fu(e,t,r,n){const s=new CustomEvent(t,{bubbles:!0,cancelable:r,detail:n});return e.dispatchEvent(s)}function yu(e,t){if(!fu(e,"hyperscript:before:init",!0,{code:t}))return;const r=function(e){const t=e.getAttribute("data-lang");if(t)return t;const r=e.closest("[lang]")?.getAttribute("lang");if(r)return r.split("-")[0];if("undefined"!=typeof document){const e=document.documentElement?.lang;if(e)return e.split("-")[0]}return"en"}(e);"en"===r?(!function(e,t){try{const r=ou(t);if(!r.ok)return void du(0,t,r);if(!r.ast)return;const n=hu(e);if(t.trim().startsWith("on "))try{pu(e,r.ast,n)}catch(e){throw e}else mu(r.ast,n)}catch(e){}}(e,t),gu(e),fu(e,"hyperscript:after:init",!1,{code:t})):async function(e,t,r){try{const n=await cu(t,{language:r});if(!n.ok)return void du(0,t,n);if(!n.ast)return;const s=hu(e);t.trim().startsWith("on ")||"eventHandler"===n.ast.type?pu(e,n.ast,s):mu(n.ast,s)}catch(e){}}(e,t,r).then(()=>{gu(e),fu(e,"hyperscript:after:init",!1,{code:t})})}function gu(e){e.hasAttribute("data-hyperscript-powered")||e.setAttribute("data-hyperscript-powered","")}class vu{constructor(e){this.capacity=e,this.head=0,this.count=0,this.items=Array(e)}push(e){this.items[this.head]=e,this.head=(this.head+1)%this.capacity,this.capacity>this.count&&this.count++}toArray(){return this.capacity>this.count?this.items.slice(0,this.count):[...this.items.slice(this.head),...this.items.slice(0,this.head)]}get length(){return this.count}clear(){this.head=0,this.count=0}last(){if(0===this.count)return;return this.items[(this.head-1+this.capacity)%this.capacity]}}class bu{constructor(){this.state={enabled:!1,paused:!1,stepMode:"continue",callDepth:0,pauseDepth:0,currentSnapshot:null},this.history=new vu(200),this.breakpoints=new Map,this.snapshotIndex=0,this._resumeResolver=null,this.listeners=new Map,this.hooks={beforeExecute:this.beforeExecute.bind(this),afterExecute:this.afterExecute.bind(this)}}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>r.delete(t)}emit(e,t){const r=this.listeners.get(e);if(r)for(const e of r)try{e(t)}catch{}}enable(){this.state.enabled=!0,this.emit("enabled")}disable(){this.state.paused&&this._resumeResolver&&(this._resumeResolver(),this._resumeResolver=null),this.state.enabled=!1,this.state.paused=!1,this.state.stepMode="continue",this.state.callDepth=0,this.emit("disabled")}get enabled(){return this.state.enabled}continue(){this.state.stepMode="continue",this.resume()}pause(){this.state.stepMode="pause"}stepOver(){this.state.stepMode="over",this.state.pauseDepth=this.state.callDepth,this.resume()}stepInto(){this.state.stepMode="into",this.resume()}stepOut(){this.state.stepMode="out",this.state.pauseDepth=this.state.callDepth,this.resume()}resume(){this._resumeResolver&&(this.state.paused=!1,this.emit("resumed"),this._resumeResolver(),this._resumeResolver=null)}setBreakpoint(e){const t=`bp_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.breakpoints.set(t,{...e,id:t,hitCount:0}),t}removeBreakpoint(e){return this.breakpoints.delete(e)}getBreakpoints(){return Array.from(this.breakpoints.values())}clearBreakpoints(){this.breakpoints.clear()}getState(){return{...this.state}}getHistory(){return this.history.toArray()}clearHistory(){this.history.clear(),this.snapshotIndex=0}async beforeExecute(e){if(!this.state.enabled)return;this.state.callDepth++;const t=this.captureSnapshot(e);this.history.push(t),this.emit("snapshot",t),this.shouldPause(e)&&(this.state.paused=!0,this.state.currentSnapshot=t,this.emit("paused",t),await new Promise(e=>{this._resumeResolver=e}),this.state.currentSnapshot=null)}async afterExecute(e,t){if(!this.state.enabled)return;const r=this.history.last();r&&(r.variables.__result=wu(t)),this.state.callDepth=Math.max(0,this.state.callDepth-1)}shouldPause(e){if(this.hitBreakpoint(e))return!0;switch(this.state.stepMode){case"pause":return this.state.stepMode="into",!0;case"into":return!0;case"over":return this.state.pauseDepth>=this.state.callDepth;case"out":return this.state.pauseDepth>this.state.callDepth;case"continue":return!1}}hitBreakpoint(e){for(const t of this.breakpoints.values()){if(!t.enabled)continue;let r=!1;switch(t.type){case"command":r=e.commandName===t.value;break;case"element":if(e.element)try{r=e.element.matches(t.value)}catch{}break;case"expression":r=this.evaluateCondition(t.value,e)}if(r)return t.hitCount++,!0}return!1}evaluateCondition(e,t){try{const r=t.executionContext,n={commandName:t.commandName,it:r.it,result:r.result,me:r.me};if(r.locals)for(const[e,t]of r.locals)n[e]=t;const s=Object.keys(n),i=s.map(e=>n[e]);return!!Function(...s,`return (${e});`)(...i)}catch{return!1}}captureSnapshot(e){const t=e.executionContext,r={};if(r.it=wu(t.it),r.result=wu(t.result),t.me&&(r.me=Eu(t.me)),t.you&&(r.you=Eu(t.you)),e.event&&(r["event.type"]=e.event.type,e.event.target&&(r["event.target"]=Eu(e.event.target))),t.locals)for(const[e,n]of t.locals)e.startsWith("__")||(r[":"+e]=wu(n));return{commandName:e.commandName,element:e.element,variables:r,timestamp:Date.now(),depth:this.state.callDepth,index:this.snapshotIndex++}}}function wu(e){if(null==e)return e;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Element)return Eu(e);if(Array.isArray(e))return`Array(${e.length})`;if(e instanceof Map)return`Map(${e.size})`;if(e instanceof Set)return`Set(${e.size})`;if("function"==typeof e)return`\u0192 ${e.name||"anonymous"}()`;if("object"==typeof e){const t=Object.keys(e);return t.length>3?`{${t.slice(0,3).join(", ")}, ...${t.length-3} more}`:`{${t.join(", ")}}`}return e+""}function Eu(e){let t="<"+e.tagName.toLowerCase();return e.id&&(t+="#"+e.id),e.classList.length>0&&(t+="."+Array.from(e.classList).join(".")),t+=">",t}const ku="en";const xu=new class{constructor(e=500){this.cache=new Map,this.hits=0,this.misses=0,this.maxSize=e}makeKey(e,t){return`${t?.language||ku}\0${t?.traditional?"1":"0"}\0${Au.semantic?1:0}\0${e}`}get(e,t){const r=this.makeKey(e,t),n=this.cache.get(r);if(n)return this.hits++,this.cache.delete(r),this.cache.set(r,n),n.result;this.misses++}set(e,t,r){if(!r.ok)return;const n=this.makeKey(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(n,{result:r})}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const e=this.hits+this.misses;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0}}}(500);let Cu=null;const Au={semantic:!0,language:"en",confidenceThreshold:.5,logAll:!1,conversions:rt.conversions,onCompileError:null};let Su=null,Tu=null;function Lu(){if(!Su&&(Su=new zl({lazyLoad:!1}),(e=Su.behaviorRegistry)instanceof Map||e&&"function"==typeof e.set?e.set("HistorySwap",ru):e&&"object"==typeof e&&(e.HistorySwap=ru),function(e){e instanceof Map||e&&"function"==typeof e.set?e.set("Boosted",iu):e&&"object"==typeof e&&(e.Boosted=iu)}(Su.behaviorRegistry),"undefined"!=typeof globalThis)){const e=globalThis;e._hyperscript=e._hyperscript||{},e._hyperscript.runtime=Su,e._hyperscript.behaviors=Su.behaviorAPI}var e;return Su}async function Ou(e,t){if(!e)throw Error("AST is required for execution");const r=t||Ee();return await Lu().execute(e,r)}function Nu(e){return{message:e.message,line:e.line??1,column:e.column??1}}function Pu(e,t){if("string"!=typeof e)throw new TypeError("Code must be a string");const r=xu.get(e,t);if(r)return r;const n=performance.now(),s=t?.language||ku;try{const r=Ts(e,{}),i=performance.now()-n;if(r.success&&r.node){const n=r.errors??[],a={ok:!0,ast:r.node,...n.length>0?{errors:n.map(Nu)}:{},meta:{parser:"traditional",language:s,timeMs:i}};return xu.set(e,t,a),a}return{ok:!1,errors:r.error?[Nu(r.error)]:[],meta:{parser:"traditional",language:s,timeMs:i}}}catch(e){const t=performance.now()-n;return{ok:!1,errors:[{message:e instanceof Error?e.message:"Unknown compilation error",line:1,column:1}],meta:{parser:"traditional",language:s,timeMs:t}}}}async function Iu(e,t){if("string"!=typeof e)throw new TypeError("Code must be a string");const r=t?.language||ku;if(r===ku||t?.traditional||!Au.semantic)return Pu(e,t);const n=xu.get(e,t);if(n)return n;const s=performance.now();try{const n=await async function(){if(!Cu){const{SemanticGrammarBridge:e}=await import("./bridge-8SRzBI2K.js");Cu=new e({confidenceThreshold:Au.confidenceThreshold}),await Cu.initialize()}return Cu}(),a=await n.parseToASTWithDetails(e,r);if(Yl){const t=a.ast?.name,n={input:e.substring(0,100),language:r,confidence:a.confidence,threshold:Au.confidenceThreshold,semanticSuccess:a.usedDirectPath,fallbackTriggered:!a.usedDirectPath&&null!==a.fallbackText,..."string"==typeof t?{command:t}:{},...a.warnings?.length?{errors:a.warnings}:{},timestamp:Date.now(),duration:performance.now()-s};!function(e){if(!Yl)return;const t=e.semanticSuccess?"semantic":e.fallbackTriggered?"fallback":"traditional",r=e.semanticSuccess?"color: #4caf50; font-weight: bold":e.fallbackTriggered?"color: #ff9800; font-weight: bold":"color: #9e9e9e";if(console.groupCollapsed(`%c[Semantic] ${t.toUpperCase()} %c${e.input.substring(0,50)}${e.input.length>50?"...":""}`,r,"color: #888"),e.roles&&Object.keys(e.roles),console.groupEnd(),Xl){const t=new CustomEvent("lokascript:semantic:parse",{detail:e,bubbles:!0});Xl.dispatchEvent(t)}}(n),i=n,eu.totalParses++,i.semanticSuccess?eu.semanticSuccesses++:i.fallbackTriggered?eu.semanticFallbacks++:eu.traditionalParses++,eu.confidenceHistory.push(i.confidence),eu.confidenceHistory.length>100&&eu.confidenceHistory.shift(),eu.averageConfidence=eu.confidenceHistory.reduce((e,t)=>e+t,0)/eu.confidenceHistory.length}if(a.usedDirectPath&&a.ast){const n=performance.now()-s,i={ok:!0,ast:a.ast,meta:{parser:"semantic",confidence:a.confidence,language:r,timeMs:n,directPath:!0,...a.warnings?.length?{warnings:a.warnings}:{}}};return xu.set(e,t,i),i}const o=Pu(a.fallbackText||e,{...t,language:ku}),c={...o,meta:{...o.meta,language:r,confidence:a.confidence,directPath:!1}};return xu.set(e,t,c),c}catch{return Pu(e,{...t,language:"en"})}var i}!function(e,t,r){ou=e,cu=t,lu=r}(Pu,Iu,Lu),uu=Au;const ju={compile:Iu,compileSync:Pu,execute:Ou,eval:async function(e,t,r){if("string"!=typeof e||0===e.trim().length)throw Error("Code must be a non-empty string");let n;if(t)if(t instanceof Element)n=Ee(t);else if("object"==typeof(s=t)&&null!==s&&"locals"in s&&s.locals instanceof Map)n=t;else{const e=t;n=function(e){return"object"==typeof e&&null!==e&&"me"in e}(e)?Ee(e.me):Ee()}else n=Ee();var s;const i=await Iu(e.trim(),r);if(!i.ok){throw Error("Compilation failed: "+(i.errors?.[0]?.message||"Unknown compilation error"))}return Ou(i.ast,n)},validate:async function(e,t){const r=await Iu(e,t),n=r.errors??[];return{valid:r.ok&&0===n.length,errors:n.length>0?n:void 0}},process:function(e){try{const t=e.getAttribute("_");t&&yu(e,t);e.querySelectorAll("[_]").forEach(e=>{const t=e.getAttribute("_");t&&yu(e,t)})}catch(e){}},cleanup:e=>{e.dispatchEvent(new CustomEvent("hyperscript:before:cleanup",{bubbles:!0,cancelable:!1}));const t=Lu().cleanupTree(e);return e.hasAttribute?.("data-hyperscript-powered")&&e.removeAttribute("data-hyperscript-powered"),e.dispatchEvent(new CustomEvent("hyperscript:after:cleanup",{bubbles:!0,cancelable:!1,detail:{count:t}})),t},createContext:function(e,t){return t?function(e,t){return{me:t??e.me,owner:e.owner??e.me??t??null,it:null,you:null,result:null,locals:new Map,globals:e.globals,parent:e}}(t,e):Ee(e)},config:Au,version:"3.0.0",createRuntime:function(e){return new zl(e)},getDefaultRuntime:()=>Lu(),registerHooks:(e,t)=>{Lu().registerHooks(e,t)},unregisterHooks:e=>Lu().unregisterHooks(e),getRegisteredHooks:()=>Lu().getRegisteredHooks(),evalLSE:async function(e,t){if("string"!=typeof e||0===e.trim().length)throw Error("LSE code must be a non-empty string");const{parseExplicit:r,semanticNodeToRuntimeAST:n}=await import("./index-CAPhqA6k.js"),s=await r(e),i=await n(s),a=t?Ee(t):Ee();return await Lu().execute(i,a)},evalLSENode:async function(e,t){const{semanticNodeToRuntimeAST:r}=await import("./index-CAPhqA6k.js"),n=await r(e),s=t?Ee(t):Ee();return await Lu().execute(n,s)},compileLSE:async function(e){const t=performance.now();if("string"!=typeof e||0===e.trim().length)return{ok:!1,errors:[{message:"LSE code must be a non-empty string",line:0,column:0}],meta:{parser:"lse",language:"explicit",timeMs:performance.now()-t}};try{const{parseExplicit:r,semanticNodeToRuntimeAST:n}=await import("./index-CAPhqA6k.js"),s=await r(e,{collectDiagnostics:!0}),i=await n(s),a=s.diagnostics?.filter(e=>"error"===e.severity),o=a&&a.length>0;return{ok:!o,ast:o?void 0:i,lse:s,...o?{errors:a.map(e=>({message:e.message,line:0,column:0}))}:{},meta:{parser:"lse",language:"explicit",timeMs:performance.now()-t}}}catch(e){return{ok:!1,errors:[{message:e.message,line:0,column:0}],meta:{parser:"lse",language:"explicit",timeMs:performance.now()-t}}}},toLSE:async function(e,t){const r=t||ku,{parseSemantic:n}=await import("./index-SorDzXmq.js"),{renderExplicit:s}=await import("./index-CAPhqA6k.js"),i=n(e,r);if(!i||!i.node)throw Error(`Failed to parse "${e}" as ${r} hyperscript`);return await s(i.node)},fromLSE:async function(e,t){const{render:r}=await import("./index-SorDzXmq.js"),{parseExplicit:n}=await import("./index-CAPhqA6k.js");return r(await n(e),t)},clearCache:()=>xu.clear(),getCacheStats:()=>xu.getStats(),get debug(){return Tu||(Tu=new bu,Lu().registerHooks("__debugger",Tu.hooks)),Tu}};var Ru=Object.freeze({__proto__:null,config:Au,hyperscript:ju});const Mu=/^on\s+(\w+)/,$u=new Set(["load","mutation","intersection","appear","every"]);function Hu(){return"undefined"!=typeof globalThis&&"scheduler"in globalThis&&"function"==typeof globalThis.scheduler?.yield?globalThis.scheduler.yield():new Promise(e=>setTimeout(e,0))}const qu=new class{constructor(e={}){this.processedElements=new WeakSet,this.observer=null,this.processedCount=0,this.readyEventDispatched=!1,this.initialized=!1,this.lazyElements=new WeakSet,this.options={attributeName:"_",autoScan:!0,processOnlyNewElements:!0,lazyParsing:!1,chunkedProcessing:!1,chunkSize:16,...e}}async init(){"undefined"!=typeof document&&(this.initialized||(this.initialized=!0,this.options.autoScan&&(await this.scanAndProcessAll(),this.dispatchReadyEvent()),this.setupMutationObserver()))}async scanAndProcessAll(){"undefined"!=typeof window&&window.__hyperfixi_behaviors_ready&&await window.__hyperfixi_behaviors_ready;const e=document.querySelectorAll('script[type="text/hyperscript"]');for(const t of e)t instanceof HTMLScriptElement&&(t.textContent?.substring(0,50),await this.processHyperscriptTag(t));const t=document.querySelectorAll(`[${this.options.attributeName}]`);if(this.options.lazyParsing){const e=[];t.forEach(t=>{if(t instanceof HTMLElement){const r=this.processElementLazy(t);r&&e.push(r)}}),e.length>0&&await Promise.all(e)}else if(this.options.chunkedProcessing)await this.processElementsChunked(t);else{const e=[];t.forEach(t=>{t instanceof HTMLElement&&e.push(this.processElementAsync(t))}),await Promise.all(e)}"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("lokascript:initialized",{detail:{scriptsProcessed:e.length,elementsProcessed:t.length}}))}reportCompileError(e,t,r,n){const s=r??[];console.error("attribute"===e?"[LokaScript] Compilation failed for _= attribute:":"[LokaScript] Compilation failed for hyperscript script tag:",s,n??"");try{Au.onCompileError?.({source:e,code:t,errors:s,element:n})}catch(e){console.error("[LokaScript] onCompileError hook threw:",e)}try{const r=n??("undefined"!=typeof document?document:null);r?.dispatchEvent(new CustomEvent("hyperfixi:compile-error",{bubbles:!0,cancelable:!1,detail:{source:e,code:t,errors:s,element:n}}))}catch(e){}}async processHyperscriptTag(e){const t=e.getAttribute("for");t?await this.processHyperscriptTagForElements(e,t):await this.processHyperscriptTagGlobal(e)}async processHyperscriptTagForElements(e,t){const r=e.textContent||e.innerHTML;if(!r||!r.trim())return;const n=document.querySelectorAll(t);if(0!==n.length)try{r.substring(0,50);const t=ju.compileSync(r);if(!t.ok)return void this.reportCompileError("script",r,t.errors,e);for(const e of n)if(e instanceof HTMLElement){const r=Ee(e);await ju.execute(t.ast,r)}}catch(e){console.error(`[LokaScript] Error processing script for="${t}":`,e)}else console.warn(`[LokaScript] Script with for="${t}" found no matching elements`)}async processHyperscriptTagGlobal(e){const t=e.textContent||e.innerHTML;if(t&&t.trim())try{t.substring(0,50);const r=Ee(null),n=ju.compileSync(t);if(!n.ok)return void this.reportCompileError("script",t,n.errors,e);await ju.execute(n.ast,r)}catch(e){console.error("[LokaScript] Script execution error:",e)}}processElement(e){this.processElementAsync(e)}async processElementAsync(e){if(this.options.processOnlyNewElements&&this.processedElements.has(e))return;const t=e.getAttribute(this.options.attributeName);if(t){this.processedElements.add(e),this.processedCount++;try{const r=Ee(e),n=ju.compileSync(t);if(!n.ok)return void this.reportCompileError("attribute",t,n.errors,e);await ju.execute(n.ast,r),this.dispatchLoadEvent(e)}catch(t){console.error("[LokaScript] Error processing _= attribute:",t,e)}}}async processElementsChunked(e){const t=this.options.chunkSize,r=[];e.forEach(e=>{e instanceof HTMLElement&&r.push(e)});for(let e=0;r.length>e;e+=t){const n=r.slice(e,e+t).map(e=>this.processElementAsync(e));await Promise.all(n),r.length>e+t&&await Hu()}}processElementLazy(e){const t=e.getAttribute(this.options.attributeName);if(!t)return null;const r=t.match(Mu);if(!r||$u.has(r[1])||this.hasMultipleHandlers(t))return this.processElementAsync(e);const n=r[1];return e.addEventListener(n,async r=>{this.lazyElements.delete(e);try{const n=ju.compileSync(t);if(!n.ok||!n.ast)return void this.reportCompileError("attribute",t,n.errors,e);const s=Ee(e);ju.execute(n.ast,s);const i=n.ast;if("eventHandler"===i.type&&i.commands?.length>0){i.modifiers?.prevent&&r.preventDefault(),i.modifiers?.stop&&r.stopPropagation();const t=Ee(e);t.locals.set("event",r),t.locals.set("target",r.target),t.event=r;for(const e of i.commands)await ju.execute(e,t)}this.dispatchLoadEvent(e)}catch(t){console.error("[LokaScript] Error in lazy handler on first event:",t,e)}},{once:!0}),this.lazyElements.add(e),this.processedElements.add(e),this.processedCount++,null}hasMultipleHandlers(e){const t=new Set(["me","it","its","my","you","yourself"]);let r=0;const n=/\bon\s+(\w+)/g;let s;for(;null!==(s=n.exec(e));){if("."!==e[s.index+s[0].length]&&(!t.has(s[1])&&(r++,r>1)))return!0}return!1}dispatchLoadEvent(e){try{const t=new Event("load",{bubbles:!1,cancelable:!1});e.dispatchEvent(t)}catch(e){}}dispatchReadyEvent(){if(!this.readyEventDispatched)try{const e=new CustomEvent("hyperscript:ready",{bubbles:!0,cancelable:!1,detail:{processedElements:this.processedCount,timestamp:Date.now()}});document.dispatchEvent(e),this.readyEventDispatched=!0}catch(e){}}setupMutationObserver(){"undefined"!=typeof MutationObserver&&(this.observer=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;"SCRIPT"===t.tagName&&"text/hyperscript"===t.getAttribute("type")&&this.processHyperscriptTag(t).catch(e=>{console.error("[LokaScript] Error processing dynamically added script tag:",e)});const r=t.querySelectorAll?.('script[type="text/hyperscript"]');r?.forEach(e=>{e instanceof HTMLScriptElement&&this.processHyperscriptTag(e).catch(e=>{console.error("[LokaScript] Error processing dynamically added script tag:",e)})}),t.getAttribute&&t.getAttribute(this.options.attributeName)&&this.processElementAsync(t).catch(e=>{console.error("[LokaScript] Error processing dynamically added element:",e)});const n=t.querySelectorAll?.(`[${this.options.attributeName}]`);n?.forEach(e=>{e instanceof HTMLElement&&this.processElementAsync(e).catch(e=>{console.error("[LokaScript] Error processing dynamically added element:",e)})})}})})}),this.observer.observe(document.body,{childList:!0,subtree:!0}))}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.initialized=!1,this.readyEventDispatched=!1,this.processedCount=0,this.lazyElements=new WeakSet}reset(){this.destroy()}};class Wu{constructor(e,t,r=0){this.pool=[],this.index=0,this.metrics={allocations:0,reuses:0,peakPoolSize:0},this.factory=e,this.reset=t;for(let t=0;r>t;t++)this.pool.push(e());this.metrics.allocations=r,this.metrics.peakPoolSize=r}get(){let e;return this.pool.length>this.index?(e=this.pool[this.index++],this.metrics.reuses++,this.reset&&this.reset(e)):(e=this.factory(),this.pool.push(e),this.index++,this.metrics.allocations++,this.pool.length>this.metrics.peakPoolSize&&(this.metrics.peakPoolSize=this.pool.length)),e}releaseAll(){this.index=0}getMetrics(){const e=this.metrics.allocations+this.metrics.reuses;return{...this.metrics,hitRate:e>0?this.metrics.reuses/e*100:0}}clear(){this.pool=[],this.index=0,this.metrics={allocations:0,reuses:0,peakPoolSize:0}}}const Vu=new class{constructor(){this.pending=new Map,this.rafId=null,this.stylePool=new Wu(()=>({}),e=>{for(const t of Object.keys(e))delete e[t]},10)}add(e,t){let r=this.pending.get(e);r||(r=this.stylePool.get(),this.pending.set(e,r)),Object.assign(r,t),this.rafId||(this.rafId=requestAnimationFrame(()=>this.flush()))}flush(){for(const[e,t]of this.pending)for(const[r,n]of Object.entries(t))if(r.startsWith("--"))e.style.setProperty(r,n);else{const t=r.replace(/-([a-z])/g,e=>e[1].toUpperCase());e.style[t]=n}this.pending.clear(),this.stylePool.releaseAll(),this.rafId=null}cancel(){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pending.clear(),this.stylePool.releaseAll()}getPendingCount(){return this.pending.size}getPoolMetrics(){return this.stylePool.getMetrics()}},Du={evalHyperScript:Zl,evalHyperScriptAsync:Gl,evalHyperScriptSmart:Ql,evaluate:Zl,compile:e=>{const t=ju.compileSync(e);if(!t.ok){throw Error(t.errors&&t.errors.length>0?t.errors[0].message:"Compilation failed")}return t},execute:ju.execute,run:async(e,t)=>ju.eval(e,t),createContext:ju.createContext,createRuntime:ju.createRuntime,Parser:Ss,Runtime:zl,tokenize:St,processNode:async e=>{e===document?qu.scanAndProcessAll():e instanceof HTMLElement&&qu.processElement(e)},process:e=>Du.processNode(e),attributeProcessor:qu,styleBatcher:Vu,ObjectPool:Wu,debug:Vr,version:"1.0.0-modular"};"undefined"!=typeof window&&(window.hyperfixi=Du,window.evalHyperScript=Zl,window.evalHyperScriptAsync=Gl,window.evalHyperScriptSmart=Ql,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{qu.init()}):qu.init());export{Jl as D,Wu as O,Ss as P,zl as R,qu as a,Gl as b,Ql as c,Vr as d,Zl as e,ju as f,Du as h,Vu as s,St as t};
2
- //# sourceMappingURL=browser-modular-L1qgqF_N.js.map