zero-query 0.8.7 → 0.8.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -65,7 +65,7 @@ The dev server includes a **full-screen error overlay** that surfaces errors dir
65
65
 
66
66
  #### Floating Toolbar & Inspector
67
67
 
68
- A compact toolbar appears in the bottom-right corner showing live request/render counters and a DOM button. Click any counter to open a **dark-themed DevTools inspector** as a popup — or visit `http://localhost:<port>/_devtools` for a standalone split-view panel with four tabs: **Elements** (live DOM tree with component badges, source viewer, expand/collapse), **Network** (fetch log with JSON viewer), **Components** (live state cards), and **Performance** (render timeline with timing metrics).
68
+ A compact expandable toolbar appears in the bottom-right corner. In its **collapsed** state it shows live render and request counters. Click the chevron to **expand** and reveal the route indicator (color-coded by the last navigation event — navigate, pop, replace, hashchange, substate), registered component count, and DOM element count. Click any stat to open a **dark-themed DevTools inspector** as a popup — or visit `http://localhost:<port>/_devtools` for a standalone split-view panel with five tabs: **Router** (live route state, guards, history timeline), **Components** (live state cards), **Performance** (render timeline with timing metrics), **Network** (fetch log with JSON viewer), and **Elements** (live DOM tree with component badges, source viewer, expand/collapse).
69
69
 
70
70
  ### Alternative: Manual Setup (No npm)
71
71
 
@@ -276,7 +276,7 @@ location / {
276
276
  | CLI Command | Description |
277
277
  | --- | --- |
278
278
  | `zquery create [dir]` | Scaffold a new project (index.html, components, store, styles) |
279
- | `zquery dev [root]` | Dev server with live-reload, CSS hot-swap, error overlay, floating toolbar &amp; inspector panel (port 3100). Visit `/_devtools` for the standalone panel. `--index` for custom HTML, `--bundle` for bundled mode, `--no-intercept` to skip CDN intercept. |
279
+ | `zquery dev [root]` | Dev server with live-reload, CSS hot-swap, error overlay, expandable floating toolbar &amp; five-tab inspector panel (port 3100). Visit `/_devtools` for the standalone panel. `--index` for custom HTML, `--bundle` for bundled mode, `--no-intercept` to skip CDN intercept. |
280
280
  | `zquery bundle [dir\|file]` | Bundle app into a single IIFE file. Accepts dir or direct entry file. |
281
281
  | `zquery build` | Build the zQuery library (`dist/zquery.min.js`) |
282
282
  | `zquery --help` | Show CLI usage |
@@ -9,7 +9,7 @@
9
9
  <button class="viewport-btn" data-width="768" title="Tablet (768px)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="2" width="16" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12" y2="18"/></svg></button>
10
10
  <button class="viewport-btn active" data-width="0" title="Desktop (fill)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg></button>
11
11
  <span class="divider-sep"></span>
12
- <button id="btn-route" title="Current route"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="7" y1="2" x2="17" y2="22"/></svg></button>
12
+ <button id="btn-route" title="Current route"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="17" y1="2" x2="7" y2="22"/></svg></button>
13
13
  <span class="route-label" id="route-label">/</span>
14
14
  </div>
15
15
  </div>
@@ -558,6 +558,7 @@ const OVERLAY_SCRIPT = `<script>
558
558
  if (__zqChannel) {
559
559
  try { __zqChannel.postMessage({ type: 'router', data: evt }); } catch(e) {}
560
560
  }
561
+ updateDevBar();
561
562
  };
562
563
 
563
564
  var _origReplaceState = history.replaceState;
@@ -576,6 +577,7 @@ const OVERLAY_SCRIPT = `<script>
576
577
  if (__zqChannel) {
577
578
  try { __zqChannel.postMessage({ type: 'router', data: evt }); } catch(e) {}
578
579
  }
580
+ updateDevBar();
579
581
  };
580
582
 
581
583
  window.addEventListener('popstate', function(e) {
@@ -593,6 +595,7 @@ const OVERLAY_SCRIPT = `<script>
593
595
  if (__zqChannel) {
594
596
  try { __zqChannel.postMessage({ type: 'router', data: evt }); } catch(e) {}
595
597
  }
598
+ updateDevBar();
596
599
  });
597
600
 
598
601
  window.addEventListener('hashchange', function() {
@@ -606,36 +609,62 @@ const OVERLAY_SCRIPT = `<script>
606
609
  if (__zqChannel) {
607
610
  try { __zqChannel.postMessage({ type: 'router', data: evt }); } catch(e) {}
608
611
  }
612
+ updateDevBar();
609
613
  });
610
614
 
611
615
  // =====================================================================
612
- // Dev Toolbar — floating bar with DOM viewer button & request counter
616
+ // Dev Toolbar — expandable floating bar with stats
613
617
  // =====================================================================
614
618
  var devBar;
619
+ var __zqBarExpanded = false;
620
+ var __zqRouteColors = {
621
+ navigate: { bg: 'rgba(63,185,80,0.12)', fg: '#3fb950' },
622
+ replace: { bg: 'rgba(210,153,34,0.12)', fg: '#d29922' },
623
+ pop: { bg: 'rgba(248,81,73,0.12)', fg: '#f85149' },
624
+ 'pop-substate':{ bg: 'rgba(248,81,73,0.12)', fg: '#f85149' },
625
+ substate: { bg: 'rgba(168,130,255,0.12)', fg: '#a882ff' },
626
+ hashchange: { bg: 'rgba(88,166,255,0.12)', fg: '#58a6ff' }
627
+ };
628
+ var __zqRouteDefault = { bg: 'rgba(227,155,55,0.12)', fg: '#e39b37' };
629
+ var __zqRouteFadeTimer = null;
615
630
 
616
631
  function createDevBar() {
617
632
  devBar = document.createElement('div');
618
633
  devBar.id = '__zq_devbar';
619
634
  devBar.setAttribute('style',
620
635
  'position:fixed;bottom:12px;right:12px;z-index:2147483646;' +
621
- 'display:flex;align-items:center;gap:6px;' +
636
+ 'display:flex;align-items:center;gap:4px;' +
622
637
  'background:rgba(22,27,34,0.92);border:1px solid rgba(48,54,61,0.8);' +
623
638
  'border-radius:8px;padding:4px 6px;backdrop-filter:blur(8px);' +
624
639
  'font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;' +
625
640
  'font-size:11px;color:#8b949e;user-select:none;cursor:default;' +
626
- 'box-shadow:0 4px 12px rgba(0,0,0,0.4);'
641
+ 'box-shadow:0 4px 12px rgba(0,0,0,0.4);transition:all .25s cubic-bezier(.22,1,.36,1);'
627
642
  );
643
+
644
+ var statStyle = 'padding:2px 6px;border-radius:4px;font-size:10px;font-weight:600;cursor:pointer;white-space:nowrap;';
645
+ var expandedStyle = statStyle + 'display:none;transform:scale(0);opacity:0;transform-origin:left center;will-change:transform,opacity;transition:transform .25s cubic-bezier(.22,1,.36,1),opacity .2s ease;';
646
+
628
647
  devBar.innerHTML =
629
648
  '<span style="color:#58a6ff;font-weight:700;padding:0 4px;font-size:10px;letter-spacing:.5px">zQ</span>' +
630
- '<span id="__zq_bar_reqs" title="Network requests" style="padding:2px 6px;border-radius:4px;' +
631
- 'background:rgba(88,166,255,0.1);color:#58a6ff;cursor:pointer;font-size:10px;font-weight:600;">0 req</span>' +
632
- '<span id="__zq_bar_morphs" title="Render operations" style="padding:2px 6px;border-radius:4px;' +
633
- 'background:rgba(188,140,255,0.1);color:#bc8cff;cursor:pointer;font-size:10px;font-weight:600;">0 render</span>' +
634
- '<button id="__zq_bar_dom" title="Open DevTools (/_devtools)" style="' +
635
- 'padding:3px 8px;border-radius:4px;font-size:10px;font-weight:700;' +
636
- 'background:rgba(63,185,80,0.15);color:#3fb950;border:1px solid rgba(63,185,80,0.3);' +
637
- 'cursor:pointer;font-family:inherit;transition:all .15s;' +
638
- '">DOM</button>' +
649
+ // Expanded-only stats
650
+ '<span id="__zq_bar_route" class="__zq_ex" title="Current route" style="' + expandedStyle +
651
+ 'background:rgba(227,155,55,0.12);color:#e39b37;outline-offset:1px;transition:transform .25s cubic-bezier(.22,1,.36,1),opacity .2s ease,background .3s ease,color .3s ease,outline-color .6s ease;">/</span>' +
652
+ '<span id="__zq_bar_comps" class="__zq_ex" title="Registered components" style="' + expandedStyle +
653
+ 'background:rgba(168,130,255,0.1);color:#a882ff;">0 comps</span>' +
654
+ // Always-visible stats
655
+ '<span id="__zq_bar_morphs" title="Render operations" style="' + statStyle +
656
+ 'background:rgba(188,140,255,0.1);color:#bc8cff;">0 render</span>' +
657
+ '<span id="__zq_bar_reqs" title="Network requests" style="' + statStyle +
658
+ 'background:rgba(88,166,255,0.1);color:#58a6ff;">0 req</span>' +
659
+ // Expanded-only stats
660
+ '<span id="__zq_bar_els" class="__zq_ex" title="DOM elements" style="' + expandedStyle +
661
+ 'background:rgba(63,185,80,0.1);color:#3fb950;">0 els</span>' +
662
+ // Toggle expand/collapse
663
+ '<button id="__zq_bar_toggle" title="Expand toolbar" style="' +
664
+ 'padding:2px 6px;border-radius:4px;font-size:10px;font-weight:600;' +
665
+ 'background:rgba(88,166,255,0.08);color:#58a6ff;border:1px solid rgba(88,166,255,0.2);' +
666
+ 'cursor:pointer;font-family:inherit;transition:all .15s;line-height:1;' +
667
+ '"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 6 9 12 15 18"/></svg></button>' +
639
668
  '<button id="__zq_bar_close" title="Close toolbar" style="' +
640
669
  'padding:0 4px;color:#484f58;cursor:pointer;font-size:14px;border:none;' +
641
670
  'background:none;font-family:inherit;line-height:1;' +
@@ -657,28 +686,9 @@ const OVERLAY_SCRIPT = `<script>
657
686
  }
658
687
  }
659
688
 
660
- // Req counter → Network tab
661
- document.getElementById('__zq_bar_reqs').addEventListener('click', function() {
662
- if (isInSplitFrame()) {
663
- switchDevTab('network');
664
- } else {
665
- openDevToolsPopup('network');
666
- }
667
- });
668
-
669
- // Render counter → Performance tab
670
- document.getElementById('__zq_bar_morphs').addEventListener('click', function() {
671
- if (isInSplitFrame()) {
672
- switchDevTab('perf');
673
- } else {
674
- openDevToolsPopup('perf');
675
- }
676
- });
677
-
678
- // DOM button → Elements tab (in split) or open popup
689
+ // Open devtools popup
679
690
  var __zqPopup = null;
680
691
  function openDevToolsPopup(tab) {
681
- // If popup is already open, just switch the tab via BroadcastChannel
682
692
  if (__zqPopup && !__zqPopup.closed) {
683
693
  switchDevTab(tab);
684
694
  __zqPopup.focus();
@@ -693,26 +703,60 @@ const OVERLAY_SCRIPT = `<script>
693
703
  ',resizable=yes,scrollbars=yes');
694
704
  }
695
705
 
696
- document.getElementById('__zq_bar_dom').addEventListener('click', function() {
697
- if (isInSplitFrame()) {
698
- switchDevTab('dom');
706
+ function openTab(tab) {
707
+ if (isInSplitFrame()) { switchDevTab(tab); } else { openDevToolsPopup(tab); }
708
+ }
709
+
710
+ // Stat click handlers → open relevant devtools tab
711
+ document.getElementById('__zq_bar_route').addEventListener('click', function() { openTab('router'); });
712
+ document.getElementById('__zq_bar_comps').addEventListener('click', function() { openTab('components'); });
713
+ document.getElementById('__zq_bar_morphs').addEventListener('click', function() { openTab('perf'); });
714
+ document.getElementById('__zq_bar_reqs').addEventListener('click', function() { openTab('network'); });
715
+ document.getElementById('__zq_bar_els').addEventListener('click', function() { openTab('dom'); });
716
+
717
+ // Expand / collapse toggle
718
+ document.getElementById('__zq_bar_toggle').addEventListener('click', function() {
719
+ __zqBarExpanded = !__zqBarExpanded;
720
+ var items = devBar.querySelectorAll('.__zq_ex');
721
+ var btn = this;
722
+ if (__zqBarExpanded) {
723
+ btn.innerHTML = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 6 15 12 9 18"/></svg>';
724
+ btn.title = 'Collapse toolbar';
725
+ for (var i = 0; i < items.length; i++) {
726
+ items[i].style.display = 'inline';
727
+ items[i].offsetWidth; // reflow
728
+ items[i].style.transform = 'scale(1)';
729
+ items[i].style.opacity = '1';
730
+ }
731
+ updateDevBar();
699
732
  } else {
700
- openDevToolsPopup('dom');
733
+ btn.innerHTML = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 6 9 12 15 18"/></svg>';
734
+ btn.title = 'Expand toolbar';
735
+ for (var i = 0; i < items.length; i++) {
736
+ items[i].style.transform = 'scale(0)';
737
+ items[i].style.opacity = '0';
738
+ }
739
+ setTimeout(function() {
740
+ if (!__zqBarExpanded) {
741
+ var items = devBar.querySelectorAll('.__zq_ex');
742
+ for (var i = 0; i < items.length; i++) items[i].style.display = 'none';
743
+ }
744
+ }, 250);
701
745
  }
702
746
  });
703
747
 
748
+ // Toggle hover
749
+ document.getElementById('__zq_bar_toggle').addEventListener('mouseover', function() {
750
+ this.style.background = 'rgba(88,166,255,0.18)';
751
+ });
752
+ document.getElementById('__zq_bar_toggle').addEventListener('mouseout', function() {
753
+ this.style.background = 'rgba(88,166,255,0.08)';
754
+ });
755
+
704
756
  // Close button
705
757
  document.getElementById('__zq_bar_close').addEventListener('click', function() {
706
758
  devBar.style.display = 'none';
707
759
  });
708
-
709
- // Hover effects
710
- document.getElementById('__zq_bar_dom').addEventListener('mouseover', function() {
711
- this.style.background = 'rgba(63,185,80,0.3)';
712
- });
713
- document.getElementById('__zq_bar_dom').addEventListener('mouseout', function() {
714
- this.style.background = 'rgba(63,185,80,0.15)';
715
- });
716
760
  }
717
761
 
718
762
  function updateDevBar() {
@@ -721,6 +765,50 @@ const OVERLAY_SCRIPT = `<script>
721
765
  var morphEl = document.getElementById('__zq_bar_morphs');
722
766
  if (reqEl) reqEl.textContent = __zqRequests.length + ' req';
723
767
  if (morphEl) morphEl.textContent = __zqMorphCount + ' render';
768
+
769
+ if (__zqBarExpanded) {
770
+ var routeEl = document.getElementById('__zq_bar_route');
771
+ var compsEl = document.getElementById('__zq_bar_comps');
772
+ var elsEl = document.getElementById('__zq_bar_els');
773
+ if (routeEl) {
774
+ var lastEvt = __zqRouterEvents.length ? __zqRouterEvents[__zqRouterEvents.length - 1] : null;
775
+ var action = lastEvt ? lastEvt.action : '';
776
+ var path = location.pathname + location.hash;
777
+ if (path.length > 16) path = path.substring(0, 14) + '…';
778
+ var colors = __zqRouteColors[action] || __zqRouteDefault;
779
+ routeEl.style.background = colors.bg;
780
+ routeEl.style.color = colors.fg;
781
+ if (action) {
782
+ var label = action === 'pop-substate' ? 'pop' : action;
783
+ routeEl.textContent = label + ' ' + path;
784
+ routeEl.title = action + ' → ' + location.pathname + location.hash;
785
+ } else {
786
+ routeEl.textContent = path;
787
+ }
788
+ // Flash brightness on fresh events
789
+ if (lastEvt && (Date.now() - lastEvt.timestamp) < 2000) {
790
+ routeEl.style.outline = '1px solid ' + colors.fg;
791
+ clearTimeout(__zqRouteFadeTimer);
792
+ __zqRouteFadeTimer = setTimeout(function() {
793
+ var el = document.getElementById('__zq_bar_route');
794
+ if (el) el.style.outline = 'none';
795
+ }, 1800);
796
+ } else {
797
+ routeEl.style.outline = 'none';
798
+ }
799
+ }
800
+ if (compsEl) {
801
+ var count = 0;
802
+ try {
803
+ if (window.$ && $.components) count = Object.keys($.components()).length;
804
+ else if (window.$ && $._components) count = Object.keys($._components).length;
805
+ } catch(e) {}
806
+ compsEl.textContent = count + ' comps';
807
+ }
808
+ if (elsEl) {
809
+ elsEl.textContent = document.querySelectorAll('*').length + ' els';
810
+ }
811
+ }
724
812
  }
725
813
 
726
814
  // Expose for devtools popup
package/cli/utils.js CHANGED
@@ -11,6 +11,43 @@
11
11
  const fs = require('fs');
12
12
  const path = require('path');
13
13
 
14
+ // ---------------------------------------------------------------------------
15
+ // _copyTemplateLiteral — copy a template literal verbatim, tracking ${…}
16
+ // nesting so that `//` inside template text isn't mistaken for a comment.
17
+ // ---------------------------------------------------------------------------
18
+
19
+ function _copyTemplateLiteral(code, start) {
20
+ let out = '`';
21
+ let i = start + 1; // skip opening backtick
22
+ let depth = 0;
23
+ while (i < code.length) {
24
+ if (code[i] === '\\') { out += code[i] + (code[i + 1] || ''); i += 2; continue; }
25
+ if (code[i] === '$' && code[i + 1] === '{') { depth++; out += '${'; i += 2; continue; }
26
+ if (depth > 0) {
27
+ if (code[i] === '{') { depth++; out += code[i]; i++; continue; }
28
+ if (code[i] === '}') { depth--; out += code[i]; i++; continue; }
29
+ if (code[i] === '`') {
30
+ const nested = _copyTemplateLiteral(code, i);
31
+ out += nested.text; i = nested.end; continue;
32
+ }
33
+ if (code[i] === '"' || code[i] === "'") {
34
+ const q = code[i]; out += code[i]; i++;
35
+ while (i < code.length) {
36
+ if (code[i] === '\\') { out += code[i] + (code[i + 1] || ''); i += 2; continue; }
37
+ out += code[i];
38
+ if (code[i] === q) { i++; break; }
39
+ i++;
40
+ }
41
+ continue;
42
+ }
43
+ out += code[i]; i++; continue;
44
+ }
45
+ if (code[i] === '`') { out += '`'; i++; return { text: out, end: i }; }
46
+ out += code[i]; i++;
47
+ }
48
+ return { text: out, end: i };
49
+ }
50
+
14
51
  // ---------------------------------------------------------------------------
15
52
  // stripComments — context-aware, skips strings / templates / regex
16
53
  // ---------------------------------------------------------------------------
@@ -22,8 +59,8 @@ function stripComments(code) {
22
59
  const ch = code[i];
23
60
  const next = code[i + 1];
24
61
 
25
- // String literals
26
- if (ch === '"' || ch === "'" || ch === '`') {
62
+ // Regular string literals: copy verbatim
63
+ if (ch === '"' || ch === "'") {
27
64
  const quote = ch;
28
65
  out += ch; i++;
29
66
  while (i < code.length) {
@@ -35,6 +72,13 @@ function stripComments(code) {
35
72
  continue;
36
73
  }
37
74
 
75
+ // Template literal: copy verbatim with ${…} nesting support
76
+ if (ch === '`') {
77
+ const tpl = _copyTemplateLiteral(code, i);
78
+ out += tpl.text; i = tpl.end;
79
+ continue;
80
+ }
81
+
38
82
  // Block comment
39
83
  if (ch === '/' && next === '*') {
40
84
  i += 2;
@@ -105,8 +149,8 @@ function _minifyBody(code) {
105
149
  const ch = code[i];
106
150
  const nx = code[i + 1];
107
151
 
108
- // ── String / template literal: copy verbatim ────────────────
109
- if (ch === '"' || ch === "'" || ch === '`') {
152
+ // ── Regular string literal: copy verbatim ─────────────────
153
+ if (ch === '"' || ch === "'") {
110
154
  const q = ch;
111
155
  out += ch; i++;
112
156
  while (i < code.length) {
@@ -118,6 +162,13 @@ function _minifyBody(code) {
118
162
  continue;
119
163
  }
120
164
 
165
+ // ── Template literal: copy verbatim with ${…} nesting ───────
166
+ if (ch === '`') {
167
+ const tpl = _copyTemplateLiteral(code, i);
168
+ out += tpl.text; i = tpl.end;
169
+ continue;
170
+ }
171
+
121
172
  // ── Block comment: skip ─────────────────────────────────────
122
173
  if (ch === '/' && nx === '*') {
123
174
  i += 2;
Binary file
package/dist/zquery.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * zQuery (zeroQuery) v0.8.7
2
+ * zQuery (zeroQuery) v0.8.9
3
3
  * Lightweight Frontend Library
4
4
  * https://github.com/tonywied17/zero-query
5
5
  * (c) 2026 Anthony Wiedman - MIT License
@@ -5264,7 +5264,7 @@ $.guardCallback = guardCallback;
5264
5264
  $.validate = validate;
5265
5265
 
5266
5266
  // --- Meta ------------------------------------------------------------------
5267
- $.version = '0.8.7';
5267
+ $.version = '0.8.9';
5268
5268
  $.libSize = '~89 KB';
5269
5269
  $.meta = {}; // populated at build time by CLI bundler
5270
5270
 
@@ -1,7 +1,7 @@
1
1
  /**
2
- * zQuery (zeroQuery) v0.8.7
2
+ * zQuery (zeroQuery) v0.8.9
3
3
  * Lightweight Frontend Library
4
4
  * https://github.com/tonywied17/zero-query
5
5
  * (c) 2026 Anthony Wiedman - MIT License
6
6
  */
7
- (function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{s._value=fn();s._notify();});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=null;};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:[elements];this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(){const sibs=[];this.elements.forEach(el=>{sibs.push(...[...el.parentElement.children].filter(c=>c!==el));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();return el?Array.from(el.parentElement.children).indexOf(el):-1;}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props){if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){el.addEventListener(evt,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>el.removeEventListener(evt,handler));});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){return new Promise(resolve=>{const count={done:0};this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(++count.done>=this.length)resolve(this);};el.addEventListener('transitionend',onEnd);});});setTimeout(()=>resolve(this),duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const visible=getComputedStyle(el).opacity!=='0'&&getComputedStyle(el).display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(1);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){args.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){elements.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){const classExpr=this.parsePostfix();let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=node.args.map(a=>evaluate(a,scope));return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(value,scope);}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,scope));if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(!ast){const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}_morphNode(oldParent,oldNode,newNode);cursor=oldNode.nextSibling;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}for(let i=oldLen-1;i>=0;i--){if(!newNames.has(oldAttrs[i].name)){oldEl.removeAttribute(oldAttrs[i].name);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot');if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')||changedKey===key){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let inAtBlock=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(inAtBlock>0)inAtBlock--;return match;}const trimmed=selector.trim();if(trimmed.startsWith('@')){inAtBlock++;return match;}if(inAtBlock>0&&/^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g,''))){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};el.addEventListener(event,handler);});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];this._delegatedEvents=null;this._eventBindings=null;if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){window.addEventListener('hashchange',()=>this._resolve());}else{window.addEventListener('popstate',(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();});}document.addEventListener('click',(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}});if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=JSON.stringify(params)===JSON.stringify(from.params);const sameQuery=JSON.stringify(query)===JSON.stringify(from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);this._instance=mount(container,matched.component,props);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();fetchOpts.signal=options.signal||controller.signal;const timeout=options.timeout??_config.timeout;let timer;if(timeout>0){timer=setTimeout(()=>controller.abort(),timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},onRequest(fn){_interceptors.request.push(fn);},onResponse(fn){_interceptors.response.push(fn);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([a-z])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){for(const source of sources){for(const key of Object.keys(source)){if(source[key]&&typeof source[key]==='object'&&!Array.isArray(source[key])){if(!target[key]||typeof target[key]!=='object')target[key]={};deepMerge(target[key],source[key]);}else{target[key]=source[key];}}}return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k]));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.8.7';$.libSize='~89 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
7
+ (function(global){'use strict';const ErrorCode=Object.freeze({REACTIVE_CALLBACK:'ZQ_REACTIVE_CALLBACK',SIGNAL_CALLBACK:'ZQ_SIGNAL_CALLBACK',EFFECT_EXEC:'ZQ_EFFECT_EXEC',EXPR_PARSE:'ZQ_EXPR_PARSE',EXPR_EVAL:'ZQ_EXPR_EVAL',EXPR_UNSAFE_ACCESS:'ZQ_EXPR_UNSAFE_ACCESS',COMP_INVALID_NAME:'ZQ_COMP_INVALID_NAME',COMP_NOT_FOUND:'ZQ_COMP_NOT_FOUND',COMP_MOUNT_TARGET:'ZQ_COMP_MOUNT_TARGET',COMP_RENDER:'ZQ_COMP_RENDER',COMP_LIFECYCLE:'ZQ_COMP_LIFECYCLE',COMP_RESOURCE:'ZQ_COMP_RESOURCE',COMP_DIRECTIVE:'ZQ_COMP_DIRECTIVE',ROUTER_LOAD:'ZQ_ROUTER_LOAD',ROUTER_GUARD:'ZQ_ROUTER_GUARD',ROUTER_RESOLVE:'ZQ_ROUTER_RESOLVE',STORE_ACTION:'ZQ_STORE_ACTION',STORE_MIDDLEWARE:'ZQ_STORE_MIDDLEWARE',STORE_SUBSCRIBE:'ZQ_STORE_SUBSCRIBE',HTTP_REQUEST:'ZQ_HTTP_REQUEST',HTTP_TIMEOUT:'ZQ_HTTP_TIMEOUT',HTTP_INTERCEPTOR:'ZQ_HTTP_INTERCEPTOR',HTTP_PARSE:'ZQ_HTTP_PARSE',INVALID_ARGUMENT:'ZQ_INVALID_ARGUMENT',});class ZQueryError extends Error{constructor(code,message,context={},cause){super(message);this.name='ZQueryError';this.code=code;this.context=context;if(cause)this.cause=cause;}}let _errorHandler=null;function onError(handler){_errorHandler=typeof handler==='function'?handler:null;}function reportError(code,message,context={},cause){const err=cause instanceof ZQueryError?cause:new ZQueryError(code,message,context,cause);if(_errorHandler){try{_errorHandler(err);}catch{}}console.error(`[zQuery ${code}] ${message}`,context,cause||'');}function guardCallback(fn,code,context={}){return(...args)=>{try{return fn(...args);}catch(err){reportError(code,err.message||'Callback error',context,err);}};}function validate(value,name,expectedType){if(value===undefined||value===null){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" is required but got ${value}`);}if(expectedType&&typeof value!==expectedType){throw new ZQueryError(ErrorCode.INVALID_ARGUMENT,`"${name}" must be a ${expectedType}, got ${typeof value}`);}}function reactive(target,onChange,_path=''){if(typeof target!=='object'||target===null)return target;if(typeof onChange!=='function'){reportError(ErrorCode.REACTIVE_CALLBACK,'reactive() onChange must be a function',{received:typeof onChange});onChange=()=>{};}const proxyCache=new WeakMap();const handler={get(obj,key){if(key==='__isReactive')return true;if(key==='__raw')return obj;const value=obj[key];if(typeof value==='object'&&value!==null){if(proxyCache.has(value))return proxyCache.get(value);const childProxy=new Proxy(value,handler);proxyCache.set(value,childProxy);return childProxy;}return value;},set(obj,key,value){const old=obj[key];if(old===value)return true;obj[key]=value;if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,value,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,value,old},err);}return true;},deleteProperty(obj,key){const old=obj[key];delete obj[key];if(old&&typeof old==='object')proxyCache.delete(old);try{onChange(key,undefined,old);}catch(err){reportError(ErrorCode.REACTIVE_CALLBACK,`Reactive onChange threw for key "${String(key)}"`,{key,old},err);}return true;}};return new Proxy(target,handler);}class Signal{constructor(value){this._value=value;this._subscribers=new Set();}get value(){if(Signal._activeEffect){this._subscribers.add(Signal._activeEffect);if(Signal._activeEffect._deps){Signal._activeEffect._deps.add(this);}}return this._value;}set value(newVal){if(this._value===newVal)return;this._value=newVal;this._notify();}peek(){return this._value;}_notify(){const subs=[...this._subscribers];for(let i=0;i<subs.length;i++){try{subs[i]();}catch(err){reportError(ErrorCode.SIGNAL_CALLBACK,'Signal subscriber threw',{signal:this},err);}}}subscribe(fn){this._subscribers.add(fn);return()=>this._subscribers.delete(fn);}toString(){return String(this._value);}}Signal._activeEffect=null;function signal(initial){return new Signal(initial);}function computed(fn){const s=new Signal(undefined);effect(()=>{s._value=fn();s._notify();});return s;}function effect(fn){const execute=()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=execute;try{fn();}catch(err){reportError(ErrorCode.EFFECT_EXEC,'Effect function threw',{},err);}finally{Signal._activeEffect=null;}};execute._deps=new Set();execute();return()=>{if(execute._deps){for(const sig of execute._deps){sig._subscribers.delete(execute);}execute._deps.clear();}Signal._activeEffect=null;};}class ZQueryCollection{constructor(elements){this.elements=Array.isArray(elements)?elements:[elements];this.length=this.elements.length;this.elements.forEach((el,i)=>{this[i]=el;});}each(fn){this.elements.forEach((el,i)=>fn.call(el,i,el));return this;}map(fn){return this.elements.map((el,i)=>fn.call(el,i,el));}forEach(fn){this.elements.forEach((el,i)=>fn(el,i,this.elements));return this;}first(){return this.elements[0]||null;}last(){return this.elements[this.length-1]||null;}eq(i){return new ZQueryCollection(this.elements[i]?[this.elements[i]]:[]);}toArray(){return[...this.elements];}[Symbol.iterator](){return this.elements[Symbol.iterator]();}find(selector){const found=[];this.elements.forEach(el=>found.push(...el.querySelectorAll(selector)));return new ZQueryCollection(found);}parent(){const parents=[...new Set(this.elements.map(el=>el.parentElement).filter(Boolean))];return new ZQueryCollection(parents);}closest(selector){return new ZQueryCollection(this.elements.map(el=>el.closest(selector)).filter(Boolean));}children(selector){const kids=[];this.elements.forEach(el=>{kids.push(...(selector?el.querySelectorAll(`:scope > ${selector}`):el.children));});return new ZQueryCollection([...kids]);}siblings(){const sibs=[];this.elements.forEach(el=>{sibs.push(...[...el.parentElement.children].filter(c=>c!==el));});return new ZQueryCollection(sibs);}next(selector){const els=this.elements.map(el=>el.nextElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}prev(selector){const els=this.elements.map(el=>el.previousElementSibling).filter(Boolean);return new ZQueryCollection(selector?els.filter(el=>el.matches(selector)):els);}nextAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}nextUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.nextElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.nextElementSibling;}});return new ZQueryCollection(result);}prevAll(selector){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(!selector||sib.matches(selector))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}prevUntil(selector,filter){const result=[];this.elements.forEach(el=>{let sib=el.previousElementSibling;while(sib){if(selector&&sib.matches(selector))break;if(!filter||sib.matches(filter))result.push(sib);sib=sib.previousElementSibling;}});return new ZQueryCollection(result);}parents(selector){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(!selector||parent.matches(selector))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}parentsUntil(selector,filter){const result=[];this.elements.forEach(el=>{let parent=el.parentElement;while(parent){if(selector&&parent.matches(selector))break;if(!filter||parent.matches(filter))result.push(parent);parent=parent.parentElement;}});return new ZQueryCollection([...new Set(result)]);}contents(){const result=[];this.elements.forEach(el=>result.push(...el.childNodes));return new ZQueryCollection(result);}filter(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter(selector));}return new ZQueryCollection(this.elements.filter(el=>el.matches(selector)));}not(selector){if(typeof selector==='function'){return new ZQueryCollection(this.elements.filter((el,i)=>!selector.call(el,i,el)));}return new ZQueryCollection(this.elements.filter(el=>!el.matches(selector)));}has(selector){return new ZQueryCollection(this.elements.filter(el=>el.querySelector(selector)));}is(selector){if(typeof selector==='function'){return this.elements.some((el,i)=>selector.call(el,i,el));}return this.elements.some(el=>el.matches(selector));}slice(start,end){return new ZQueryCollection(this.elements.slice(start,end));}add(selector,context){const toAdd=(selector instanceof ZQueryCollection)?selector.elements:(selector instanceof Node)?[selector]:Array.from((context||document).querySelectorAll(selector));return new ZQueryCollection([...this.elements,...toAdd]);}get(index){if(index===undefined)return[...this.elements];return index<0?this.elements[this.length+index]:this.elements[index];}index(selector){if(selector===undefined){const el=this.first();return el?Array.from(el.parentElement.children).indexOf(el):-1;}const target=(typeof selector==='string')?document.querySelector(selector):selector;return this.elements.indexOf(target);}addClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.add(...classes);return this;}removeClass(...names){if(names.length===1&&names[0].indexOf(' ')===-1){const c=names[0];for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(c);return this;}const classes=names.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++)this.elements[i].classList.remove(...classes);return this;}toggleClass(...args){const force=typeof args[args.length-1]==='boolean'?args.pop():undefined;if(args.length===1&&args[0].indexOf(' ')===-1){const c=args[0];for(let i=0;i<this.elements.length;i++){force!==undefined?this.elements[i].classList.toggle(c,force):this.elements[i].classList.toggle(c);}return this;}const classes=args.flatMap(n=>n.split(/\s+/));for(let i=0;i<this.elements.length;i++){const el=this.elements[i];for(let j=0;j<classes.length;j++){force!==undefined?el.classList.toggle(classes[j],force):el.classList.toggle(classes[j]);}}return this;}hasClass(name){return this.first()?.classList.contains(name)||false;}attr(name,value){if(value===undefined)return this.first()?.getAttribute(name);return this.each((_,el)=>el.setAttribute(name,value));}removeAttr(name){return this.each((_,el)=>el.removeAttribute(name));}prop(name,value){if(value===undefined)return this.first()?.[name];return this.each((_,el)=>{el[name]=value;});}data(key,value){if(value===undefined){if(key===undefined)return this.first()?.dataset;const raw=this.first()?.dataset[key];try{return JSON.parse(raw);}catch{return raw;}}return this.each((_,el)=>{el.dataset[key]=typeof value==='object'?JSON.stringify(value):value;});}css(props){if(typeof props==='string'){const el=this.first();return el?getComputedStyle(el)[props]:undefined;}return this.each((_,el)=>Object.assign(el.style,props));}width(){return this.first()?.getBoundingClientRect().width;}height(){return this.first()?.getBoundingClientRect().height;}offset(){const r=this.first()?.getBoundingClientRect();return r?{top:r.top+window.scrollY,left:r.left+window.scrollX,width:r.width,height:r.height}:null;}position(){const el=this.first();return el?{top:el.offsetTop,left:el.offsetLeft}:null;}scrollTop(value){if(value===undefined){const el=this.first();return el===window?window.scrollY:el?.scrollTop;}return this.each((_,el)=>{if(el===window)window.scrollTo(window.scrollX,value);else el.scrollTop=value;});}scrollLeft(value){if(value===undefined){const el=this.first();return el===window?window.scrollX:el?.scrollLeft;}return this.each((_,el)=>{if(el===window)window.scrollTo(value,window.scrollY);else el.scrollLeft=value;});}innerWidth(){const el=this.first();return el?.clientWidth;}innerHeight(){const el=this.first();return el?.clientHeight;}outerWidth(includeMargin=false){const el=this.first();if(!el)return undefined;let w=el.offsetWidth;if(includeMargin){const style=getComputedStyle(el);w+=parseFloat(style.marginLeft)+parseFloat(style.marginRight);}return w;}outerHeight(includeMargin=false){const el=this.first();if(!el)return undefined;let h=el.offsetHeight;if(includeMargin){const style=getComputedStyle(el);h+=parseFloat(style.marginTop)+parseFloat(style.marginBottom);}return h;}html(content){if(content===undefined)return this.first()?.innerHTML;return this.each((_,el)=>{if(el.childNodes.length>0){_morph(el,content);}else{el.innerHTML=content;}});}morph(content){return this.each((_,el)=>{_morph(el,content);});}text(content){if(content===undefined)return this.first()?.textContent;return this.each((_,el)=>{el.textContent=content;});}val(value){if(value===undefined)return this.first()?.value;return this.each((_,el)=>{el.value=value;});}append(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforeend',content);else if(content instanceof ZQueryCollection)content.each((__,c)=>el.appendChild(c));else if(content instanceof Node)el.appendChild(content);});}prepend(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterbegin',content);else if(content instanceof Node)el.insertBefore(content,el.firstChild);});}after(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('afterend',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el.nextSibling);});}before(content){return this.each((_,el)=>{if(typeof content==='string')el.insertAdjacentHTML('beforebegin',content);else if(content instanceof Node)el.parentNode.insertBefore(content,el);});}wrap(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);el.parentNode.insertBefore(w,el);w.appendChild(el);});}remove(){return this.each((_,el)=>el.remove());}empty(){return this.each((_,el)=>{el.textContent='';});}clone(deep=true){return new ZQueryCollection(this.elements.map(el=>el.cloneNode(deep)));}replaceWith(content){return this.each((_,el)=>{if(typeof content==='string'){_morphElement(el,content);}else if(content instanceof Node){el.parentNode.replaceChild(content,el);}});}appendTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.appendChild(el));return this;}prependTo(target){const dest=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(dest)this.each((_,el)=>dest.insertBefore(el,dest.firstChild));return this;}insertAfter(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref.nextSibling));return this;}insertBefore(target){const ref=typeof target==='string'?document.querySelector(target):target instanceof ZQueryCollection?target.first():target;if(ref&&ref.parentNode)this.each((_,el)=>ref.parentNode.insertBefore(el,ref));return this;}replaceAll(target){const targets=typeof target==='string'?Array.from(document.querySelectorAll(target)):target instanceof ZQueryCollection?target.elements:[target];targets.forEach((t,i)=>{const nodes=i===0?this.elements:this.elements.map(el=>el.cloneNode(true));nodes.forEach(el=>t.parentNode.insertBefore(el,t));t.remove();});return this;}unwrap(selector){this.elements.forEach(el=>{const parent=el.parentElement;if(!parent||parent===document.body)return;if(selector&&!parent.matches(selector))return;parent.replaceWith(...parent.childNodes);});return this;}wrapAll(wrapper){const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);const first=this.first();if(!first)return this;first.parentNode.insertBefore(w,first);this.each((_,el)=>w.appendChild(el));return this;}wrapInner(wrapper){return this.each((_,el)=>{const w=typeof wrapper==='string'?createFragment(wrapper).firstElementChild:wrapper.cloneNode(true);while(el.firstChild)w.appendChild(el.firstChild);el.appendChild(w);});}detach(){return this.each((_,el)=>el.remove());}show(display=''){return this.each((_,el)=>{el.style.display=display;});}hide(){return this.each((_,el)=>{el.style.display='none';});}toggle(display=''){return this.each((_,el)=>{const hidden=el.style.display==='none'||(el.style.display!==''?false:getComputedStyle(el).display==='none');el.style.display=hidden?display:'none';});}on(event,selectorOrHandler,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>{if(typeof selectorOrHandler==='function'){el.addEventListener(evt,selectorOrHandler);}else if(typeof selectorOrHandler==='string'){el.addEventListener(evt,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target&&el.contains(target))handler.call(target,e);});}});});}off(event,handler){const events=event.split(/\s+/);return this.each((_,el)=>{events.forEach(evt=>el.removeEventListener(evt,handler));});}one(event,handler){return this.each((_,el)=>{el.addEventListener(event,handler,{once:true});});}trigger(event,detail){return this.each((_,el)=>{el.dispatchEvent(new CustomEvent(event,{detail,bubbles:true,cancelable:true}));});}click(fn){return fn?this.on('click',fn):this.trigger('click');}submit(fn){return fn?this.on('submit',fn):this.trigger('submit');}focus(){this.first()?.focus();return this;}blur(){this.first()?.blur();return this;}hover(enterFn,leaveFn){this.on('mouseenter',enterFn);return this.on('mouseleave',leaveFn||enterFn);}animate(props,duration=300,easing='ease'){return new Promise(resolve=>{const count={done:0};this.each((_,el)=>{el.style.transition=`all ${duration}ms ${easing}`;requestAnimationFrame(()=>{Object.assign(el.style,props);const onEnd=()=>{el.removeEventListener('transitionend',onEnd);el.style.transition='';if(++count.done>=this.length)resolve(this);};el.addEventListener('transitionend',onEnd);});});setTimeout(()=>resolve(this),duration+50);});}fadeIn(duration=300){return this.css({opacity:'0',display:''}).animate({opacity:'1'},duration);}fadeOut(duration=300){return this.animate({opacity:'0'},duration).then(col=>col.hide());}fadeToggle(duration=300){return Promise.all(this.elements.map(el=>{const visible=getComputedStyle(el).opacity!=='0'&&getComputedStyle(el).display!=='none';const col=new ZQueryCollection([el]);return visible?col.fadeOut(duration):col.fadeIn(duration);})).then(()=>this);}fadeTo(duration,opacity){return this.animate({opacity:String(opacity)},duration);}slideDown(duration=300){return this.each((_,el)=>{el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideUp(duration=300){return this.each((_,el)=>{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);});}slideToggle(duration=300){return this.each((_,el)=>{if(el.style.display==='none'||getComputedStyle(el).display==='none'){el.style.display='';el.style.overflow='hidden';const h=el.scrollHeight+'px';el.style.maxHeight='0';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight=h;});setTimeout(()=>{el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}else{el.style.overflow='hidden';el.style.maxHeight=el.scrollHeight+'px';el.style.transition=`max-height ${duration}ms ease`;requestAnimationFrame(()=>{el.style.maxHeight='0';});setTimeout(()=>{el.style.display='none';el.style.maxHeight='';el.style.overflow='';el.style.transition='';},duration);}});}serialize(){const form=this.first();if(!form||form.tagName!=='FORM')return'';return new URLSearchParams(new FormData(form)).toString();}serializeObject(){const form=this.first();if(!form||form.tagName!=='FORM')return{};const obj={};new FormData(form).forEach((v,k)=>{if(obj[k]!==undefined){if(!Array.isArray(obj[k]))obj[k]=[obj[k]];obj[k].push(v);}else{obj[k]=v;}});return obj;}}function createFragment(html){const tpl=document.createElement('template');tpl.innerHTML=html.trim();return tpl.content;}function query(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}function queryAll(selector,context){if(!selector)return new ZQueryCollection([]);if(selector instanceof ZQueryCollection)return selector;if(selector instanceof Node||selector===window){return new ZQueryCollection([selector]);}if(selector instanceof NodeList||selector instanceof HTMLCollection||Array.isArray(selector)){return new ZQueryCollection(Array.from(selector));}if(typeof selector==='string'&&selector.trim().startsWith('<')){const fragment=createFragment(selector);return new ZQueryCollection([...fragment.childNodes].filter(n=>n.nodeType===1));}if(typeof selector==='string'){const root=context?(typeof context==='string'?document.querySelector(context):context):document;return new ZQueryCollection([...root.querySelectorAll(selector)]);}return new ZQueryCollection([]);}query.id=(id)=>document.getElementById(id);query.class=(name)=>document.querySelector(`.${name}`);query.classes=(name)=>new ZQueryCollection(Array.from(document.getElementsByClassName(name)));query.tag=(name)=>new ZQueryCollection(Array.from(document.getElementsByTagName(name)));Object.defineProperty(query,'name',{value:(name)=>new ZQueryCollection(Array.from(document.getElementsByName(name))),writable:true,configurable:true});query.children=(parentId)=>{const p=document.getElementById(parentId);return new ZQueryCollection(p?Array.from(p.children):[]);};query.create=(tag,attrs={},...children)=>{const el=document.createElement(tag);for(const[k,v]of Object.entries(attrs)){if(k==='class')el.className=v;else if(k==='style'&&typeof v==='object')Object.assign(el.style,v);else if(k.startsWith('on')&&typeof v==='function')el.addEventListener(k.slice(2),v);else if(k==='data'&&typeof v==='object')Object.entries(v).forEach(([dk,dv])=>{el.dataset[dk]=dv;});else el.setAttribute(k,v);}children.flat().forEach(child=>{if(typeof child==='string')el.appendChild(document.createTextNode(child));else if(child instanceof Node)el.appendChild(child);});return new ZQueryCollection(el);};query.ready=(fn)=>{if(document.readyState!=='loading')fn();else document.addEventListener('DOMContentLoaded',fn);};query.on=(event,selectorOrHandler,handler)=>{if(typeof selectorOrHandler==='function'){document.addEventListener(event,selectorOrHandler);return;}if(typeof selectorOrHandler==='object'&&typeof selectorOrHandler.addEventListener==='function'){selectorOrHandler.addEventListener(event,handler);return;}document.addEventListener(event,(e)=>{if(!e.target||typeof e.target.closest!=='function')return;const target=e.target.closest(selectorOrHandler);if(target)handler.call(target,e);});};query.off=(event,handler)=>{document.removeEventListener(event,handler);};query.fn=ZQueryCollection.prototype;const T={NUM:1,STR:2,IDENT:3,OP:4,PUNC:5,TMPL:6,EOF:7};const PREC={'??':2,'||':3,'&&':4,'==':8,'!=':8,'===':8,'!==':8,'<':9,'>':9,'<=':9,'>=':9,'instanceof':9,'in':9,'+':11,'-':11,'*':12,'/':12,'%':12,};const KEYWORDS=new Set(['true','false','null','undefined','typeof','instanceof','in','new','void']);function tokenize(expr){const tokens=[];let i=0;const len=expr.length;while(i<len){const ch=expr[i];if(ch===' '||ch==='\t'||ch==='\n'||ch==='\r'){i++;continue;}if((ch>='0'&&ch<='9')||(ch==='.'&&i+1<len&&expr[i+1]>='0'&&expr[i+1]<='9')){let num='';if(ch==='0'&&i+1<len&&(expr[i+1]==='x'||expr[i+1]==='X')){num='0x';i+=2;while(i<len&&/[0-9a-fA-F]/.test(expr[i]))num+=expr[i++];}else{while(i<len&&((expr[i]>='0'&&expr[i]<='9')||expr[i]==='.'))num+=expr[i++];if(i<len&&(expr[i]==='e'||expr[i]==='E')){num+=expr[i++];if(i<len&&(expr[i]==='+'||expr[i]==='-'))num+=expr[i++];while(i<len&&expr[i]>='0'&&expr[i]<='9')num+=expr[i++];}}tokens.push({t:T.NUM,v:Number(num)});continue;}if(ch==="'"||ch==='"'){const quote=ch;let str='';i++;while(i<len&&expr[i]!==quote){if(expr[i]==='\\'&&i+1<len){const esc=expr[++i];if(esc==='n')str+='\n';else if(esc==='t')str+='\t';else if(esc==='r')str+='\r';else if(esc==='\\')str+='\\';else if(esc===quote)str+=quote;else str+=esc;}else{str+=expr[i];}i++;}i++;tokens.push({t:T.STR,v:str});continue;}if(ch==='`'){const parts=[];let str='';i++;while(i<len&&expr[i]!=='`'){if(expr[i]==='$'&&i+1<len&&expr[i+1]==='{'){parts.push(str);str='';i+=2;let depth=1;let inner='';while(i<len&&depth>0){if(expr[i]==='{')depth++;else if(expr[i]==='}'){depth--;if(depth===0)break;}inner+=expr[i++];}i++;parts.push({expr:inner});}else{if(expr[i]==='\\'&&i+1<len){str+=expr[++i];}else str+=expr[i];i++;}}i++;parts.push(str);tokens.push({t:T.TMPL,v:parts});continue;}if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||ch==='_'||ch==='$'){let ident='';while(i<len&&/[\w$]/.test(expr[i]))ident+=expr[i++];tokens.push({t:T.IDENT,v:ident});continue;}const two=expr.slice(i,i+3);if(two==='==='||two==='!=='||two==='?.'){if(two==='?.'){tokens.push({t:T.OP,v:'?.'});i+=2;}else{tokens.push({t:T.OP,v:two});i+=3;}continue;}const pair=expr.slice(i,i+2);if(pair==='=='||pair==='!='||pair==='<='||pair==='>='||pair==='&&'||pair==='||'||pair==='??'||pair==='?.'||pair==='=>'){tokens.push({t:T.OP,v:pair});i+=2;continue;}if('+-*/%'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('<>=!'.includes(ch)){tokens.push({t:T.OP,v:ch});i++;continue;}if('()[]{},.?:'.includes(ch)){tokens.push({t:T.PUNC,v:ch});i++;continue;}i++;}tokens.push({t:T.EOF,v:null});return tokens;}class Parser{constructor(tokens,scope){this.tokens=tokens;this.pos=0;this.scope=scope;}peek(){return this.tokens[this.pos];}next(){return this.tokens[this.pos++];}expect(type,val){const t=this.next();if(t.t!==type||(val!==undefined&&t.v!==val)){throw new Error(`Expected ${val || type} but got ${t.v}`);}return t;}match(type,val){const t=this.peek();if(t.t===type&&(val===undefined||t.v===val)){return this.next();}return null;}parse(){const result=this.parseExpression(0);return result;}parseExpression(minPrec){let left=this.parseUnary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='?'){if(this.tokens[this.pos+1]?.v!=='.'){if(1<=minPrec)break;this.next();const truthy=this.parseExpression(0);this.expect(T.PUNC,':');const falsy=this.parseExpression(1);left={type:'ternary',cond:left,truthy,falsy};continue;}}if(tok.t===T.OP&&tok.v in PREC){const prec=PREC[tok.v];if(prec<=minPrec)break;this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}if(tok.t===T.IDENT&&(tok.v==='instanceof'||tok.v==='in')&&PREC[tok.v]>minPrec){const prec=PREC[tok.v];this.next();const right=this.parseExpression(prec);left={type:'binary',op:tok.v,left,right};continue;}break;}return left;}parseUnary(){const tok=this.peek();if(tok.t===T.IDENT&&tok.v==='typeof'){this.next();const arg=this.parseUnary();return{type:'typeof',arg};}if(tok.t===T.IDENT&&tok.v==='void'){this.next();this.parseUnary();return{type:'literal',value:undefined};}if(tok.t===T.OP&&tok.v==='!'){this.next();const arg=this.parseUnary();return{type:'not',arg};}if(tok.t===T.OP&&(tok.v==='-'||tok.v==='+')){this.next();const arg=this.parseUnary();return{type:'unary',op:tok.v,arg};}return this.parsePostfix();}parsePostfix(){let left=this.parsePrimary();while(true){const tok=this.peek();if(tok.t===T.PUNC&&tok.v==='.'){this.next();const prop=this.next();left={type:'member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.OP&&tok.v==='?.'){this.next();const next=this.peek();if(next.t===T.PUNC&&next.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'optional_member',obj:left,prop,computed:true};}else if(next.t===T.PUNC&&next.v==='('){left={type:'optional_call',callee:left,args:this._parseArgs()};}else{const prop=this.next();left={type:'optional_member',obj:left,prop:prop.v,computed:false};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}}continue;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const prop=this.parseExpression(0);this.expect(T.PUNC,']');left={type:'member',obj:left,prop,computed:true};if(this.peek().t===T.PUNC&&this.peek().v==='('){left=this._parseCall(left);}continue;}if(tok.t===T.PUNC&&tok.v==='('){left=this._parseCall(left);continue;}break;}return left;}_parseCall(callee){const args=this._parseArgs();return{type:'call',callee,args};}_parseArgs(){this.expect(T.PUNC,'(');const args=[];while(!(this.peek().t===T.PUNC&&this.peek().v===')')&&this.peek().t!==T.EOF){args.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,')');return args;}parsePrimary(){const tok=this.peek();if(tok.t===T.NUM){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.STR){this.next();return{type:'literal',value:tok.v};}if(tok.t===T.TMPL){this.next();return{type:'template',parts:tok.v};}if(tok.t===T.PUNC&&tok.v==='('){const savedPos=this.pos;this.next();const params=[];let couldBeArrow=true;if(this.peek().t===T.PUNC&&this.peek().v===')'){}else{while(couldBeArrow){const p=this.peek();if(p.t===T.IDENT&&!KEYWORDS.has(p.v)){params.push(this.next().v);if(this.peek().t===T.PUNC&&this.peek().v===','){this.next();}else{break;}}else{couldBeArrow=false;}}}if(couldBeArrow&&this.peek().t===T.PUNC&&this.peek().v===')'){this.next();if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params,body};}}this.pos=savedPos;this.next();const expr=this.parseExpression(0);this.expect(T.PUNC,')');return expr;}if(tok.t===T.PUNC&&tok.v==='['){this.next();const elements=[];while(!(this.peek().t===T.PUNC&&this.peek().v===']')&&this.peek().t!==T.EOF){elements.push(this.parseExpression(0));if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,']');return{type:'array',elements};}if(tok.t===T.PUNC&&tok.v==='{'){this.next();const properties=[];while(!(this.peek().t===T.PUNC&&this.peek().v==='}')&&this.peek().t!==T.EOF){const keyTok=this.next();let key;if(keyTok.t===T.IDENT||keyTok.t===T.STR)key=keyTok.v;else if(keyTok.t===T.NUM)key=String(keyTok.v);else throw new Error('Invalid object key: '+keyTok.v);if(this.peek().t===T.PUNC&&(this.peek().v===','||this.peek().v==='}')){properties.push({key,value:{type:'ident',name:key}});}else{this.expect(T.PUNC,':');properties.push({key,value:this.parseExpression(0)});}if(this.peek().t===T.PUNC&&this.peek().v===',')this.next();}this.expect(T.PUNC,'}');return{type:'object',properties};}if(tok.t===T.IDENT){this.next();if(tok.v==='true')return{type:'literal',value:true};if(tok.v==='false')return{type:'literal',value:false};if(tok.v==='null')return{type:'literal',value:null};if(tok.v==='undefined')return{type:'literal',value:undefined};if(tok.v==='new'){const classExpr=this.parsePostfix();let args=[];if(this.peek().t===T.PUNC&&this.peek().v==='('){args=this._parseArgs();}return{type:'new',callee:classExpr,args};}if(this.peek().t===T.OP&&this.peek().v==='=>'){this.next();const body=this.parseExpression(0);return{type:'arrow',params:[tok.v],body};}return{type:'ident',name:tok.v};}this.next();return{type:'literal',value:undefined};}}const SAFE_ARRAY_METHODS=new Set(['length','map','filter','find','findIndex','some','every','reduce','reduceRight','forEach','includes','indexOf','lastIndexOf','join','slice','concat','flat','flatMap','reverse','sort','fill','keys','values','entries','at','toString',]);const SAFE_STRING_METHODS=new Set(['length','charAt','charCodeAt','includes','indexOf','lastIndexOf','slice','substring','trim','trimStart','trimEnd','toLowerCase','toUpperCase','split','replace','replaceAll','match','search','startsWith','endsWith','padStart','padEnd','repeat','at','toString','valueOf',]);const SAFE_NUMBER_METHODS=new Set(['toFixed','toPrecision','toString','valueOf',]);const SAFE_OBJECT_METHODS=new Set(['hasOwnProperty','toString','valueOf',]);const SAFE_MATH_PROPS=new Set(['PI','E','LN2','LN10','LOG2E','LOG10E','SQRT2','SQRT1_2','abs','ceil','floor','round','trunc','max','min','pow','sqrt','sign','random','log','log2','log10',]);const SAFE_JSON_PROPS=new Set(['parse','stringify']);function _isSafeAccess(obj,prop){const BLOCKED=new Set(['constructor','__proto__','prototype','__defineGetter__','__defineSetter__','__lookupGetter__','__lookupSetter__',]);if(typeof prop==='string'&&BLOCKED.has(prop))return false;if(obj!==null&&obj!==undefined&&(typeof obj==='object'||typeof obj==='function'))return true;if(typeof obj==='string')return SAFE_STRING_METHODS.has(prop);if(typeof obj==='number')return SAFE_NUMBER_METHODS.has(prop);return false;}function evaluate(node,scope){if(!node)return undefined;switch(node.type){case'literal':return node.value;case'ident':{const name=node.name;for(const layer of scope){if(layer&&typeof layer==='object'&&name in layer){return layer[name];}}if(name==='Math')return Math;if(name==='JSON')return JSON;if(name==='Date')return Date;if(name==='Array')return Array;if(name==='Object')return Object;if(name==='String')return String;if(name==='Number')return Number;if(name==='Boolean')return Boolean;if(name==='parseInt')return parseInt;if(name==='parseFloat')return parseFloat;if(name==='isNaN')return isNaN;if(name==='isFinite')return isFinite;if(name==='Infinity')return Infinity;if(name==='NaN')return NaN;if(name==='encodeURIComponent')return encodeURIComponent;if(name==='decodeURIComponent')return decodeURIComponent;if(name==='console')return console;return undefined;}case'template':{let result='';for(const part of node.parts){if(typeof part==='string'){result+=part;}else if(part&&part.expr){result+=String(safeEval(part.expr,scope)??'');}}return result;}case'member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'optional_member':{const obj=evaluate(node.obj,scope);if(obj==null)return undefined;const prop=node.computed?evaluate(node.prop,scope):node.prop;if(!_isSafeAccess(obj,prop))return undefined;return obj[prop];}case'call':{const result=_resolveCall(node,scope,false);return result;}case'optional_call':{const callee=evaluate(node.callee,scope);if(callee==null)return undefined;if(typeof callee!=='function')return undefined;const args=node.args.map(a=>evaluate(a,scope));return callee(...args);}case'new':{const Ctor=evaluate(node.callee,scope);if(typeof Ctor!=='function')return undefined;if(Ctor===Date||Ctor===Array||Ctor===Map||Ctor===Set||Ctor===RegExp||Ctor===Error||Ctor===URL||Ctor===URLSearchParams){const args=node.args.map(a=>evaluate(a,scope));return new Ctor(...args);}return undefined;}case'binary':return _evalBinary(node,scope);case'unary':{const val=evaluate(node.arg,scope);return node.op==='-'?-val:+val;}case'not':return!evaluate(node.arg,scope);case'typeof':{try{return typeof evaluate(node.arg,scope);}catch{return'undefined';}}case'ternary':{const cond=evaluate(node.cond,scope);return cond?evaluate(node.truthy,scope):evaluate(node.falsy,scope);}case'array':return node.elements.map(e=>evaluate(e,scope));case'object':{const obj={};for(const{key,value}of node.properties){obj[key]=evaluate(value,scope);}return obj;}case'arrow':{const paramNames=node.params;const bodyNode=node.body;const closedScope=scope;return function(...args){const arrowScope={};paramNames.forEach((name,i)=>{arrowScope[name]=args[i];});return evaluate(bodyNode,[arrowScope,...closedScope]);};}default:return undefined;}}function _resolveCall(node,scope){const callee=node.callee;const args=node.args.map(a=>evaluate(a,scope));if(callee.type==='member'||callee.type==='optional_member'){const obj=evaluate(callee.obj,scope);if(obj==null)return undefined;const prop=callee.computed?evaluate(callee.prop,scope):callee.prop;if(!_isSafeAccess(obj,prop))return undefined;const fn=obj[prop];if(typeof fn!=='function')return undefined;return fn.apply(obj,args);}const fn=evaluate(callee,scope);if(typeof fn!=='function')return undefined;return fn(...args);}function _evalBinary(node,scope){if(node.op==='&&'){const left=evaluate(node.left,scope);return left?evaluate(node.right,scope):left;}if(node.op==='||'){const left=evaluate(node.left,scope);return left?left:evaluate(node.right,scope);}if(node.op==='??'){const left=evaluate(node.left,scope);return left!=null?left:evaluate(node.right,scope);}const left=evaluate(node.left,scope);const right=evaluate(node.right,scope);switch(node.op){case'+':return left+right;case'-':return left-right;case'*':return left*right;case'/':return left/right;case'%':return left%right;case'==':return left==right;case'!=':return left!=right;case'===':return left===right;case'!==':return left!==right;case'<':return left<right;case'>':return left>right;case'<=':return left<=right;case'>=':return left>=right;case'instanceof':return left instanceof right;case'in':return left in right;default:return undefined;}}const _astCache=new Map();const _AST_CACHE_MAX=512;function safeEval(expr,scope){try{const trimmed=expr.trim();if(!trimmed)return undefined;if(/^[a-zA-Z_$][\w$]*$/.test(trimmed)){for(const layer of scope){if(layer&&typeof layer==='object'&&trimmed in layer){return layer[trimmed];}}}let ast=_astCache.get(trimmed);if(!ast){const tokens=tokenize(trimmed);const parser=new Parser(tokens,scope);ast=parser.parse();if(_astCache.size>=_AST_CACHE_MAX){const first=_astCache.keys().next().value;_astCache.delete(first);}_astCache.set(trimmed,ast);}return evaluate(ast,scope);}catch(err){if(typeof console!=='undefined'&&console.debug){console.debug(`[zQuery EXPR_EVAL] Failed to evaluate: "${expr}"`,err.message);}return undefined;}}let _tpl=null;function _getTemplate(){if(!_tpl)_tpl=document.createElement('template');return _tpl;}function morph(rootEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newRoot=tpl.content;const tempDiv=document.createElement('div');while(newRoot.firstChild)tempDiv.appendChild(newRoot.firstChild);_morphChildren(rootEl,tempDiv);if(start)window.__zqMorphHook(rootEl,performance.now()-start);}function morphElement(oldEl,newHTML){const start=typeof window!=='undefined'&&window.__zqMorphHook?performance.now():0;const tpl=_getTemplate();tpl.innerHTML=newHTML;const newEl=tpl.content.firstElementChild;if(!newEl)return oldEl;if(oldEl.nodeName===newEl.nodeName){_morphAttributes(oldEl,newEl);_morphChildren(oldEl,newEl);if(start)window.__zqMorphHook(oldEl,performance.now()-start);return oldEl;}const clone=newEl.cloneNode(true);oldEl.parentNode.replaceChild(clone,oldEl);if(start)window.__zqMorphHook(clone,performance.now()-start);return clone;}function _morphChildren(oldParent,newParent){const oldCN=oldParent.childNodes;const newCN=newParent.childNodes;const oldLen=oldCN.length;const newLen=newCN.length;const oldChildren=new Array(oldLen);const newChildren=new Array(newLen);for(let i=0;i<oldLen;i++)oldChildren[i]=oldCN[i];for(let i=0;i<newLen;i++)newChildren[i]=newCN[i];let hasKeys=false;let oldKeyMap,newKeyMap;for(let i=0;i<oldLen;i++){if(_getKey(oldChildren[i])!=null){hasKeys=true;break;}}if(!hasKeys){for(let i=0;i<newLen;i++){if(_getKey(newChildren[i])!=null){hasKeys=true;break;}}}if(hasKeys){oldKeyMap=new Map();newKeyMap=new Map();for(let i=0;i<oldLen;i++){const key=_getKey(oldChildren[i]);if(key!=null)oldKeyMap.set(key,i);}for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null)newKeyMap.set(key,i);}_morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap);}else{_morphChildrenUnkeyed(oldParent,oldChildren,newChildren);}}function _morphChildrenUnkeyed(oldParent,oldChildren,newChildren){const oldLen=oldChildren.length;const newLen=newChildren.length;const minLen=oldLen<newLen?oldLen:newLen;for(let i=0;i<minLen;i++){_morphNode(oldParent,oldChildren[i],newChildren[i]);}if(newLen>oldLen){for(let i=oldLen;i<newLen;i++){oldParent.appendChild(newChildren[i].cloneNode(true));}}if(oldLen>newLen){for(let i=oldLen-1;i>=newLen;i--){oldParent.removeChild(oldChildren[i]);}}}function _morphChildrenKeyed(oldParent,oldChildren,newChildren,oldKeyMap,newKeyMap){const consumed=new Set();const newLen=newChildren.length;const matched=new Array(newLen);for(let i=0;i<newLen;i++){const key=_getKey(newChildren[i]);if(key!=null&&oldKeyMap.has(key)){const oldIdx=oldKeyMap.get(key);matched[i]=oldChildren[oldIdx];consumed.add(oldIdx);}else{matched[i]=null;}}for(let i=oldChildren.length-1;i>=0;i--){if(!consumed.has(i)){const key=_getKey(oldChildren[i]);if(key!=null&&!newKeyMap.has(key)){oldParent.removeChild(oldChildren[i]);}}}const oldIndices=[];for(let i=0;i<newLen;i++){if(matched[i]){const key=_getKey(newChildren[i]);oldIndices.push(oldKeyMap.get(key));}else{oldIndices.push(-1);}}const lisSet=_lis(oldIndices);let cursor=oldParent.firstChild;const unkeyedOld=[];for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)&&_getKey(oldChildren[i])==null){unkeyedOld.push(oldChildren[i]);}}let unkeyedIdx=0;for(let i=0;i<newLen;i++){const newNode=newChildren[i];const newKey=_getKey(newNode);let oldNode=matched[i];if(!oldNode&&newKey==null){oldNode=unkeyedOld[unkeyedIdx++]||null;}if(oldNode){if(!lisSet.has(i)){oldParent.insertBefore(oldNode,cursor);}_morphNode(oldParent,oldNode,newNode);cursor=oldNode.nextSibling;}else{const clone=newNode.cloneNode(true);if(cursor){oldParent.insertBefore(clone,cursor);}else{oldParent.appendChild(clone);}}}while(unkeyedIdx<unkeyedOld.length){const leftover=unkeyedOld[unkeyedIdx++];if(leftover.parentNode===oldParent){oldParent.removeChild(leftover);}}for(let i=0;i<oldChildren.length;i++){if(!consumed.has(i)){const node=oldChildren[i];if(node.parentNode===oldParent&&_getKey(node)!=null&&!newKeyMap.has(_getKey(node))){oldParent.removeChild(node);}}}}function _lis(arr){const len=arr.length;const result=new Set();if(len===0)return result;const tails=[];const prev=new Array(len).fill(-1);const tailIndices=[];for(let i=0;i<len;i++){if(arr[i]===-1)continue;const val=arr[i];let lo=0,hi=tails.length;while(lo<hi){const mid=(lo+hi)>>1;if(tails[mid]<val)lo=mid+1;else hi=mid;}tails[lo]=val;tailIndices[lo]=i;prev[i]=lo>0?tailIndices[lo-1]:-1;}let k=tailIndices[tails.length-1];for(let i=tails.length-1;i>=0;i--){result.add(k);k=prev[k];}return result;}function _morphNode(parent,oldNode,newNode){if(oldNode.nodeType===3||oldNode.nodeType===8){if(newNode.nodeType===oldNode.nodeType){if(oldNode.nodeValue!==newNode.nodeValue){oldNode.nodeValue=newNode.nodeValue;}return;}parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType!==newNode.nodeType||oldNode.nodeName!==newNode.nodeName){parent.replaceChild(newNode.cloneNode(true),oldNode);return;}if(oldNode.nodeType===1){if(oldNode.hasAttribute('z-skip'))return;if(oldNode.isEqualNode(newNode))return;_morphAttributes(oldNode,newNode);const tag=oldNode.nodeName;if(tag==='INPUT'){_syncInputValue(oldNode,newNode);return;}if(tag==='TEXTAREA'){if(oldNode.value!==newNode.textContent){oldNode.value=newNode.textContent||'';}return;}if(tag==='SELECT'){_morphChildren(oldNode,newNode);if(oldNode.value!==newNode.value){oldNode.value=newNode.value;}return;}_morphChildren(oldNode,newNode);}}function _morphAttributes(oldEl,newEl){const newAttrs=newEl.attributes;const oldAttrs=oldEl.attributes;const newLen=newAttrs.length;const oldLen=oldAttrs.length;if(newLen===oldLen){let same=true;for(let i=0;i<newLen;i++){const na=newAttrs[i];if(oldEl.getAttribute(na.name)!==na.value){same=false;break;}}if(same){for(let i=0;i<oldLen;i++){if(!newEl.hasAttribute(oldAttrs[i].name)){same=false;break;}}}if(same)return;}const newNames=new Set();for(let i=0;i<newLen;i++){const attr=newAttrs[i];newNames.add(attr.name);if(oldEl.getAttribute(attr.name)!==attr.value){oldEl.setAttribute(attr.name,attr.value);}}for(let i=oldLen-1;i>=0;i--){if(!newNames.has(oldAttrs[i].name)){oldEl.removeAttribute(oldAttrs[i].name);}}}function _syncInputValue(oldEl,newEl){const type=(oldEl.type||'').toLowerCase();if(type==='checkbox'||type==='radio'){if(oldEl.checked!==newEl.checked)oldEl.checked=newEl.checked;}else{if(oldEl.value!==(newEl.getAttribute('value')||'')){oldEl.value=newEl.getAttribute('value')||'';}}if(oldEl.disabled!==newEl.disabled)oldEl.disabled=newEl.disabled;}function _getKey(node){if(node.nodeType!==1)return null;const zk=node.getAttribute('z-key');if(zk)return zk;if(node.id)return'\0id:'+node.id;const ds=node.dataset;if(ds){if(ds.id)return'\0data-id:'+ds.id;if(ds.key)return'\0data-key:'+ds.key;}return null;}const _registry=new Map();const _instances=new Map();const _resourceCache=new Map();let _uid=0;if(typeof document!=='undefined'&&!document.querySelector('[data-zq-cloak]')){const _s=document.createElement('style');_s.textContent='[z-cloak]{display:none!important}*,*::before,*::after{-webkit-tap-highlight-color:transparent}';_s.setAttribute('data-zq-cloak','');document.head.appendChild(_s);}const _debounceTimers=new WeakMap();const _throttleTimers=new WeakMap();function _fetchResource(url){if(_resourceCache.has(url))return _resourceCache.get(url);if(typeof window!=='undefined'&&window.__zqInline){for(const[path,content]of Object.entries(window.__zqInline)){if(url===path||url.endsWith('/'+path)||url.endsWith('\\'+path)){const resolved=Promise.resolve(content);_resourceCache.set(url,resolved);return resolved;}}}let resolvedUrl=url;if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){try{const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');resolvedUrl=new URL(url,root).href;}catch{}}const promise=fetch(resolvedUrl).then(res=>{if(!res.ok)throw new Error(`zQuery: Failed to load resource "${url}" (${res.status})`);return res.text();});_resourceCache.set(url,promise);return promise;}function _resolveUrl(url,base){if(!base||!url||typeof url!=='string')return url;if(url.startsWith('/')||url.includes('://')||url.startsWith('//'))return url;try{if(base.includes('://')){return new URL(url,base).href;}const baseEl=document.querySelector('base');const root=baseEl?baseEl.href:(window.location.origin+'/');const absBase=new URL(base.endsWith('/')?base:base+'/',root).href;return new URL(url,absBase).href;}catch{return url;}}let _ownScriptUrl;try{if(typeof document!=='undefined'&&document.currentScript&&document.currentScript.src){_ownScriptUrl=document.currentScript.src.replace(/[?#].*$/,'');}}catch{}function _detectCallerBase(){try{const stack=new Error().stack||'';const urls=stack.match(/(?:https?|file):\/\/[^\s\)]+/g)||[];for(const raw of urls){const url=raw.replace(/:\d+:\d+$/,'').replace(/:\d+$/,'');if(/zquery(\.min)?\.js$/i.test(url))continue;if(_ownScriptUrl&&url.replace(/[?#].*$/,'')===_ownScriptUrl)continue;return url.replace(/\/[^/]*$/,'/');}}catch{}return undefined;}function _getPath(obj,path){return path.split('.').reduce((o,k)=>o?.[k],obj);}function _setPath(obj,path,value){const keys=path.split('.');const last=keys.pop();const target=keys.reduce((o,k)=>(o&&typeof o==='object')?o[k]:undefined,obj);if(target&&typeof target==='object')target[last]=value;}class Component{constructor(el,definition,props={}){this._uid=++_uid;this._el=el;this._def=definition;this._mounted=false;this._destroyed=false;this._updateQueued=false;this._listeners=[];this._watchCleanups=[];this.refs={};this._slotContent={};const defaultSlotNodes=[];[...el.childNodes].forEach(node=>{if(node.nodeType===1&&node.hasAttribute('slot')){const slotName=node.getAttribute('slot');if(!this._slotContent[slotName])this._slotContent[slotName]='';this._slotContent[slotName]+=node.outerHTML;}else if(node.nodeType===1||(node.nodeType===3&&node.textContent.trim())){defaultSlotNodes.push(node.nodeType===1?node.outerHTML:node.textContent);}});if(defaultSlotNodes.length){this._slotContent['default']=defaultSlotNodes.join('');}this.props=Object.freeze({...props});const initialState=typeof definition.state==='function'?definition.state():{...(definition.state||{})};this.state=reactive(initialState,(key,value,old)=>{if(!this._destroyed){this._runWatchers(key,value,old);this._scheduleUpdate();}});this.computed={};if(definition.computed){for(const[name,fn]of Object.entries(definition.computed)){Object.defineProperty(this.computed,name,{get:()=>fn.call(this,this.state.__raw||this.state),enumerable:true});}}for(const[key,val]of Object.entries(definition)){if(typeof val==='function'&&!_reservedKeys.has(key)){this[key]=val.bind(this);}}if(definition.init){try{definition.init.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${definition._name}" init() threw`,{component:definition._name},err);}}if(definition.watch){this._prevWatchValues={};for(const key of Object.keys(definition.watch)){this._prevWatchValues[key]=_getPath(this.state.__raw||this.state,key);}}}_runWatchers(changedKey,value,old){const watchers=this._def.watch;if(!watchers)return;for(const[key,handler]of Object.entries(watchers)){if(changedKey===key||key.startsWith(changedKey+'.')||changedKey.startsWith(key+'.')||changedKey===key){const currentVal=_getPath(this.state.__raw||this.state,key);const prevVal=this._prevWatchValues?.[key];if(currentVal!==prevVal){const fn=typeof handler==='function'?handler:handler.handler;if(typeof fn==='function')fn.call(this,currentVal,prevVal);if(this._prevWatchValues)this._prevWatchValues[key]=currentVal;}}}}_scheduleUpdate(){if(this._updateQueued)return;this._updateQueued=true;queueMicrotask(()=>{try{if(!this._destroyed)this._render();}finally{this._updateQueued=false;}});}async _loadExternals(){const def=this._def;const base=def._base;if(def.templateUrl&&!def._templateLoaded){const tu=def.templateUrl;if(typeof tu==='string'){def._externalTemplate=await _fetchResource(_resolveUrl(tu,base));}else if(Array.isArray(tu)){const urls=tu.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalTemplates={};results.forEach((html,i)=>{def._externalTemplates[i]=html;});}else if(typeof tu==='object'){const entries=Object.entries(tu);const results=await Promise.all(entries.map(([,url])=>_fetchResource(_resolveUrl(url,base))));def._externalTemplates={};entries.forEach(([key],i)=>{def._externalTemplates[key]=results[i];});}def._templateLoaded=true;}if(def.styleUrl&&!def._styleLoaded){const su=def.styleUrl;if(typeof su==='string'){const resolved=_resolveUrl(su,base);def._externalStyles=await _fetchResource(resolved);def._resolvedStyleUrls=[resolved];}else if(Array.isArray(su)){const urls=su.map(u=>_resolveUrl(u,base));const results=await Promise.all(urls.map(u=>_fetchResource(u)));def._externalStyles=results.join('\n');def._resolvedStyleUrls=urls;}def._styleLoaded=true;}}_render(){if((this._def.templateUrl&&!this._def._templateLoaded)||(this._def.styleUrl&&!this._def._styleLoaded)){this._loadExternals().then(()=>{if(!this._destroyed)this._render();});return;}if(this._def._externalTemplates){this.templates=this._def._externalTemplates;}let html;if(this._def.render){html=this._def.render.call(this);html=this._expandZFor(html);}else if(this._def._externalTemplate){html=this._expandZFor(this._def._externalTemplate);html=html.replace(/\{\{(.+?)\}\}/g,(_,expr)=>{try{const result=safeEval(expr.trim(),[this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});}else{html='';}html=this._expandContentDirectives(html);if(html.includes('<slot')){html=html.replace(/<slot(?:\s+name="([^"]*)")?\s*(?:\/>|>([\s\S]*?)<\/slot>)/g,(_,name,fallback)=>{const slotName=name||'default';return this._slotContent[slotName]||fallback||'';});}const combinedStyles=[this._def.styles||'',this._def._externalStyles||''].filter(Boolean).join('\n');if(!this._mounted&&combinedStyles){const scopeAttr=`z-s${this._uid}`;this._el.setAttribute(scopeAttr,'');let inAtBlock=0;const scoped=combinedStyles.replace(/([^{}]+)\{|\}/g,(match,selector)=>{if(match==='}'){if(inAtBlock>0)inAtBlock--;return match;}const trimmed=selector.trim();if(trimmed.startsWith('@')){inAtBlock++;return match;}if(inAtBlock>0&&/^[\d%\s,fromto]+$/.test(trimmed.replace(/\s/g,''))){return match;}return selector.split(',').map(s=>`[${scopeAttr}] ${s.trim()}`).join(', ')+' {';});const styleEl=document.createElement('style');styleEl.textContent=scoped;styleEl.setAttribute('data-zq-component',this._def._name||'');styleEl.setAttribute('data-zq-scope',scopeAttr);if(this._def._resolvedStyleUrls){styleEl.setAttribute('data-zq-style-urls',this._def._resolvedStyleUrls.join(' '));if(this._def.styles){styleEl.setAttribute('data-zq-inline',this._def.styles);}}document.head.appendChild(styleEl);this._styleEl=styleEl;}let _focusInfo=null;const _active=document.activeElement;if(_active&&this._el.contains(_active)){const modelKey=_active.getAttribute?.('z-model');const refKey=_active.getAttribute?.('z-ref');let selector=null;if(modelKey){selector=`[z-model="${modelKey}"]`;}else if(refKey){selector=`[z-ref="${refKey}"]`;}else{const tag=_active.tagName.toLowerCase();if(tag==='input'||tag==='textarea'||tag==='select'){let s=tag;if(_active.type)s+=`[type="${_active.type}"]`;if(_active.name)s+=`[name="${_active.name}"]`;if(_active.placeholder)s+=`[placeholder="${CSS.escape(_active.placeholder)}"]`;selector=s;}}if(selector){_focusInfo={selector,start:_active.selectionStart,end:_active.selectionEnd,dir:_active.selectionDirection,};}}const _renderStart=typeof window!=='undefined'&&(window.__zqMorphHook||window.__zqRenderHook)?performance.now():0;if(!this._mounted){this._el.innerHTML=html;if(_renderStart&&window.__zqRenderHook)window.__zqRenderHook(this._el,performance.now()-_renderStart,'mount',this._def._name);}else{morph(this._el,html);}this._processDirectives();this._bindEvents();this._bindRefs();this._bindModels();if(_focusInfo){const el=this._el.querySelector(_focusInfo.selector);if(el&&el!==document.activeElement){el.focus();try{if(_focusInfo.start!==null&&_focusInfo.start!==undefined){el.setSelectionRange(_focusInfo.start,_focusInfo.end,_focusInfo.dir);}}catch(_){}}}mountAll(this._el);if(!this._mounted){this._mounted=true;if(this._def.mounted){try{this._def.mounted.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" mounted() threw`,{component:this._def._name},err);}}}else{if(this._def.updated){try{this._def.updated.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" updated() threw`,{component:this._def._name},err);}}}}_bindEvents(){const eventMap=new Map();const allEls=this._el.querySelectorAll('*');allEls.forEach(child=>{if(child.closest('[z-pre]'))return;const attrs=child.attributes;for(let a=0;a<attrs.length;a++){const attr=attrs[a];let raw;if(attr.name.charCodeAt(0)===64){raw=attr.name.slice(1);}else if(attr.name.startsWith('z-on:')){raw=attr.name.slice(5);}else{continue;}const parts=raw.split('.');const event=parts[0];const modifiers=parts.slice(1);const methodExpr=attr.value;if(!child.dataset.zqEid){child.dataset.zqEid=String(++_uid);}const selector=`[data-zq-eid="${child.dataset.zqEid}"]`;if(!eventMap.has(event))eventMap.set(event,[]);eventMap.get(event).push({selector,methodExpr,modifiers,el:child});}});this._eventBindings=eventMap;if(this._delegatedEvents){for(const event of eventMap.keys()){if(!this._delegatedEvents.has(event)){this._attachDelegatedEvent(event,eventMap.get(event));}}for(const event of this._delegatedEvents.keys()){if(!eventMap.has(event)){const{handler,opts}=this._delegatedEvents.get(event);this._el.removeEventListener(event,handler,opts);this._delegatedEvents.delete(event);this._listeners=this._listeners.filter(l=>l.event!==event);}}return;}this._delegatedEvents=new Map();for(const[event,bindings]of eventMap){this._attachDelegatedEvent(event,bindings);}}_attachDelegatedEvent(event,bindings){const needsCapture=bindings.some(b=>b.modifiers.includes('capture'));const needsPassive=bindings.some(b=>b.modifiers.includes('passive'));const listenerOpts=(needsCapture||needsPassive)?{capture:needsCapture,passive:needsPassive}:false;const handler=(e)=>{const currentBindings=this._eventBindings?.get(event)||[];for(const{selector,methodExpr,modifiers,el}of currentBindings){if(!e.target.closest(selector))continue;if(modifiers.includes('self')&&e.target!==el)continue;if(modifiers.includes('prevent'))e.preventDefault();if(modifiers.includes('stop'))e.stopPropagation();const invoke=(evt)=>{const match=methodExpr.match(/^(\w+)(?:\(([^)]*)\))?$/);if(!match)return;const methodName=match[1];const fn=this[methodName];if(typeof fn!=='function')return;if(match[2]!==undefined){const args=match[2].split(',').map(a=>{a=a.trim();if(a==='')return undefined;if(a==='$event')return evt;if(a==='true')return true;if(a==='false')return false;if(a==='null')return null;if(/^-?\d+(\.\d+)?$/.test(a))return Number(a);if((a.startsWith("'")&&a.endsWith("'"))||(a.startsWith('"')&&a.endsWith('"')))return a.slice(1,-1);if(a.startsWith('state.'))return _getPath(this.state,a.slice(6));return a;}).filter(a=>a!==undefined);fn(...args);}else{fn(evt);}};const debounceIdx=modifiers.indexOf('debounce');if(debounceIdx!==-1){const ms=parseInt(modifiers[debounceIdx+1],10)||250;const timers=_debounceTimers.get(el)||{};clearTimeout(timers[event]);timers[event]=setTimeout(()=>invoke(e),ms);_debounceTimers.set(el,timers);continue;}const throttleIdx=modifiers.indexOf('throttle');if(throttleIdx!==-1){const ms=parseInt(modifiers[throttleIdx+1],10)||250;const timers=_throttleTimers.get(el)||{};if(timers[event])continue;invoke(e);timers[event]=setTimeout(()=>{timers[event]=null;},ms);_throttleTimers.set(el,timers);continue;}if(modifiers.includes('once')){if(el.dataset.zqOnce===event)continue;el.dataset.zqOnce=event;}invoke(e);}};this._el.addEventListener(event,handler,listenerOpts);this._listeners.push({event,handler});this._delegatedEvents.set(event,{handler,opts:listenerOpts});}_bindRefs(){this.refs={};this._el.querySelectorAll('[z-ref]').forEach(el=>{this.refs[el.getAttribute('z-ref')]=el;});}_bindModels(){this._el.querySelectorAll('[z-model]').forEach(el=>{const key=el.getAttribute('z-model');const tag=el.tagName.toLowerCase();const type=(el.type||'').toLowerCase();const isEditable=el.hasAttribute('contenteditable');const isLazy=el.hasAttribute('z-lazy');const isTrim=el.hasAttribute('z-trim');const isNum=el.hasAttribute('z-number');const currentVal=_getPath(this.state,key);if(tag==='input'&&type==='checkbox'){el.checked=!!currentVal;}else if(tag==='input'&&type==='radio'){el.checked=el.value===String(currentVal);}else if(tag==='select'&&el.multiple){const vals=Array.isArray(currentVal)?currentVal.map(String):[];[...el.options].forEach(opt=>{opt.selected=vals.includes(opt.value);});}else if(isEditable){if(el.textContent!==String(currentVal??'')){el.textContent=currentVal??'';}}else{el.value=currentVal??'';}const event=isLazy||tag==='select'||type==='checkbox'||type==='radio'?'change':isEditable?'input':'input';if(el._zqModelBound)return;el._zqModelBound=true;const handler=()=>{let val;if(type==='checkbox')val=el.checked;else if(tag==='select'&&el.multiple)val=[...el.selectedOptions].map(o=>o.value);else if(isEditable)val=el.textContent;else val=el.value;if(isTrim&&typeof val==='string')val=val.trim();if(isNum||type==='number'||type==='range')val=Number(val);_setPath(this.state,key,val);};el.addEventListener(event,handler);});}_evalExpr(expr){return safeEval(expr,[this.state.__raw||this.state,{props:this.props,refs:this.refs,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);}_expandZFor(html){if(!html.includes('z-for'))return html;const temp=document.createElement('div');temp.innerHTML=html;const _recurse=(root)=>{let forEls=[...root.querySelectorAll('[z-for]')].filter(el=>!el.querySelector('[z-for]'));if(!forEls.length)return;for(const el of forEls){if(!el.parentNode)continue;const expr=el.getAttribute('z-for');const m=expr.match(/^\s*(?:\(\s*(\w+)(?:\s*,\s*(\w+))?\s*\)|(\w+))\s+in\s+(.+)\s*$/);if(!m){el.removeAttribute('z-for');continue;}const itemVar=m[1]||m[3];const indexVar=m[2]||'$index';const listExpr=m[4].trim();let list=this._evalExpr(listExpr);if(list==null){el.remove();continue;}if(typeof list==='number'){list=Array.from({length:list},(_,i)=>i+1);}if(!Array.isArray(list)&&typeof list==='object'&&typeof list[Symbol.iterator]!=='function'){list=Object.entries(list).map(([k,v])=>({key:k,value:v}));}if(!Array.isArray(list)&&typeof list[Symbol.iterator]==='function'){list=[...list];}if(!Array.isArray(list)){el.remove();continue;}const parent=el.parentNode;const tplEl=el.cloneNode(true);tplEl.removeAttribute('z-for');const tplOuter=tplEl.outerHTML;const fragment=document.createDocumentFragment();const evalReplace=(str,item,index)=>str.replace(/\{\{(.+?)\}\}/g,(_,inner)=>{try{const loopScope={};loopScope[itemVar]=item;loopScope[indexVar]=index;const result=safeEval(inner.trim(),[loopScope,this.state.__raw||this.state,{props:this.props,computed:this.computed,$:typeof window!=='undefined'?window.$:undefined}]);return result!=null?result:'';}catch{return'';}});for(let i=0;i<list.length;i++){const processed=evalReplace(tplOuter,list[i],i);const wrapper=document.createElement('div');wrapper.innerHTML=processed;while(wrapper.firstChild)fragment.appendChild(wrapper.firstChild);}parent.replaceChild(fragment,el);}if(root.querySelector('[z-for]'))_recurse(root);};_recurse(temp);return temp.innerHTML;}_expandContentDirectives(html){if(!html.includes('z-html')&&!html.includes('z-text'))return html;const temp=document.createElement('div');temp.innerHTML=html;temp.querySelectorAll('[z-html]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-html'));el.innerHTML=val!=null?String(val):'';el.removeAttribute('z-html');});temp.querySelectorAll('[z-text]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-text'));el.textContent=val!=null?String(val):'';el.removeAttribute('z-text');});return temp.innerHTML;}_processDirectives(){const ifEls=[...this._el.querySelectorAll('[z-if]')];for(const el of ifEls){if(!el.parentNode||el.closest('[z-pre]'))continue;const show=!!this._evalExpr(el.getAttribute('z-if'));const chain=[{el,show}];let sib=el.nextElementSibling;while(sib){if(sib.hasAttribute('z-else-if')){chain.push({el:sib,show:!!this._evalExpr(sib.getAttribute('z-else-if'))});sib=sib.nextElementSibling;}else if(sib.hasAttribute('z-else')){chain.push({el:sib,show:true});break;}else{break;}}let found=false;for(const item of chain){if(!found&&item.show){found=true;item.el.removeAttribute('z-if');item.el.removeAttribute('z-else-if');item.el.removeAttribute('z-else');}else{item.el.remove();}}}this._el.querySelectorAll('[z-show]').forEach(el=>{if(el.closest('[z-pre]'))return;const show=!!this._evalExpr(el.getAttribute('z-show'));el.style.display=show?'':'none';el.removeAttribute('z-show');});const walker=document.createTreeWalker(this._el,NodeFilter.SHOW_ELEMENT,{acceptNode(n){return n.hasAttribute('z-pre')?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const attrs=node.attributes;for(let i=attrs.length-1;i>=0;i--){const attr=attrs[i];let attrName;if(attr.name.startsWith('z-bind:'))attrName=attr.name.slice(7);else if(attr.name.charCodeAt(0)===58&&attr.name.charCodeAt(1)!==58)attrName=attr.name.slice(1);else continue;const val=this._evalExpr(attr.value);node.removeAttribute(attr.name);if(val===false||val===null||val===undefined){node.removeAttribute(attrName);}else if(val===true){node.setAttribute(attrName,'');}else{node.setAttribute(attrName,String(val));}}}this._el.querySelectorAll('[z-class]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-class'));if(typeof val==='string'){val.split(/\s+/).filter(Boolean).forEach(c=>el.classList.add(c));}else if(Array.isArray(val)){val.filter(Boolean).forEach(c=>el.classList.add(String(c)));}else if(val&&typeof val==='object'){for(const[cls,active]of Object.entries(val)){el.classList.toggle(cls,!!active);}}el.removeAttribute('z-class');});this._el.querySelectorAll('[z-style]').forEach(el=>{if(el.closest('[z-pre]'))return;const val=this._evalExpr(el.getAttribute('z-style'));if(typeof val==='string'){el.style.cssText+=';'+val;}else if(val&&typeof val==='object'){for(const[prop,v]of Object.entries(val)){el.style[prop]=v;}}el.removeAttribute('z-style');});this._el.querySelectorAll('[z-cloak]').forEach(el=>{el.removeAttribute('z-cloak');});}setState(partial){if(partial&&Object.keys(partial).length>0){Object.assign(this.state,partial);}else{this._scheduleUpdate();}}emit(name,detail){this._el.dispatchEvent(new CustomEvent(name,{detail,bubbles:true,cancelable:true}));}destroy(){if(this._destroyed)return;this._destroyed=true;if(this._def.destroyed){try{this._def.destroyed.call(this);}catch(err){reportError(ErrorCode.COMP_LIFECYCLE,`Component "${this._def._name}" destroyed() threw`,{component:this._def._name},err);}}this._listeners.forEach(({event,handler})=>this._el.removeEventListener(event,handler));this._listeners=[];this._delegatedEvents=null;this._eventBindings=null;if(this._styleEl)this._styleEl.remove();_instances.delete(this._el);this._el.innerHTML='';}}const _reservedKeys=new Set(['state','render','styles','init','mounted','updated','destroyed','props','templateUrl','styleUrl','templates','base','computed','watch']);function component(name,definition){if(!name||typeof name!=='string'){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,'Component name must be a non-empty string');}if(!name.includes('-')){throw new ZQueryError(ErrorCode.COMP_INVALID_NAME,`Component name "${name}" must contain a hyphen (Web Component convention)`);}definition._name=name;if(definition.base!==undefined){definition._base=definition.base;}else{definition._base=_detectCallerBase();}_registry.set(name,definition);}function mount(target,componentName,props={}){const el=typeof target==='string'?document.querySelector(target):target;if(!el)throw new ZQueryError(ErrorCode.COMP_MOUNT_TARGET,`Mount target "${target}" not found`,{target});const def=_registry.get(componentName);if(!def)throw new ZQueryError(ErrorCode.COMP_NOT_FOUND,`Component "${componentName}" not registered`,{component:componentName});if(_instances.has(el))_instances.get(el).destroy();const instance=new Component(el,def,props);_instances.set(el,instance);instance._render();return instance;}function mountAll(root=document.body){for(const[name,def]of _registry){const tags=root.querySelectorAll(name);tags.forEach(tag=>{if(_instances.has(tag))return;const props={};let parentInstance=null;let ancestor=tag.parentElement;while(ancestor){if(_instances.has(ancestor)){parentInstance=_instances.get(ancestor);break;}ancestor=ancestor.parentElement;}[...tag.attributes].forEach(attr=>{if(attr.name.startsWith('@')||attr.name.startsWith('z-'))return;if(attr.name.startsWith(':')){const propName=attr.name.slice(1);if(parentInstance){props[propName]=safeEval(attr.value,[parentInstance.state.__raw||parentInstance.state,{props:parentInstance.props,refs:parentInstance.refs,computed:parentInstance.computed,$:typeof window!=='undefined'?window.$:undefined}]);}else{try{props[propName]=JSON.parse(attr.value);}catch{props[propName]=attr.value;}}return;}try{props[attr.name]=JSON.parse(attr.value);}catch{props[attr.name]=attr.value;}});const instance=new Component(tag,def,props);_instances.set(tag,instance);instance._render();});}}function getInstance(target){const el=typeof target==='string'?document.querySelector(target):target;return _instances.get(el)||null;}function destroy(target){const el=typeof target==='string'?document.querySelector(target):target;const inst=_instances.get(el);if(inst)inst.destroy();}function getRegistry(){return Object.fromEntries(_registry);}async function prefetch(name){const def=_registry.get(name);if(!def)return;if((def.templateUrl&&!def._templateLoaded)||(def.styleUrl&&!def._styleLoaded)){await Component.prototype._loadExternals.call({_def:def});}}const _globalStyles=new Map();function style(urls,opts={}){const callerBase=_detectCallerBase();const list=Array.isArray(urls)?urls:[urls];const elements=[];const loadPromises=[];let _criticalStyle=null;if(opts.critical!==false){_criticalStyle=document.createElement('style');_criticalStyle.setAttribute('data-zq-critical','');_criticalStyle.textContent=`html{visibility:hidden!important;background:${opts.bg || '#0d1117'}}`;document.head.insertBefore(_criticalStyle,document.head.firstChild);}for(let url of list){if(typeof url==='string'&&!url.startsWith('/')&&!url.includes(':')&&!url.startsWith('//')){url=_resolveUrl(url,callerBase);}if(_globalStyles.has(url)){elements.push(_globalStyles.get(url));continue;}const link=document.createElement('link');link.rel='stylesheet';link.href=url;link.setAttribute('data-zq-style','');const p=new Promise(resolve=>{link.onload=resolve;link.onerror=resolve;});loadPromises.push(p);document.head.appendChild(link);_globalStyles.set(url,link);elements.push(link);}const ready=Promise.all(loadPromises).then(()=>{if(_criticalStyle){_criticalStyle.remove();}});return{ready,remove(){for(const el of elements){el.remove();for(const[k,v]of _globalStyles){if(v===el){_globalStyles.delete(k);break;}}}}};}const _ZQ_STATE_KEY='__zq';class Router{constructor(config={}){this._el=null;const isFile=typeof location!=='undefined'&&location.protocol==='file:';this._mode=isFile?'hash':(config.mode||'history');let rawBase=config.base;if(rawBase==null){rawBase=(typeof window!=='undefined'&&window.__ZQ_BASE)||'';if(!rawBase&&typeof document!=='undefined'){const baseEl=document.querySelector('base');if(baseEl){try{rawBase=new URL(baseEl.href).pathname;}catch{rawBase=baseEl.getAttribute('href')||'';}if(rawBase==='/')rawBase='';}}}this._base=String(rawBase).replace(/\/+$/,'');if(this._base&&!this._base.startsWith('/'))this._base='/'+this._base;this._routes=[];this._fallback=config.fallback||null;this._current=null;this._guards={before:[],after:[]};this._listeners=new Set();this._instance=null;this._resolving=false;this._substateListeners=[];this._inSubstate=false;if(config.el){this._el=typeof config.el==='string'?document.querySelector(config.el):config.el;}if(config.routes){config.routes.forEach(r=>this.add(r));}if(this._mode==='hash'){window.addEventListener('hashchange',()=>this._resolve());}else{window.addEventListener('popstate',(e)=>{const st=e.state;if(st&&st[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(st.key,st.data,'pop');if(handled)return;}else if(this._inSubstate){this._inSubstate=false;this._fireSubstate(null,null,'reset');}this._resolve();});}document.addEventListener('click',(e)=>{if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const link=e.target.closest('[z-link]');if(!link)return;if(link.getAttribute('target')==='_blank')return;e.preventDefault();let href=link.getAttribute('z-link');const paramsAttr=link.getAttribute('z-link-params');if(paramsAttr){try{const params=JSON.parse(paramsAttr);href=this._interpolateParams(href,params);}catch{}}this.navigate(href);if(link.hasAttribute('z-to-top')){const scrollBehavior=link.getAttribute('z-to-top')||'instant';window.scrollTo({top:0,behavior:scrollBehavior});}});if(this._el){queueMicrotask(()=>this._resolve());}}add(route){const keys=[];const pattern=route.path.replace(/:(\w+)/g,(_,key)=>{keys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const regex=new RegExp(`^${pattern}$`);this._routes.push({...route,_regex:regex,_keys:keys});if(route.fallback){const fbKeys=[];const fbPattern=route.fallback.replace(/:(\w+)/g,(_,key)=>{fbKeys.push(key);return'([^/]+)';}).replace(/\*/g,'(.*)');const fbRegex=new RegExp(`^${fbPattern}$`);this._routes.push({...route,path:route.fallback,_regex:fbRegex,_keys:fbKeys});}return this;}remove(path){this._routes=this._routes.filter(r=>r.path!==path);return this;}_interpolateParams(path,params){if(!params||typeof params!=='object')return path;return path.replace(/:([\w]+)/g,(_,key)=>{const val=params[key];return val!=null?encodeURIComponent(String(val)):':'+key;});}_currentURL(){if(this._mode==='hash'){return window.location.hash.slice(1)||'/';}const pathname=window.location.pathname||'/';const hash=window.location.hash||'';return pathname+hash;}navigate(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;const targetHash='#'+normalized;if(window.location.hash===targetHash&&!options.force)return this;window.location.hash=targetHash;}else{const targetURL=this._base+normalized+hash;const currentURL=(window.location.pathname||'/')+(window.location.hash||'');if(targetURL===currentURL&&!options.force){if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}const targetPathOnly=this._base+normalized;const currentPathOnly=window.location.pathname||'/';if(targetPathOnly===currentPathOnly&&hash&&!options.force){window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);if(fragment){const el=document.getElementById(fragment);if(el)el.scrollIntoView({behavior:'smooth',block:'start'});}return this;}window.history.pushState({...options.state,[_ZQ_STATE_KEY]:'route'},'',targetURL);this._resolve();}return this;}replace(path,options={}){if(options.params)path=this._interpolateParams(path,options.params);const[cleanPath,fragment]=(path||'').split('#');let normalized=this._normalizePath(cleanPath);const hash=fragment?'#'+fragment:'';if(this._mode==='hash'){if(fragment)window.__zqScrollTarget=fragment;window.location.replace('#'+normalized);}else{window.history.replaceState({...options.state,[_ZQ_STATE_KEY]:'route'},'',this._base+normalized+hash);this._resolve();}return this;}_normalizePath(path){let p=path&&path.startsWith('/')?path:(path?`/${path}`:'/');if(this._base){if(p===this._base)return'/';if(p.startsWith(this._base+'/'))p=p.slice(this._base.length)||'/';}return p;}resolve(path){const normalized=path&&path.startsWith('/')?path:(path?`/${path}`:'/');return this._base+normalized;}back(){window.history.back();return this;}forward(){window.history.forward();return this;}go(n){window.history.go(n);return this;}beforeEach(fn){this._guards.before.push(fn);return this;}afterEach(fn){this._guards.after.push(fn);return this;}onChange(fn){this._listeners.add(fn);return()=>this._listeners.delete(fn);}pushSubstate(key,data){this._inSubstate=true;if(this._mode==='hash'){const current=window.location.hash||'#/';window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}else{window.history.pushState({[_ZQ_STATE_KEY]:'substate',key,data},'',window.location.href);}return this;}onSubstate(fn){this._substateListeners.push(fn);return()=>{this._substateListeners=this._substateListeners.filter(f=>f!==fn);};}_fireSubstate(key,data,action){for(const fn of this._substateListeners){try{if(fn(key,data,action)===true)return true;}catch(err){reportError(ErrorCode.ROUTER_GUARD,'onSubstate listener threw',{key,data},err);}}return false;}get current(){return this._current;}get base(){return this._base;}get path(){if(this._mode==='hash'){const raw=window.location.hash.slice(1)||'/';if(raw&&!raw.startsWith('/')){window.__zqScrollTarget=raw;const fallbackPath=(this._current&&this._current.path)||'/';window.location.replace('#'+fallbackPath);return fallbackPath;}return raw;}let pathname=window.location.pathname||'/';if(pathname.length>1&&pathname.endsWith('/')){pathname=pathname.slice(0,-1);}if(this._base){if(pathname===this._base)return'/';if(pathname.startsWith(this._base+'/')){return pathname.slice(this._base.length)||'/';}}return pathname;}get query(){const search=this._mode==='hash'?(window.location.hash.split('?')[1]||''):window.location.search.slice(1);return Object.fromEntries(new URLSearchParams(search));}async _resolve(){if(this._resolving)return;this._resolving=true;this._redirectCount=0;try{await this.__resolve();}finally{this._resolving=false;}}async __resolve(){const histState=window.history.state;if(histState&&histState[_ZQ_STATE_KEY]==='substate'){const handled=this._fireSubstate(histState.key,histState.data,'resolve');if(handled)return;}const fullPath=this.path;const[pathPart,queryString]=fullPath.split('?');const path=pathPart||'/';const query=Object.fromEntries(new URLSearchParams(queryString||''));let matched=null;let params={};for(const route of this._routes){const m=path.match(route._regex);if(m){matched=route;route._keys.forEach((key,i)=>{params[key]=m[i+1];});break;}}if(!matched&&this._fallback){matched={component:this._fallback,path:'*',_keys:[],_regex:/.*/};}if(!matched)return;const to={route:matched,params,query,path};const from=this._current;if(from&&this._instance&&matched.component===from.route.component){const sameParams=JSON.stringify(params)===JSON.stringify(from.params);const sameQuery=JSON.stringify(query)===JSON.stringify(from.query);if(sameParams&&sameQuery){return;}}for(const guard of this._guards.before){try{const result=await guard(to,from);if(result===false)return;if(typeof result==='string'){if(++this._redirectCount>10){reportError(ErrorCode.ROUTER_GUARD,'Too many guard redirects (possible loop)',{to},null);return;}const[rPath,rFrag]=result.split('#');const rNorm=this._normalizePath(rPath||'/');const rHash=rFrag?'#'+rFrag:'';if(this._mode==='hash'){if(rFrag)window.__zqScrollTarget=rFrag;window.location.replace('#'+rNorm);}else{window.history.replaceState({[_ZQ_STATE_KEY]:'route'},'',this._base+rNorm+rHash);}return this.__resolve();}}catch(err){reportError(ErrorCode.ROUTER_GUARD,'Before-guard threw',{to,from},err);return;}}if(matched.load){try{await matched.load();}catch(err){reportError(ErrorCode.ROUTER_LOAD,`Failed to load module for route "${matched.path}"`,{path:matched.path},err);return;}}this._current=to;if(this._el&&matched.component){if(typeof matched.component==='string'){await prefetch(matched.component);}if(this._instance){this._instance.destroy();this._instance=null;}const _routeStart=typeof window!=='undefined'&&window.__zqRenderHook?performance.now():0;this._el.innerHTML='';const props={...params,$route:to,$query:query,$params:params};if(typeof matched.component==='string'){const container=document.createElement(matched.component);this._el.appendChild(container);this._instance=mount(container,matched.component,props);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',matched.component);}else if(typeof matched.component==='function'){this._el.innerHTML=matched.component(to);if(_routeStart)window.__zqRenderHook(this._el,performance.now()-_routeStart,'route',to);}}for(const guard of this._guards.after){await guard(to,from);}this._listeners.forEach(fn=>fn(to,from));}destroy(){if(this._instance)this._instance.destroy();this._listeners.clear();this._substateListeners=[];this._inSubstate=false;this._routes=[];this._guards={before:[],after:[]};}}let _activeRouter=null;function createRouter(config){_activeRouter=new Router(config);return _activeRouter;}function getRouter(){return _activeRouter;}class Store{constructor(config={}){this._subscribers=new Map();this._wildcards=new Set();this._actions=config.actions||{};this._getters=config.getters||{};this._middleware=[];this._history=[];this._debug=config.debug||false;const initial=typeof config.state==='function'?config.state():{...(config.state||{})};this.state=reactive(initial,(key,value,old)=>{const subs=this._subscribers.get(key);if(subs)subs.forEach(fn=>{try{fn(value,old,key);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,`Subscriber for "${key}" threw`,{key},err);}});this._wildcards.forEach(fn=>{try{fn(key,value,old);}catch(err){reportError(ErrorCode.STORE_SUBSCRIBE,'Wildcard subscriber threw',{key},err);}});});this.getters={};for(const[name,fn]of Object.entries(this._getters)){Object.defineProperty(this.getters,name,{get:()=>fn(this.state.__raw||this.state),enumerable:true});}}dispatch(name,...args){const action=this._actions[name];if(!action){reportError(ErrorCode.STORE_ACTION,`Unknown action "${name}"`,{action:name,args});return;}for(const mw of this._middleware){try{const result=mw(name,args,this.state);if(result===false)return;}catch(err){reportError(ErrorCode.STORE_MIDDLEWARE,`Middleware threw during "${name}"`,{action:name},err);return;}}if(this._debug){console.log(`%c[Store] ${name}`,'color: #4CAF50; font-weight: bold;',...args);}try{const result=action(this.state,...args);this._history.push({action:name,args,timestamp:Date.now()});return result;}catch(err){reportError(ErrorCode.STORE_ACTION,`Action "${name}" threw`,{action:name,args},err);}}subscribe(keyOrFn,fn){if(typeof keyOrFn==='function'){this._wildcards.add(keyOrFn);return()=>this._wildcards.delete(keyOrFn);}if(!this._subscribers.has(keyOrFn)){this._subscribers.set(keyOrFn,new Set());}this._subscribers.get(keyOrFn).add(fn);return()=>this._subscribers.get(keyOrFn)?.delete(fn);}snapshot(){return JSON.parse(JSON.stringify(this.state.__raw||this.state));}replaceState(newState){const raw=this.state.__raw||this.state;for(const key of Object.keys(raw)){delete this.state[key];}Object.assign(this.state,newState);}use(fn){this._middleware.push(fn);return this;}get history(){return[...this._history];}reset(initialState){this.replaceState(initialState);this._history=[];}}let _stores=new Map();function createStore(name,config){if(typeof name==='object'){config=name;name='default';}const store=new Store(config);_stores.set(name,store);return store;}function getStore(name='default'){return _stores.get(name)||null;}const _config={baseURL:'',headers:{'Content-Type':'application/json'},timeout:30000,};const _interceptors={request:[],response:[],};async function request(method,url,data,options={}){if(!url||typeof url!=='string'){throw new Error(`HTTP request requires a URL string, got ${typeof url}`);}let fullURL=url.startsWith('http')?url:_config.baseURL+url;let headers={..._config.headers,...options.headers};let body=undefined;const fetchOpts={method:method.toUpperCase(),headers,...options,};if(data!==undefined&&method!=='GET'&&method!=='HEAD'){if(data instanceof FormData){body=data;delete fetchOpts.headers['Content-Type'];}else if(typeof data==='object'){body=JSON.stringify(data);}else{body=data;}fetchOpts.body=body;}if(data&&(method==='GET'||method==='HEAD')&&typeof data==='object'){const params=new URLSearchParams(data).toString();fullURL+=(fullURL.includes('?')?'&':'?')+params;}const controller=new AbortController();fetchOpts.signal=options.signal||controller.signal;const timeout=options.timeout??_config.timeout;let timer;if(timeout>0){timer=setTimeout(()=>controller.abort(),timeout);}for(const interceptor of _interceptors.request){const result=await interceptor(fetchOpts,fullURL);if(result===false)throw new Error('Request blocked by interceptor');if(result?.url)fullURL=result.url;if(result?.options)Object.assign(fetchOpts,result.options);}try{const response=await fetch(fullURL,fetchOpts);if(timer)clearTimeout(timer);const contentType=response.headers.get('Content-Type')||'';let responseData;try{if(contentType.includes('application/json')){responseData=await response.json();}else if(contentType.includes('text/')){responseData=await response.text();}else if(contentType.includes('application/octet-stream')||contentType.includes('image/')){responseData=await response.blob();}else{const text=await response.text();try{responseData=JSON.parse(text);}catch{responseData=text;}}}catch(parseErr){responseData=null;console.warn(`[zQuery HTTP] Failed to parse response body from ${method} ${fullURL}:`,parseErr.message);}const result={ok:response.ok,status:response.status,statusText:response.statusText,headers:Object.fromEntries(response.headers.entries()),data:responseData,response,};for(const interceptor of _interceptors.response){await interceptor(result);}if(!response.ok){const err=new Error(`HTTP ${response.status}: ${response.statusText}`);err.response=result;throw err;}return result;}catch(err){if(timer)clearTimeout(timer);if(err.name==='AbortError'){throw new Error(`Request timeout after ${timeout}ms: ${method} ${fullURL}`);}throw err;}}const http={get:(url,params,opts)=>request('GET',url,params,opts),post:(url,data,opts)=>request('POST',url,data,opts),put:(url,data,opts)=>request('PUT',url,data,opts),patch:(url,data,opts)=>request('PATCH',url,data,opts),delete:(url,data,opts)=>request('DELETE',url,data,opts),configure(opts){if(opts.baseURL!==undefined)_config.baseURL=opts.baseURL;if(opts.headers)Object.assign(_config.headers,opts.headers);if(opts.timeout!==undefined)_config.timeout=opts.timeout;},onRequest(fn){_interceptors.request.push(fn);},onResponse(fn){_interceptors.response.push(fn);},createAbort(){return new AbortController();},raw:(url,opts)=>fetch(url,opts),};function debounce(fn,ms=250){let timer;const debounced=(...args)=>{clearTimeout(timer);timer=setTimeout(()=>fn(...args),ms);};debounced.cancel=()=>clearTimeout(timer);return debounced;}function throttle(fn,ms=250){let last=0;let timer;return(...args)=>{const now=Date.now();const remaining=ms-(now-last);clearTimeout(timer);if(remaining<=0){last=now;fn(...args);}else{timer=setTimeout(()=>{last=Date.now();fn(...args);},remaining);}};}function pipe(...fns){return(input)=>fns.reduce((val,fn)=>fn(val),input);}function once(fn){let called=false,result;return(...args)=>{if(!called){called=true;result=fn(...args);}return result;};}function sleep(ms){return new Promise(resolve=>setTimeout(resolve,ms));}function escapeHtml(str){const map={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'};return String(str).replace(/[&<>"']/g,c=>map[c]);}function html(strings,...values){return strings.reduce((result,str,i)=>{const val=values[i-1];const escaped=(val instanceof TrustedHTML)?val.toString():escapeHtml(val??'');return result+escaped+str;});}class TrustedHTML{constructor(html){this._html=html;}toString(){return this._html;}}function trust(htmlStr){return new TrustedHTML(htmlStr);}function uuid(){return crypto?.randomUUID?.()||'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0;return(c==='x'?r:(r&0x3|0x8)).toString(16);});}function camelCase(str){return str.replace(/-([a-z])/g,(_,c)=>c.toUpperCase());}function kebabCase(str){return str.replace(/([a-z])([A-Z])/g,'$1-$2').toLowerCase();}function deepClone(obj){if(typeof structuredClone==='function')return structuredClone(obj);return JSON.parse(JSON.stringify(obj));}function deepMerge(target,...sources){for(const source of sources){for(const key of Object.keys(source)){if(source[key]&&typeof source[key]==='object'&&!Array.isArray(source[key])){if(!target[key]||typeof target[key]!=='object')target[key]={};deepMerge(target[key],source[key]);}else{target[key]=source[key];}}}return target;}function isEqual(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(typeof a!=='object'||a===null||b===null)return false;const keysA=Object.keys(a);const keysB=Object.keys(b);if(keysA.length!==keysB.length)return false;return keysA.every(k=>isEqual(a[k],b[k]));}function param(obj){return new URLSearchParams(obj).toString();}function parseQuery(str){return Object.fromEntries(new URLSearchParams(str));}const storage={get(key,fallback=null){try{const raw=localStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){localStorage.setItem(key,JSON.stringify(value));},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();},};const session={get(key,fallback=null){try{const raw=sessionStorage.getItem(key);return raw!==null?JSON.parse(raw):fallback;}catch{return fallback;}},set(key,value){sessionStorage.setItem(key,JSON.stringify(value));},remove(key){sessionStorage.removeItem(key);},clear(){sessionStorage.clear();},};class EventBus{constructor(){this._handlers=new Map();}on(event,fn){if(!this._handlers.has(event))this._handlers.set(event,new Set());this._handlers.get(event).add(fn);return()=>this.off(event,fn);}off(event,fn){this._handlers.get(event)?.delete(fn);}emit(event,...args){this._handlers.get(event)?.forEach(fn=>fn(...args));}once(event,fn){const wrapper=(...args)=>{fn(...args);this.off(event,wrapper);};return this.on(event,wrapper);}clear(){this._handlers.clear();}}const bus=new EventBus();function $(selector,context){if(typeof selector==='function'){query.ready(selector);return;}return query(selector,context);}$.id=query.id;$.class=query.class;$.classes=query.classes;$.tag=query.tag;Object.defineProperty($,'name',{value:query.name,writable:true,configurable:true});$.children=query.children;$.all=function(selector,context){return queryAll(selector,context);};$.create=query.create;$.ready=query.ready;$.on=query.on;$.off=query.off;$.fn=query.fn;$.reactive=reactive;$.Signal=Signal;$.signal=signal;$.computed=computed;$.effect=effect;$.component=component;$.mount=mount;$.mountAll=mountAll;$.getInstance=getInstance;$.destroy=destroy;$.components=getRegistry;$.prefetch=prefetch;$.style=style;$.morph=morph;$.morphElement=morphElement;$.safeEval=safeEval;$.router=createRouter;$.getRouter=getRouter;$.store=createStore;$.getStore=getStore;$.http=http;$.get=http.get;$.post=http.post;$.put=http.put;$.patch=http.patch;$.delete=http.delete;$.debounce=debounce;$.throttle=throttle;$.pipe=pipe;$.once=once;$.sleep=sleep;$.escapeHtml=escapeHtml;$.html=html;$.trust=trust;$.uuid=uuid;$.camelCase=camelCase;$.kebabCase=kebabCase;$.deepClone=deepClone;$.deepMerge=deepMerge;$.isEqual=isEqual;$.param=param;$.parseQuery=parseQuery;$.storage=storage;$.session=session;$.bus=bus;$.onError=onError;$.ZQueryError=ZQueryError;$.ErrorCode=ErrorCode;$.guardCallback=guardCallback;$.validate=validate;$.version='0.8.9';$.libSize='~89 KB';$.meta={};$.noConflict=()=>{if(typeof window!=='undefined'&&window.$===$){delete window.$;}return $;};if(typeof window!=='undefined'){window.$=$;window.zQuery=$;}$;})(typeof window!=='undefined'?window:globalThis);
package/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Lightweight modern frontend library — jQuery-like selectors, reactive
5
5
  * components, SPA router, state management, HTTP client & utilities.
6
6
  *
7
- * @version 0.8.7
7
+ * @version 0.8.9
8
8
  * @license MIT
9
9
  * @see https://z-query.com/docs
10
10
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-query",
3
- "version": "0.8.7",
3
+ "version": "0.8.9",
4
4
  "description": "Lightweight modern frontend library — jQuery-like selectors, reactive components, SPA router, and state management with zero dependencies.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",