@mcp-fe/react-event-tracker 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.mjs +367 -1042
  2. package/package.json +3 -5
package/index.mjs CHANGED
@@ -1,67 +1,68 @@
1
- import * as m from "react";
2
- import I, { useRef as C, useState as te, useEffect as W } from "react";
3
- const fe = Object.prototype.hasOwnProperty;
4
- function ne(t, e, r = 0) {
5
- if (t === e)
6
- return t;
7
- if (r > 500) return e;
8
- const n = e, o = G(t) && G(n);
9
- if (!o && !(H(t) && H(n))) return n;
10
- const a = o ? t : F(t);
11
- if (!a) return n;
12
- const h = o ? n : F(n);
13
- if (!h) return n;
14
- const u = a.length, l = h.length, c = o ? new Array(l) : {};
15
- let s = 0;
16
- for (let i = 0; i < l; i++) {
17
- const k = o ? i : h[i], f = t[k], g = n[k];
18
- if (f === g) {
19
- c[k] = f, (o ? i < u : fe.call(t, k)) && s++;
1
+ import * as S from "react";
2
+ import D, { useRef as N, useState as Z, useEffect as y } from "react";
3
+ import { workerClient as b } from "@mcp-fe/mcp-worker";
4
+ const ie = Object.prototype.hasOwnProperty;
5
+ function ee(e, t, r = 0) {
6
+ if (e === t)
7
+ return e;
8
+ if (r > 500) return t;
9
+ const o = t, u = W(e) && W(o);
10
+ if (!u && !(U(e) && U(o))) return o;
11
+ const p = u ? e : G(e);
12
+ if (!p) return o;
13
+ const m = u ? o : G(o);
14
+ if (!m) return o;
15
+ const l = p.length, d = m.length, n = u ? new Array(d) : {};
16
+ let i = 0;
17
+ for (let c = 0; c < d; c++) {
18
+ const v = u ? c : m[c], a = e[v], s = o[v];
19
+ if (a === s) {
20
+ n[v] = a, (u ? c < l : ie.call(e, v)) && i++;
20
21
  continue;
21
22
  }
22
- if (f === null || g === null || typeof f != "object" || typeof g != "object") {
23
- c[k] = g;
23
+ if (a === null || s === null || typeof a != "object" || typeof s != "object") {
24
+ n[v] = s;
24
25
  continue;
25
26
  }
26
- const v = ne(f, g, r + 1);
27
- c[k] = v, v === f && s++;
27
+ const f = ee(a, s, r + 1);
28
+ n[v] = f, f === a && i++;
28
29
  }
29
- return u === l && s === u ? t : c;
30
+ return l === d && i === l ? e : n;
30
31
  }
31
- function F(t) {
32
- const e = [], r = Object.getOwnPropertyNames(t);
33
- for (const o of r) {
34
- if (!Object.prototype.propertyIsEnumerable.call(t, o)) return !1;
35
- e.push(o);
36
- }
37
- const n = Object.getOwnPropertySymbols(t);
38
- for (const o of n) {
39
- if (!Object.prototype.propertyIsEnumerable.call(t, o)) return !1;
40
- e.push(o);
41
- }
42
- return e;
32
+ function G(e) {
33
+ const t = [], r = Object.getOwnPropertyNames(e);
34
+ for (const u of r) {
35
+ if (!Object.prototype.propertyIsEnumerable.call(e, u)) return !1;
36
+ t.push(u);
37
+ }
38
+ const o = Object.getOwnPropertySymbols(e);
39
+ for (const u of o) {
40
+ if (!Object.prototype.propertyIsEnumerable.call(e, u)) return !1;
41
+ t.push(u);
42
+ }
43
+ return t;
43
44
  }
44
- function H(t) {
45
- if (!q(t))
45
+ function U(e) {
46
+ if (!K(e))
46
47
  return !1;
47
- const e = t.constructor;
48
- if (typeof e > "u")
48
+ const t = e.constructor;
49
+ if (typeof t > "u")
49
50
  return !0;
50
- const r = e.prototype;
51
- return !(!q(r) || !r.hasOwnProperty("isPrototypeOf"));
51
+ const r = t.prototype;
52
+ return !(!K(r) || !r.hasOwnProperty("isPrototypeOf"));
52
53
  }
53
- function q(t) {
54
- return Object.prototype.toString.call(t) === "[object Object]";
54
+ function K(e) {
55
+ return Object.prototype.toString.call(e) === "[object Object]";
55
56
  }
56
- function G(t) {
57
- return Array.isArray(t) && t.length === Object.keys(t).length;
57
+ function W(e) {
58
+ return Array.isArray(e) && e.length === Object.keys(e).length;
58
59
  }
59
- var de = process.env.NODE_ENV === "production";
60
- function he(t, e) {
61
- if (!de) {
62
- if (t)
60
+ var se = process.env.NODE_ENV === "production";
61
+ function le(e, t) {
62
+ if (!se) {
63
+ if (e)
63
64
  return;
64
- var r = "Warning: " + e;
65
+ var r = "Warning: " + t;
65
66
  typeof console < "u" && console.warn(r);
66
67
  try {
67
68
  throw Error(r);
@@ -69,1160 +70,484 @@ function he(t, e) {
69
70
  }
70
71
  }
71
72
  }
72
- var L = { exports: {} }, P = {}, N = { exports: {} }, A = {};
73
- var K;
74
- function ge() {
75
- if (K) return A;
76
- K = 1;
77
- var t = I;
78
- function e(i, k) {
79
- return i === k && (i !== 0 || 1 / i === 1 / k) || i !== i && k !== k;
80
- }
81
- var r = typeof Object.is == "function" ? Object.is : e, n = t.useState, o = t.useEffect, a = t.useLayoutEffect, h = t.useDebugValue;
82
- function u(i, k) {
83
- var f = k(), g = n({ inst: { value: f, getSnapshot: k } }), v = g[0].inst, p = g[1];
84
- return a(
73
+ var k = { exports: {} }, I = {}, C = { exports: {} }, V = {};
74
+ var H;
75
+ function fe() {
76
+ if (H) return V;
77
+ H = 1;
78
+ var e = D;
79
+ function t(c, v) {
80
+ return c === v && (c !== 0 || 1 / c === 1 / v) || c !== c && v !== v;
81
+ }
82
+ var r = typeof Object.is == "function" ? Object.is : t, o = e.useState, u = e.useEffect, p = e.useLayoutEffect, m = e.useDebugValue;
83
+ function l(c, v) {
84
+ var a = v(), s = o({ inst: { value: a, getSnapshot: v } }), f = s[0].inst, E = s[1];
85
+ return p(
85
86
  function() {
86
- v.value = f, v.getSnapshot = k, l(v) && p({ inst: v });
87
+ f.value = a, f.getSnapshot = v, d(f) && E({ inst: f });
87
88
  },
88
- [i, f, k]
89
- ), o(
89
+ [c, a, v]
90
+ ), u(
90
91
  function() {
91
- return l(v) && p({ inst: v }), i(function() {
92
- l(v) && p({ inst: v });
92
+ return d(f) && E({ inst: f }), c(function() {
93
+ d(f) && E({ inst: f });
93
94
  });
94
95
  },
95
- [i]
96
- ), h(f), f;
96
+ [c]
97
+ ), m(a), a;
97
98
  }
98
- function l(i) {
99
- var k = i.getSnapshot;
100
- i = i.value;
99
+ function d(c) {
100
+ var v = c.getSnapshot;
101
+ c = c.value;
101
102
  try {
102
- var f = k();
103
- return !r(i, f);
103
+ var a = v();
104
+ return !r(c, a);
104
105
  } catch {
105
106
  return !0;
106
107
  }
107
108
  }
108
- function c(i, k) {
109
- return k();
109
+ function n(c, v) {
110
+ return v();
110
111
  }
111
- var s = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? c : u;
112
- return A.useSyncExternalStore = t.useSyncExternalStore !== void 0 ? t.useSyncExternalStore : s, A;
112
+ var i = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? n : l;
113
+ return V.useSyncExternalStore = e.useSyncExternalStore !== void 0 ? e.useSyncExternalStore : i, V;
113
114
  }
114
- var b = {};
115
- var $;
116
- function ke() {
117
- return $ || ($ = 1, process.env.NODE_ENV !== "production" && (function() {
118
- function t(f, g) {
119
- return f === g && (f !== 0 || 1 / f === 1 / g) || f !== f && g !== g;
115
+ var x = {};
116
+ var q;
117
+ function de() {
118
+ return q || (q = 1, process.env.NODE_ENV !== "production" && (function() {
119
+ function e(a, s) {
120
+ return a === s && (a !== 0 || 1 / a === 1 / s) || a !== a && s !== s;
120
121
  }
121
- function e(f, g) {
122
- s || o.startTransition === void 0 || (s = !0, console.error(
122
+ function t(a, s) {
123
+ i || u.startTransition === void 0 || (i = !0, console.error(
123
124
  "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
124
125
  ));
125
- var v = g();
126
- if (!i) {
127
- var p = g();
128
- a(v, p) || (console.error(
126
+ var f = s();
127
+ if (!c) {
128
+ var E = s();
129
+ p(f, E) || (console.error(
129
130
  "The result of getSnapshot should be cached to avoid an infinite loop"
130
- ), i = !0);
131
+ ), c = !0);
131
132
  }
132
- p = h({
133
- inst: { value: v, getSnapshot: g }
133
+ E = m({
134
+ inst: { value: f, getSnapshot: s }
134
135
  });
135
- var E = p[0].inst, S = p[1];
136
- return l(
136
+ var O = E[0].inst, T = E[1];
137
+ return d(
137
138
  function() {
138
- E.value = v, E.getSnapshot = g, r(E) && S({ inst: E });
139
+ O.value = f, O.getSnapshot = s, r(O) && T({ inst: O });
139
140
  },
140
- [f, v, g]
141
- ), u(
141
+ [a, f, s]
142
+ ), l(
142
143
  function() {
143
- return r(E) && S({ inst: E }), f(function() {
144
- r(E) && S({ inst: E });
144
+ return r(O) && T({ inst: O }), a(function() {
145
+ r(O) && T({ inst: O });
145
146
  });
146
147
  },
147
- [f]
148
- ), c(v), v;
148
+ [a]
149
+ ), n(f), f;
149
150
  }
150
- function r(f) {
151
- var g = f.getSnapshot;
152
- f = f.value;
151
+ function r(a) {
152
+ var s = a.getSnapshot;
153
+ a = a.value;
153
154
  try {
154
- var v = g();
155
- return !a(f, v);
155
+ var f = s();
156
+ return !p(a, f);
156
157
  } catch {
157
158
  return !0;
158
159
  }
159
160
  }
160
- function n(f, g) {
161
- return g();
161
+ function o(a, s) {
162
+ return s();
162
163
  }
163
164
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
164
- var o = I, a = typeof Object.is == "function" ? Object.is : t, h = o.useState, u = o.useEffect, l = o.useLayoutEffect, c = o.useDebugValue, s = !1, i = !1, k = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? n : e;
165
- b.useSyncExternalStore = o.useSyncExternalStore !== void 0 ? o.useSyncExternalStore : k, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
166
- })()), b;
165
+ var u = D, p = typeof Object.is == "function" ? Object.is : e, m = u.useState, l = u.useEffect, d = u.useLayoutEffect, n = u.useDebugValue, i = !1, c = !1, v = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? o : t;
166
+ x.useSyncExternalStore = u.useSyncExternalStore !== void 0 ? u.useSyncExternalStore : v, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
167
+ })()), x;
167
168
  }
168
- var X;
169
- function oe() {
170
- return X || (X = 1, process.env.NODE_ENV === "production" ? N.exports = ge() : N.exports = ke()), N.exports;
169
+ var j;
170
+ function te() {
171
+ return j || (j = 1, process.env.NODE_ENV === "production" ? C.exports = fe() : C.exports = de()), C.exports;
171
172
  }
172
- var B;
173
- function ve() {
174
- if (B) return P;
175
- B = 1;
176
- var t = I, e = oe();
177
- function r(c, s) {
178
- return c === s && (c !== 0 || 1 / c === 1 / s) || c !== c && s !== s;
179
- }
180
- var n = typeof Object.is == "function" ? Object.is : r, o = e.useSyncExternalStore, a = t.useRef, h = t.useEffect, u = t.useMemo, l = t.useDebugValue;
181
- return P.useSyncExternalStoreWithSelector = function(c, s, i, k, f) {
182
- var g = a(null);
183
- if (g.current === null) {
184
- var v = { hasValue: !1, value: null };
185
- g.current = v;
186
- } else v = g.current;
187
- g = u(
173
+ var F;
174
+ function pe() {
175
+ if (F) return I;
176
+ F = 1;
177
+ var e = D, t = te();
178
+ function r(n, i) {
179
+ return n === i && (n !== 0 || 1 / n === 1 / i) || n !== n && i !== i;
180
+ }
181
+ var o = typeof Object.is == "function" ? Object.is : r, u = t.useSyncExternalStore, p = e.useRef, m = e.useEffect, l = e.useMemo, d = e.useDebugValue;
182
+ return I.useSyncExternalStoreWithSelector = function(n, i, c, v, a) {
183
+ var s = p(null);
184
+ if (s.current === null) {
185
+ var f = { hasValue: !1, value: null };
186
+ s.current = f;
187
+ } else f = s.current;
188
+ s = l(
188
189
  function() {
189
- function E(T) {
190
- if (!S) {
191
- if (S = !0, w = T, T = k(T), f !== void 0 && v.hasValue) {
192
- var y = v.value;
193
- if (f(y, T))
194
- return _ = y;
190
+ function O(_) {
191
+ if (!T) {
192
+ if (T = !0, R = _, _ = v(_), a !== void 0 && f.hasValue) {
193
+ var h = f.value;
194
+ if (a(h, _))
195
+ return g = h;
195
196
  }
196
- return _ = T;
197
+ return g = _;
197
198
  }
198
- if (y = _, n(w, T)) return y;
199
- var O = k(T);
200
- return f !== void 0 && f(y, O) ? (w = T, y) : (w = T, _ = O);
199
+ if (h = g, o(R, _)) return h;
200
+ var L = v(_);
201
+ return a !== void 0 && a(h, L) ? (R = _, h) : (R = _, g = L);
201
202
  }
202
- var S = !1, w, _, R = i === void 0 ? null : i;
203
+ var T = !1, R, g, w = c === void 0 ? null : c;
203
204
  return [
204
205
  function() {
205
- return E(s());
206
+ return O(i());
206
207
  },
207
- R === null ? void 0 : function() {
208
- return E(R());
208
+ w === null ? void 0 : function() {
209
+ return O(w());
209
210
  }
210
211
  ];
211
212
  },
212
- [s, i, k, f]
213
+ [i, c, v, a]
213
214
  );
214
- var p = o(c, g[0], g[1]);
215
- return h(
215
+ var E = u(n, s[0], s[1]);
216
+ return m(
216
217
  function() {
217
- v.hasValue = !0, v.value = p;
218
+ f.hasValue = !0, f.value = E;
218
219
  },
219
- [p]
220
- ), l(p), p;
221
- }, P;
220
+ [E]
221
+ ), d(E), E;
222
+ }, I;
222
223
  }
223
- var U = {};
224
- var Q;
225
- function pe() {
226
- return Q || (Q = 1, process.env.NODE_ENV !== "production" && (function() {
227
- function t(c, s) {
228
- return c === s && (c !== 0 || 1 / c === 1 / s) || c !== c && s !== s;
224
+ var A = {};
225
+ var X;
226
+ function ve() {
227
+ return X || (X = 1, process.env.NODE_ENV !== "production" && (function() {
228
+ function e(n, i) {
229
+ return n === i && (n !== 0 || 1 / n === 1 / i) || n !== n && i !== i;
229
230
  }
230
231
  typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
231
- var e = I, r = oe(), n = typeof Object.is == "function" ? Object.is : t, o = r.useSyncExternalStore, a = e.useRef, h = e.useEffect, u = e.useMemo, l = e.useDebugValue;
232
- U.useSyncExternalStoreWithSelector = function(c, s, i, k, f) {
233
- var g = a(null);
234
- if (g.current === null) {
235
- var v = { hasValue: !1, value: null };
236
- g.current = v;
237
- } else v = g.current;
238
- g = u(
232
+ var t = D, r = te(), o = typeof Object.is == "function" ? Object.is : e, u = r.useSyncExternalStore, p = t.useRef, m = t.useEffect, l = t.useMemo, d = t.useDebugValue;
233
+ A.useSyncExternalStoreWithSelector = function(n, i, c, v, a) {
234
+ var s = p(null);
235
+ if (s.current === null) {
236
+ var f = { hasValue: !1, value: null };
237
+ s.current = f;
238
+ } else f = s.current;
239
+ s = l(
239
240
  function() {
240
- function E(T) {
241
- if (!S) {
242
- if (S = !0, w = T, T = k(T), f !== void 0 && v.hasValue) {
243
- var y = v.value;
244
- if (f(y, T))
245
- return _ = y;
241
+ function O(_) {
242
+ if (!T) {
243
+ if (T = !0, R = _, _ = v(_), a !== void 0 && f.hasValue) {
244
+ var h = f.value;
245
+ if (a(h, _))
246
+ return g = h;
246
247
  }
247
- return _ = T;
248
+ return g = _;
248
249
  }
249
- if (y = _, n(w, T))
250
- return y;
251
- var O = k(T);
252
- return f !== void 0 && f(y, O) ? (w = T, y) : (w = T, _ = O);
250
+ if (h = g, o(R, _))
251
+ return h;
252
+ var L = v(_);
253
+ return a !== void 0 && a(h, L) ? (R = _, h) : (R = _, g = L);
253
254
  }
254
- var S = !1, w, _, R = i === void 0 ? null : i;
255
+ var T = !1, R, g, w = c === void 0 ? null : c;
255
256
  return [
256
257
  function() {
257
- return E(s());
258
+ return O(i());
258
259
  },
259
- R === null ? void 0 : function() {
260
- return E(R());
260
+ w === null ? void 0 : function() {
261
+ return O(w());
261
262
  }
262
263
  ];
263
264
  },
264
- [s, i, k, f]
265
+ [i, c, v, a]
265
266
  );
266
- var p = o(c, g[0], g[1]);
267
- return h(
267
+ var E = u(n, s[0], s[1]);
268
+ return m(
268
269
  function() {
269
- v.hasValue = !0, v.value = p;
270
+ f.hasValue = !0, f.value = E;
270
271
  },
271
- [p]
272
- ), l(p), p;
272
+ [E]
273
+ ), d(E), E;
273
274
  }, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
274
- })()), U;
275
+ })()), A;
275
276
  }
276
- var Y;
277
- function Te() {
278
- return Y || (Y = 1, process.env.NODE_ENV === "production" ? L.exports = ve() : L.exports = pe()), L.exports;
277
+ var $;
278
+ function me() {
279
+ return $ || ($ = 1, process.env.NODE_ENV === "production" ? k.exports = pe() : k.exports = ve()), k.exports;
279
280
  }
280
- var Ee = Te();
281
- function ye(t, e = (n) => n, r = {}) {
282
- const n = r.equal ?? me;
281
+ var Ee = me();
282
+ function _e(e, t = (o) => o, r = {}) {
283
+ const o = r.equal ?? Oe;
283
284
  return Ee.useSyncExternalStoreWithSelector(
284
- t.subscribe,
285
- () => t.state,
286
- () => t.state,
287
- e,
288
- n
285
+ e.subscribe,
286
+ () => e.state,
287
+ () => e.state,
288
+ t,
289
+ o
289
290
  );
290
291
  }
291
- function me(t, e) {
292
- if (Object.is(t, e))
292
+ function Oe(e, t) {
293
+ if (Object.is(e, t))
293
294
  return !0;
294
- if (typeof t != "object" || t === null || typeof e != "object" || e === null)
295
+ if (typeof e != "object" || e === null || typeof t != "object" || t === null)
295
296
  return !1;
296
- if (t instanceof Map && e instanceof Map) {
297
- if (t.size !== e.size) return !1;
298
- for (const [n, o] of t)
299
- if (!e.has(n) || !Object.is(o, e.get(n))) return !1;
297
+ if (e instanceof Map && t instanceof Map) {
298
+ if (e.size !== t.size) return !1;
299
+ for (const [o, u] of e)
300
+ if (!t.has(o) || !Object.is(u, t.get(o))) return !1;
300
301
  return !0;
301
302
  }
302
- if (t instanceof Set && e instanceof Set) {
303
- if (t.size !== e.size) return !1;
304
- for (const n of t)
305
- if (!e.has(n)) return !1;
303
+ if (e instanceof Set && t instanceof Set) {
304
+ if (e.size !== t.size) return !1;
305
+ for (const o of e)
306
+ if (!t.has(o)) return !1;
306
307
  return !0;
307
308
  }
308
- if (t instanceof Date && e instanceof Date)
309
- return t.getTime() === e.getTime();
310
- const r = j(t);
311
- if (r.length !== j(e).length)
309
+ if (e instanceof Date && t instanceof Date)
310
+ return e.getTime() === t.getTime();
311
+ const r = Y(e);
312
+ if (r.length !== Y(t).length)
312
313
  return !1;
313
- for (let n = 0; n < r.length; n++)
314
- if (!Object.prototype.hasOwnProperty.call(e, r[n]) || !Object.is(t[r[n]], e[r[n]]))
314
+ for (let o = 0; o < r.length; o++)
315
+ if (!Object.prototype.hasOwnProperty.call(t, r[o]) || !Object.is(e[r[o]], t[r[o]]))
315
316
  return !1;
316
317
  return !0;
317
318
  }
318
- function j(t) {
319
- return Object.keys(t).concat(
320
- Object.getOwnPropertySymbols(t)
319
+ function Y(e) {
320
+ return Object.keys(e).concat(
321
+ Object.getOwnPropertySymbols(e)
321
322
  );
322
323
  }
323
- const D = m.createContext(null);
324
- function We() {
325
- return typeof document > "u" ? D : window.__TSR_ROUTER_CONTEXT__ ? window.__TSR_ROUTER_CONTEXT__ : (window.__TSR_ROUTER_CONTEXT__ = D, D);
324
+ const P = S.createContext(null);
325
+ function he() {
326
+ return typeof document > "u" ? P : window.__TSR_ROUTER_CONTEXT__ ? window.__TSR_ROUTER_CONTEXT__ : (window.__TSR_ROUTER_CONTEXT__ = P, P);
326
327
  }
327
- function Se(t) {
328
- const e = m.useContext(We());
329
- return he(
330
- !((t?.warn ?? !0) && !e),
328
+ function Se(e) {
329
+ const t = S.useContext(he());
330
+ return le(
331
+ !((e?.warn ?? !0) && !t),
331
332
  "useRouter must be used inside a <RouterProvider> component!"
332
- ), e;
333
+ ), t;
333
334
  }
334
- function we(t) {
335
- const e = Se({
336
- warn: t?.router === void 0
337
- }), r = t?.router || e, n = C(void 0);
338
- return ye(r.__store, (o) => {
339
- if (t?.select) {
340
- if (t.structuralSharing ?? r.options.defaultStructuralSharing) {
341
- const a = ne(
342
- n.current,
343
- t.select(o)
335
+ function ye(e) {
336
+ const t = Se({
337
+ warn: e?.router === void 0
338
+ }), r = e?.router || t, o = N(void 0);
339
+ return _e(r.__store, (u) => {
340
+ if (e?.select) {
341
+ if (e.structuralSharing ?? r.options.defaultStructuralSharing) {
342
+ const p = ee(
343
+ o.current,
344
+ e.select(u)
344
345
  );
345
- return n.current = a, a;
346
+ return o.current = p, p;
346
347
  }
347
- return t.select(o);
348
+ return e.select(u);
348
349
  }
349
- return o;
350
+ return u;
350
351
  });
351
352
  }
352
- function _e(t) {
353
- return we({
354
- select: (e) => e.location
353
+ function Te(e) {
354
+ return ye({
355
+ select: (t) => t.location
355
356
  });
356
357
  }
357
- const Ce = typeof process < "u" && process.env?.NODE_ENV === "production", J = typeof process < "u" && process.env?.MCP_DEBUG, M = J === "true" || !Ce && J !== "false", d = {
358
- log: (...t) => {
359
- M && console.log(...t);
360
- },
361
- debug: (...t) => {
362
- M && console.debug(...t);
363
- },
364
- info: (...t) => {
365
- console.info(...t);
366
- },
367
- error: (...t) => {
368
- console.error(...t);
369
- },
370
- warn: (...t) => {
371
- M && console.warn(...t);
372
- }
373
- };
374
- class Re {
375
- // Configurable worker script URLs (defaults kept for backward compatibility)
376
- sharedWorkerUrl = "/mcp-shared-worker.js";
377
- serviceWorkerUrl = "/mcp-service-worker.js";
378
- // Backend websocket URL to pass into the worker(s)
379
- backendWsUrl = "ws://localhost:3001";
380
- serviceWorkerRegistration = null;
381
- sharedWorker = null;
382
- sharedWorkerPort = null;
383
- workerType = null;
384
- pendingAuthToken = null;
385
- // connection status subscribers
386
- connectionStatusCallbacks = /* @__PURE__ */ new Set();
387
- // Mutex/promise to prevent concurrent init runs
388
- initPromise = null;
389
- // Initialization state
390
- isInitialized = !1;
391
- initResolvers = [];
392
- // Queue for operations that need to wait for initialization
393
- pendingRegistrations = [];
394
- // Map to store tool handlers in main thread
395
- toolHandlers = /* @__PURE__ */ new Map();
396
- // Tool registry for tracking registrations and reference counting
397
- toolRegistry = /* @__PURE__ */ new Map();
398
- // Subscribers for tool changes (for React hooks reactivity)
399
- toolChangeListeners = /* @__PURE__ */ new Map();
400
- // Initialize and choose worker implementation (prefer SharedWorker)
401
- // Accept either a ServiceWorkerRegistration OR WorkerInitOptions to configure URLs
402
- async init(e) {
403
- d.log("[WorkerClient] init() called", {
404
- hasOptions: !!e,
405
- currentWorkerType: this.workerType,
406
- initInProgress: !!this.initPromise,
407
- timestamp: Date.now()
408
- });
409
- let r;
410
- const n = e;
411
- if (n && typeof n.scope == "string")
412
- r = e, d.log("[WorkerClient] Using explicit ServiceWorker registration");
413
- else if (e) {
414
- const o = e;
415
- d.log("[WorkerClient] Using WorkerClientInitOptions:", o), o.sharedWorkerUrl && (this.sharedWorkerUrl = o.sharedWorkerUrl), o.serviceWorkerUrl && (this.serviceWorkerUrl = o.serviceWorkerUrl), o.backendWsUrl && (this.backendWsUrl = o.backendWsUrl);
416
- }
417
- return this.initPromise ? this.initPromise.then(async () => {
418
- r && this.workerType !== "service" && await this.init(r);
419
- }) : (this.initPromise = (async () => {
420
- try {
421
- if (r) {
422
- this.serviceWorkerRegistration = r, this.workerType = "service", d.info(
423
- "[WorkerClient] Using ServiceWorker (explicit registration)"
424
- );
425
- try {
426
- const a = {
427
- type: "INIT",
428
- backendUrl: this.backendWsUrl
429
- };
430
- this.pendingAuthToken && (a.token = this.pendingAuthToken), this.serviceWorkerRegistration.active ? this.serviceWorkerRegistration.active.postMessage(a) : "serviceWorker" in navigator && navigator.serviceWorker.controller && navigator.serviceWorker.controller.postMessage(a);
431
- } catch {
432
- }
433
- return;
434
- }
435
- if (await this.initSharedWorker()) {
436
- this.markAsInitialized();
437
- return;
438
- }
439
- await this.initServiceWorkerFallback(), this.markAsInitialized();
440
- } finally {
441
- this.initPromise = null;
442
- }
443
- })(), this.initPromise);
444
- }
445
- /**
446
- * Mark worker as initialized and process pending registrations
447
- * @private
448
- */
449
- markAsInitialized() {
450
- this.isInitialized = !0, d.log(
451
- "[WorkerClient] Worker initialized, processing pending operations"
452
- ), this.initResolvers.forEach((r) => r()), this.initResolvers = [];
453
- const e = [...this.pendingRegistrations];
454
- this.pendingRegistrations = [], e.forEach(
455
- async ({ name: r, description: n, inputSchema: o, handler: a, resolve: h, reject: u }) => {
456
- try {
457
- await this.registerToolInternal(
458
- r,
459
- n,
460
- o,
461
- a
462
- ), h();
463
- } catch (l) {
464
- u(l instanceof Error ? l : new Error(String(l)));
465
- }
466
- }
467
- );
468
- }
469
- /**
470
- * Wait for worker initialization
471
- * @returns Promise that resolves when worker is initialized
472
- */
473
- async waitForInit() {
474
- if (this.isInitialized)
475
- return Promise.resolve();
476
- if (this.initPromise) {
477
- await this.initPromise;
478
- return;
479
- }
480
- return new Promise((e) => {
481
- this.initResolvers.push(e);
482
- });
483
- }
484
- /**
485
- * Check if worker is initialized
486
- */
487
- get initialized() {
488
- return this.isInitialized;
489
- }
490
- async initSharedWorker() {
491
- if (typeof SharedWorker > "u")
492
- return Promise.resolve(!1);
493
- try {
494
- this.sharedWorker = new SharedWorker(this.sharedWorkerUrl, {
495
- type: "module"
496
- }), this.sharedWorkerPort = this.sharedWorker.port, this.sharedWorkerPort.start(), await new Promise((r, n) => {
497
- let o = !1;
498
- const a = setTimeout(() => {
499
- if (!o) {
500
- const u = this.sharedWorkerPort;
501
- u && (u.onmessage = null), n(new Error("SharedWorker initialization timeout"));
502
- }
503
- }, 2e3), h = this.sharedWorkerPort;
504
- if (!h)
505
- return clearTimeout(a), n(new Error("SharedWorker port not available"));
506
- h.onmessage = (u) => {
507
- try {
508
- const l = u.data;
509
- l && l.type === "CONNECTION_STATUS" && (clearTimeout(a), o = !0, this.workerType = "shared", h.onmessage = null, r(!0));
510
- } catch {
511
- }
512
- };
513
- });
514
- const e = this.sharedWorkerPort;
515
- if (e) {
516
- try {
517
- const r = {
518
- type: "INIT",
519
- backendUrl: this.backendWsUrl
520
- };
521
- this.pendingAuthToken && (r.token = this.pendingAuthToken), e.postMessage(r), this.pendingAuthToken = null;
522
- } catch (r) {
523
- d.warn(
524
- "[WorkerClient] Failed to send INIT to SharedWorker port:",
525
- r
526
- );
527
- }
528
- e.onmessage = (r) => {
529
- try {
530
- const n = r.data;
531
- if (n && n.type === "CONNECTION_STATUS") {
532
- const o = !!n.connected;
533
- this.connectionStatusCallbacks.forEach((a) => {
534
- try {
535
- a(o);
536
- } catch {
537
- }
538
- });
539
- } else n && n.type === "CALL_TOOL" && this.handleToolCall(n.toolName, n.args, n.callId).catch(
540
- (o) => {
541
- d.error(
542
- "[WorkerClient] Failed to handle tool call:",
543
- o
544
- );
545
- }
546
- );
547
- } catch {
548
- }
549
- };
550
- }
551
- return d.info("[WorkerClient] Using SharedWorker"), !0;
552
- } catch (e) {
553
- return d.warn(
554
- "[WorkerClient] SharedWorker not available, falling back to ServiceWorker:",
555
- e
556
- ), !1;
557
- }
558
- }
559
- async initServiceWorkerFallback() {
560
- if ("serviceWorker" in navigator)
561
- try {
562
- const e = await navigator.serviceWorker.getRegistration();
563
- if (e) {
564
- this.serviceWorkerRegistration = e, this.workerType = "service", d.info(
565
- "[WorkerClient] Using existing ServiceWorker registration"
566
- );
567
- return;
568
- }
569
- this.serviceWorkerRegistration = await navigator.serviceWorker.register(
570
- this.serviceWorkerUrl
571
- ), this.workerType = "service", "serviceWorker" in navigator && navigator.serviceWorker.addEventListener(
572
- "message",
573
- (r) => {
574
- try {
575
- const n = r.data;
576
- n && n.type === "CALL_TOOL" && this.handleToolCall(
577
- n.toolName,
578
- n.args,
579
- n.callId
580
- ).catch((o) => {
581
- d.error(
582
- "[WorkerClient] Failed to handle tool call:",
583
- o
584
- );
585
- });
586
- } catch (n) {
587
- d.error(
588
- "[WorkerClient] Error processing ServiceWorker message:",
589
- n
590
- );
591
- }
592
- }
593
- ), d.info("[WorkerClient] Using MCP ServiceWorker (fallback)");
594
- try {
595
- const r = {
596
- type: "INIT",
597
- backendUrl: this.backendWsUrl
598
- };
599
- this.pendingAuthToken && (r.token = this.pendingAuthToken), this.serviceWorkerRegistration.active ? this.serviceWorkerRegistration.active.postMessage(r) : "serviceWorker" in navigator && navigator.serviceWorker.controller && navigator.serviceWorker.controller.postMessage(r), this.pendingAuthToken = null;
600
- } catch {
601
- }
602
- } catch (e) {
603
- throw d.error("[WorkerClient] Failed to register ServiceWorker:", e), e;
604
- }
605
- else
606
- throw new Error("Neither SharedWorker nor ServiceWorker is supported");
607
- }
608
- // Low-level request that expects a reply via MessageChannel
609
- async request(e, r, n = 5e3) {
610
- if (d.log("[WorkerClient] Request started:", {
611
- type: e,
612
- payload: r,
613
- timeoutMs: n,
614
- workerType: this.workerType,
615
- hasSharedWorkerPort: !!this.sharedWorkerPort,
616
- hasServiceWorkerReg: !!this.serviceWorkerRegistration
617
- }), this.workerType === "shared" && this.sharedWorkerPort)
618
- return new Promise((o, a) => {
619
- const h = new MessageChannel(), u = Math.random().toString(36).substring(7), l = Date.now(), c = setTimeout(() => {
620
- const s = Date.now() - l;
621
- d.error("[WorkerClient] Request timeout:", {
622
- type: e,
623
- requestId: u,
624
- elapsed: s,
625
- timeoutMs: n
626
- }), h.port1.onmessage = null, a(new Error("Request timeout"));
627
- }, n);
628
- h.port1.onmessage = (s) => {
629
- try {
630
- const i = Date.now() - l;
631
- d.log("[WorkerClient] Request response received:", {
632
- type: e,
633
- requestId: u,
634
- elapsed: i,
635
- success: s.data?.success
636
- }), clearTimeout(c), s.data && s.data.success ? o(s.data) : s.data && s.data.success === !1 ? a(new Error(s.data.error || "Worker error")) : o(s.data);
637
- } catch (i) {
638
- clearTimeout(c), h.port1.onmessage = null, a(
639
- i instanceof Error ? i : new Error(String(i))
640
- );
641
- }
642
- };
643
- try {
644
- const s = this.sharedWorkerPort;
645
- if (!s)
646
- return clearTimeout(c), d.error("[WorkerClient] SharedWorker port not available"), a(new Error("SharedWorker port not available"));
647
- d.log("[WorkerClient] Posting message to SharedWorker:", {
648
- type: e,
649
- requestId: u
650
- }), s.postMessage({ type: e, ...r || {} }, [h.port2]);
651
- } catch (s) {
652
- clearTimeout(c), d.error("[WorkerClient] Failed to post message:", s), a(s instanceof Error ? s : new Error(String(s)));
653
- }
654
- });
655
- if (this.workerType === "service" && this.serviceWorkerRegistration) {
656
- const o = this.serviceWorkerRegistration;
657
- if (!o) throw new Error("Service worker registration missing");
658
- if (!o.active && (d.log("[WorkerClient] ServiceWorker not active, waiting..."), await navigator.serviceWorker.ready, !o.active))
659
- throw new Error("Service worker not active");
660
- return new Promise((a, h) => {
661
- const u = new MessageChannel(), l = Math.random().toString(36).substring(7), c = Date.now(), s = setTimeout(() => {
662
- const i = Date.now() - c;
663
- d.error("[WorkerClient] ServiceWorker request timeout:", {
664
- type: e,
665
- requestId: l,
666
- elapsed: i,
667
- timeoutMs: n
668
- }), u.port1.onmessage = null, h(new Error("Request timeout"));
669
- }, n);
670
- u.port1.onmessage = (i) => {
671
- try {
672
- const k = Date.now() - c;
673
- d.log("[WorkerClient] ServiceWorker response received:", {
674
- type: e,
675
- requestId: l,
676
- elapsed: k,
677
- success: i.data?.success
678
- }), clearTimeout(s), i.data && i.data.success ? a(i.data) : i.data && i.data.success === !1 ? h(new Error(i.data.error || "Worker error")) : a(i.data);
679
- } catch (k) {
680
- clearTimeout(s), u.port1.onmessage = null, h(
681
- k instanceof Error ? k : new Error(String(k))
682
- );
683
- }
684
- };
685
- try {
686
- const i = o.active;
687
- if (!i)
688
- return clearTimeout(s), d.error(
689
- "[WorkerClient] ServiceWorker active instance not available"
690
- ), h(
691
- new Error("Service worker active instance not available")
692
- );
693
- d.log("[WorkerClient] Posting message to ServiceWorker:", {
694
- type: e,
695
- requestId: l
696
- }), i.postMessage({ type: e, ...r || {} }, [u.port2]);
697
- } catch (i) {
698
- clearTimeout(s), d.error(
699
- "[WorkerClient] Failed to post message to ServiceWorker:",
700
- i
701
- ), h(i instanceof Error ? i : new Error(String(i)));
702
- }
703
- });
704
- }
705
- throw new Error("No worker registered");
706
- }
707
- // Fire-and-forget postMessage (no response expected)
708
- async post(e, r) {
709
- if (this.workerType === "shared" && this.sharedWorkerPort) {
710
- try {
711
- this.sharedWorkerPort.postMessage({ type: e, ...r || {} });
712
- } catch (n) {
713
- d.error("[WorkerClient] Failed to post to SharedWorker:", n);
714
- }
715
- return;
716
- }
717
- if (this.workerType === "service" && this.serviceWorkerRegistration?.active) {
718
- try {
719
- this.serviceWorkerRegistration.active.postMessage({
720
- type: e,
721
- ...r || {}
722
- });
723
- } catch (n) {
724
- d.error(
725
- "[WorkerClient] Failed to post to ServiceWorker (active):",
726
- n
727
- );
728
- }
729
- return;
730
- }
731
- if ("serviceWorker" in navigator && navigator.serviceWorker.controller) {
732
- try {
733
- navigator.serviceWorker.controller.postMessage({
734
- type: e,
735
- ...r || {}
736
- });
737
- } catch (n) {
738
- d.error(
739
- "[WorkerClient] Failed to post to ServiceWorker.controller:",
740
- n
741
- );
742
- }
743
- return;
744
- }
745
- if (e === "SET_AUTH_TOKEN" && r) {
746
- const n = r.token;
747
- typeof n == "string" && (this.pendingAuthToken = n);
748
- }
749
- }
750
- sendAuthTokenToServiceWorker(e) {
751
- if (this.serviceWorkerRegistration?.active)
752
- try {
753
- this.serviceWorkerRegistration.active.postMessage({
754
- type: "SET_AUTH_TOKEN",
755
- token: e
756
- });
757
- } catch (r) {
758
- console.error(
759
- "[WorkerClient] Failed to send auth token to ServiceWorker:",
760
- r
761
- );
762
- }
763
- else if ("serviceWorker" in navigator && navigator.serviceWorker.controller)
764
- try {
765
- navigator.serviceWorker.controller.postMessage({
766
- type: "SET_AUTH_TOKEN",
767
- token: e
768
- });
769
- } catch (r) {
770
- console.error(
771
- "[WorkerClient] Failed to send auth token to ServiceWorker.controller:",
772
- r
773
- );
774
- }
775
- else
776
- this.pendingAuthToken = e;
777
- }
778
- // Subscription API for consumers to listen for connection status updates
779
- onConnectionStatus(e) {
780
- this.connectionStatusCallbacks.add(e);
781
- }
782
- offConnectionStatus(e) {
783
- this.connectionStatusCallbacks.delete(e);
784
- }
785
- async getConnectionStatus() {
786
- try {
787
- const e = await this.request(
788
- "GET_CONNECTION_STATUS",
789
- void 0,
790
- 2e3
791
- );
792
- return e && typeof e == "object" && "connected" in e ? !!e.connected : !!e?.connected;
793
- } catch {
794
- return !1;
795
- }
796
- }
797
- setAuthToken(e) {
798
- if (this.pendingAuthToken = e, this.workerType === "shared" && this.sharedWorkerPort)
799
- try {
800
- this.sharedWorkerPort.postMessage({ type: "SET_AUTH_TOKEN", token: e }), this.pendingAuthToken = null;
801
- } catch (r) {
802
- d.error(
803
- "[WorkerClient] Failed to set auth token on SharedWorker:",
804
- r
805
- );
806
- }
807
- else this.workerType === "service" && (this.sendAuthTokenToServiceWorker(e), this.pendingAuthToken = null);
808
- }
809
- /**
810
- * Register a custom MCP tool dynamically
811
- *
812
- * The handler function runs in the MAIN THREAD (browser context), not in the worker.
813
- * This means you have full access to:
814
- * - React context, hooks, Redux store
815
- * - DOM API, window, localStorage
816
- * - All your imports and dependencies
817
- * - Closures and external variables
818
- *
819
- * The worker acts as a proxy - it receives MCP tool calls and forwards them
820
- * to your handler via MessageChannel.
821
- *
822
- * @param name - Tool name
823
- * @param description - Tool description
824
- * @param inputSchema - JSON Schema for tool inputs
825
- * @param handler - Async function that handles the tool execution (runs in main thread)
826
- * @returns Promise that resolves when tool is registered
827
- *
828
- * @example With full access to imports and context:
829
- * ```typescript
830
- * import { z } from 'zod';
831
- * import { useMyStore } from './store';
832
- *
833
- * const store = useMyStore();
834
- *
835
- * await client.registerTool(
836
- * 'validate_user',
837
- * 'Validate user data',
838
- * { type: 'object', properties: { username: { type: 'string' } } },
839
- * async (args: any) => {
840
- * // Full access to everything!
841
- * const schema = z.object({ username: z.string().min(3) });
842
- * const validated = schema.parse(args);
843
- *
844
- * // Can access store, context, etc.
845
- * const currentUser = store.getState().user;
846
- *
847
- * return {
848
- * content: [{
849
- * type: 'text',
850
- * text: JSON.stringify({ validated, currentUser })
851
- * }]
852
- * };
853
- * }
854
- * );
855
- * ```
856
- */
857
- async registerTool(e, r, n, o) {
858
- return this.isInitialized ? this.registerToolInternal(e, r, n, o) : (d.log(
859
- `[WorkerClient] Queueing tool registration '${e}' (worker not initialized yet)`
860
- ), new Promise((a, h) => {
861
- this.pendingRegistrations.push({
862
- name: e,
863
- description: r,
864
- inputSchema: n,
865
- handler: o,
866
- resolve: a,
867
- reject: h
868
- });
869
- }));
870
- }
871
- /**
872
- * Internal method to register tool (assumes worker is initialized)
873
- * @private
874
- */
875
- async registerToolInternal(e, r, n, o) {
876
- const a = this.toolRegistry.get(e);
877
- if (a) {
878
- a.refCount++, d.log(
879
- `[WorkerClient] Incremented ref count for '${e}': ${a.refCount}`
880
- ), this.toolHandlers.set(e, o), this.notifyToolChange(e);
881
- return;
882
- }
883
- this.toolHandlers.set(e, o), await this.request("REGISTER_TOOL", {
884
- name: e,
885
- description: r,
886
- inputSchema: n,
887
- handlerType: "proxy"
888
- // Tell worker this is a proxy handler
889
- }), this.toolRegistry.set(e, {
890
- refCount: 1,
891
- description: r,
892
- inputSchema: n,
893
- isRegistered: !0
894
- }), d.log(
895
- `[WorkerClient] Registered tool '${e}' with main-thread handler`
896
- ), this.notifyToolChange(e);
897
- }
898
- /**
899
- * Unregister a previously registered MCP tool
900
- * @param name - Tool name to unregister
901
- * @returns Promise that resolves to true if tool was found and removed
902
- */
903
- async unregisterTool(e) {
904
- const r = this.toolRegistry.get(e);
905
- if (!r)
906
- return d.warn(`[WorkerClient] Cannot unregister '${e}': not found`), !1;
907
- if (r.refCount--, d.log(
908
- `[WorkerClient] Decremented ref count for '${e}': ${r.refCount}`
909
- ), r.refCount <= 0) {
910
- this.toolHandlers.delete(e);
911
- const n = await this.request(
912
- "UNREGISTER_TOOL",
913
- { name: e }
914
- );
915
- return this.toolRegistry.delete(e), d.log(`[WorkerClient] Unregistered tool '${e}'`), this.notifyToolChange(e), n?.success ?? !1;
916
- }
917
- return this.notifyToolChange(e), !0;
918
- }
919
- /**
920
- * Subscribe to tool changes for a specific tool
921
- * Returns unsubscribe function
922
- */
923
- onToolChange(e, r) {
924
- this.toolChangeListeners.has(e) || this.toolChangeListeners.set(e, /* @__PURE__ */ new Set());
925
- const n = this.toolChangeListeners.get(e);
926
- n.add(r);
927
- const o = this.toolRegistry.get(e);
928
- return r(o ? {
929
- refCount: o.refCount,
930
- isRegistered: o.isRegistered
931
- } : null), () => {
932
- n.delete(r), n.size === 0 && this.toolChangeListeners.delete(e);
933
- };
934
- }
935
- /**
936
- * Notify all listeners about tool changes
937
- * @private
938
- */
939
- notifyToolChange(e) {
940
- const r = this.toolChangeListeners.get(e);
941
- if (!r || r.size === 0) return;
942
- const n = this.toolRegistry.get(e), o = n ? {
943
- refCount: n.refCount,
944
- isRegistered: n.isRegistered
945
- } : null;
946
- r.forEach((a) => {
947
- try {
948
- a(o);
949
- } catch (h) {
950
- d.error("[WorkerClient] Error in tool change listener:", h);
951
- }
952
- });
953
- }
954
- /**
955
- * Get tool info from registry
956
- */
957
- getToolInfo(e) {
958
- const r = this.toolRegistry.get(e);
959
- return r ? {
960
- refCount: r.refCount,
961
- isRegistered: r.isRegistered
962
- } : null;
963
- }
964
- /**
965
- * Get all registered tool names
966
- */
967
- getRegisteredTools() {
968
- return Array.from(this.toolRegistry.keys()).filter(
969
- (e) => this.toolRegistry.get(e)?.isRegistered
970
- );
971
- }
972
- /**
973
- * Check if a tool is registered
974
- */
975
- isToolRegistered(e) {
976
- return this.toolRegistry.get(e)?.isRegistered ?? !1;
977
- }
978
- /**
979
- * Handle tool call from worker - execute handler in main thread and return result
980
- * @private
981
- */
982
- async handleToolCall(e, r, n) {
983
- d.log(`[WorkerClient] Handling tool call: ${e}`, {
984
- callId: n,
985
- args: r
986
- });
987
- try {
988
- const o = this.toolHandlers.get(e);
989
- if (!o)
990
- throw new Error(`Tool handler not found: ${e}`);
991
- const a = await o(r);
992
- this.sendToolCallResult(n, { success: !0, result: a });
993
- } catch (o) {
994
- d.error(`[WorkerClient] Tool call failed: ${e}`, o), this.sendToolCallResult(n, {
995
- success: !1,
996
- error: o instanceof Error ? o.message : "Unknown error"
997
- });
998
- }
999
- }
1000
- /**
1001
- * Send tool call result back to worker
1002
- * @private
1003
- */
1004
- sendToolCallResult(e, r) {
1005
- const n = {
1006
- type: "TOOL_CALL_RESULT",
1007
- callId: e,
1008
- success: r.success,
1009
- result: r.result,
1010
- error: r.error
1011
- };
1012
- if (this.workerType === "shared" && this.sharedWorkerPort)
1013
- try {
1014
- this.sharedWorkerPort.postMessage(n);
1015
- } catch (o) {
1016
- d.error(
1017
- "[WorkerClient] Failed to send result to SharedWorker:",
1018
- o
1019
- );
1020
- }
1021
- else if (this.workerType === "service" && this.serviceWorkerRegistration?.active)
1022
- try {
1023
- this.serviceWorkerRegistration.active.postMessage(n);
1024
- } catch (o) {
1025
- d.error(
1026
- "[WorkerClient] Failed to send result to ServiceWorker:",
1027
- o
1028
- );
1029
- }
1030
- }
1031
- }
1032
- const x = new Re();
1033
- async function ie(t) {
1034
- return x.init(t);
358
+ async function re(e) {
359
+ return b.init(e);
1035
360
  }
1036
- async function V(t) {
1037
- const e = { ...t, timestamp: Date.now() };
1038
- await x.request("STORE_EVENT", { event: e });
361
+ async function z(e) {
362
+ const t = { ...e, timestamp: Date.now() };
363
+ await b.request("STORE_EVENT", { event: t });
1039
364
  }
1040
- function se(t) {
1041
- x.setAuthToken(t);
365
+ function ne(e) {
366
+ b.setAuthToken(e);
1042
367
  }
1043
- async function ae(t, e, r) {
1044
- return V({ type: "navigation", from: t, to: e, path: r || e });
368
+ async function oe(e, t, r) {
369
+ return z({ type: "navigation", from: e, to: t, path: r || t });
1045
370
  }
1046
- async function ce(t, e, r) {
1047
- const n = t.id || void 0, o = t.className || void 0, a = t.textContent?.trim().substring(0, 100) || void 0, h = t.tagName.toLowerCase();
1048
- return V({
371
+ async function ue(e, t, r) {
372
+ const o = e.id || void 0, u = e.className || void 0, p = e.textContent?.trim().substring(0, 100) || void 0, m = e.tagName.toLowerCase();
373
+ return z({
1049
374
  type: "click",
1050
- element: h,
1051
- elementId: n,
1052
- elementClass: o,
1053
- elementText: a,
1054
- path: e || window.location.pathname,
375
+ element: m,
376
+ elementId: o,
377
+ elementClass: u,
378
+ elementText: p,
379
+ path: t || window.location.pathname,
1055
380
  metadata: r
1056
381
  });
1057
382
  }
1058
- async function ue(t, e, r) {
1059
- const n = t.id || void 0, o = t.className || void 0, a = t.tagName.toLowerCase();
1060
- return V({
383
+ async function ae(e, t, r) {
384
+ const o = e.id || void 0, u = e.className || void 0, p = e.tagName.toLowerCase();
385
+ return z({
1061
386
  type: "input",
1062
- element: a,
1063
- elementId: n,
1064
- elementClass: o,
387
+ element: p,
388
+ elementId: o,
389
+ elementClass: u,
1065
390
  path: r || window.location.pathname,
1066
391
  metadata: {
1067
- valueLength: e?.length || 0,
1068
- value: e
392
+ valueLength: t?.length || 0,
393
+ value: t
1069
394
  }
1070
395
  });
1071
396
  }
1072
- function xe(t) {
1073
- const e = _e(), [r, n] = te(!1), o = C(!1), a = C(e.pathname), h = C(null);
1074
- return W(() => {
1075
- h.current = a.current, a.current = e.pathname;
1076
- }, [e.pathname]), W(() => {
1077
- o.current || (o.current = !0, ie(t).then(() => {
1078
- n(!0);
1079
- }).catch((u) => {
397
+ function Ae(e) {
398
+ const t = Te(), [r, o] = Z(!1), u = N(!1), p = N(t.pathname), m = N(null);
399
+ return y(() => {
400
+ m.current = p.current, p.current = t.pathname;
401
+ }, [t.pathname]), y(() => {
402
+ u.current || (u.current = !0, re(e).then(() => {
403
+ o(!0);
404
+ }).catch((l) => {
1080
405
  console.error(
1081
406
  "[TanstackEventTracker] Worker initialization failed:",
1082
- u
407
+ l
1083
408
  );
1084
409
  }));
1085
- }, [t]), W(() => {
410
+ }, [e]), y(() => {
1086
411
  if (!r) return;
1087
- const u = h.current, l = a.current;
1088
- u && u !== l && ae(u, l, l).catch((c) => {
412
+ const l = m.current, d = p.current;
413
+ l && l !== d && oe(l, d, d).catch((n) => {
1089
414
  console.error(
1090
415
  "[TanstackEventTracker] Failed to track navigation:",
1091
- c
416
+ n
1092
417
  );
1093
418
  });
1094
- }, [e.pathname, r]), W(() => {
419
+ }, [t.pathname, r]), y(() => {
1095
420
  if (!r) return;
1096
- const u = (l) => {
1097
- const c = l.target;
1098
- if (!c) return;
1099
- c.tagName === "BUTTON" || c.tagName === "A" || c.closest("button") || c.closest("a") || ce(c, a.current).catch((i) => {
1100
- console.error("[TanstackEventTracker] Failed to track click:", i);
421
+ const l = (d) => {
422
+ const n = d.target;
423
+ if (!n) return;
424
+ n.tagName === "BUTTON" || n.tagName === "A" || n.closest("button") || n.closest("a") || ue(n, p.current).catch((c) => {
425
+ console.error("[TanstackEventTracker] Failed to track click:", c);
1101
426
  });
1102
427
  };
1103
- return document.addEventListener("click", u, !0), () => document.removeEventListener("click", u, !0);
1104
- }, [r]), W(() => {
428
+ return document.addEventListener("click", l, !0), () => document.removeEventListener("click", l, !0);
429
+ }, [r]), y(() => {
1105
430
  if (!r) return;
1106
- let u;
1107
- const l = (c) => {
1108
- const s = c.target;
1109
- s && (s.tagName === "INPUT" || s.tagName === "TEXTAREA") && (clearTimeout(u), u = setTimeout(() => {
1110
- ue(s, s.value, a.current).catch(
1111
- (i) => {
431
+ let l;
432
+ const d = (n) => {
433
+ const i = n.target;
434
+ i && (i.tagName === "INPUT" || i.tagName === "TEXTAREA") && (clearTimeout(l), l = setTimeout(() => {
435
+ ae(i, i.value, p.current).catch(
436
+ (c) => {
1112
437
  console.error(
1113
438
  "[TanstackEventTracker] Failed to track input:",
1114
- i
439
+ c
1115
440
  );
1116
441
  }
1117
442
  );
1118
443
  }, 1e3));
1119
444
  };
1120
- return document.addEventListener("input", l, !0), () => {
1121
- clearTimeout(u), document.removeEventListener("input", l, !0);
445
+ return document.addEventListener("input", d, !0), () => {
446
+ clearTimeout(l), document.removeEventListener("input", d, !0);
1122
447
  };
1123
448
  }, [r]), {
1124
- setAuthToken: se
449
+ setAuthToken: ne
1125
450
  };
1126
451
  }
1127
- var Z;
1128
- (function(t) {
1129
- t.Pop = "POP", t.Push = "PUSH", t.Replace = "REPLACE";
1130
- })(Z || (Z = {}));
1131
- function ee(t, e) {
1132
- throw new Error(e);
452
+ var B;
453
+ (function(e) {
454
+ e.Pop = "POP", e.Push = "PUSH", e.Replace = "REPLACE";
455
+ })(B || (B = {}));
456
+ function J(e, t) {
457
+ throw new Error(t);
1133
458
  }
1134
- var re;
1135
- (function(t) {
1136
- t.data = "data", t.deferred = "deferred", t.redirect = "redirect", t.error = "error";
1137
- })(re || (re = {}));
1138
- const le = ["post", "put", "patch", "delete"];
1139
- new Set(le);
1140
- const Oe = ["get", ...le];
1141
- new Set(Oe);
1142
- const Le = /* @__PURE__ */ m.createContext(null);
1143
- process.env.NODE_ENV !== "production" && (Le.displayName = "DataRouter");
1144
- const Ne = /* @__PURE__ */ m.createContext(null);
459
+ var Q;
460
+ (function(e) {
461
+ e.data = "data", e.deferred = "deferred", e.redirect = "redirect", e.error = "error";
462
+ })(Q || (Q = {}));
463
+ const ce = ["post", "put", "patch", "delete"];
464
+ new Set(ce);
465
+ const Re = ["get", ...ce];
466
+ new Set(Re);
467
+ const ge = /* @__PURE__ */ S.createContext(null);
468
+ process.env.NODE_ENV !== "production" && (ge.displayName = "DataRouter");
469
+ const Ne = /* @__PURE__ */ S.createContext(null);
1145
470
  process.env.NODE_ENV !== "production" && (Ne.displayName = "DataRouterState");
1146
- const Ie = /* @__PURE__ */ m.createContext(null);
1147
- process.env.NODE_ENV !== "production" && (Ie.displayName = "Await");
1148
- const Pe = /* @__PURE__ */ m.createContext(null);
1149
- process.env.NODE_ENV !== "production" && (Pe.displayName = "Navigation");
1150
- const z = /* @__PURE__ */ m.createContext(null);
1151
- process.env.NODE_ENV !== "production" && (z.displayName = "Location");
1152
- const Ae = /* @__PURE__ */ m.createContext({
471
+ const we = /* @__PURE__ */ S.createContext(null);
472
+ process.env.NODE_ENV !== "production" && (we.displayName = "Await");
473
+ const Le = /* @__PURE__ */ S.createContext(null);
474
+ process.env.NODE_ENV !== "production" && (Le.displayName = "Navigation");
475
+ const M = /* @__PURE__ */ S.createContext(null);
476
+ process.env.NODE_ENV !== "production" && (M.displayName = "Location");
477
+ const ke = /* @__PURE__ */ S.createContext({
1153
478
  outlet: null,
1154
479
  matches: [],
1155
480
  isDataRoute: !1
1156
481
  });
1157
- process.env.NODE_ENV !== "production" && (Ae.displayName = "Route");
1158
- const be = /* @__PURE__ */ m.createContext(null);
1159
- process.env.NODE_ENV !== "production" && (be.displayName = "RouteError");
1160
- function Ue() {
1161
- return m.useContext(z) != null;
1162
- }
482
+ process.env.NODE_ENV !== "production" && (ke.displayName = "Route");
483
+ const Ce = /* @__PURE__ */ S.createContext(null);
484
+ process.env.NODE_ENV !== "production" && (Ce.displayName = "RouteError");
1163
485
  function De() {
1164
- return Ue() || (process.env.NODE_ENV !== "production" ? ee(
486
+ return S.useContext(M) != null;
487
+ }
488
+ function Ie() {
489
+ return De() || (process.env.NODE_ENV !== "production" ? J(
1165
490
  !1,
1166
491
  // TODO: This error is probably because they somehow have 2 versions of the
1167
492
  // router loaded. We can help them understand how to avoid that.
1168
493
  "useLocation() may be used only in the context of a <Router> component."
1169
- ) : ee()), m.useContext(z).location;
494
+ ) : J()), S.useContext(M).location;
1170
495
  }
1171
496
  new Promise(() => {
1172
497
  });
1173
- function Ve(t) {
1174
- const e = De(), [r, n] = te(!1), o = C(!1), a = C(e.pathname), h = C(null);
1175
- return W(() => {
1176
- h.current = a.current, a.current = e.pathname;
1177
- }, [e.pathname]), W(() => {
1178
- o.current || (o.current = !0, ie(t).then(() => {
1179
- n(!0);
1180
- }).catch((u) => {
498
+ function Pe(e) {
499
+ const t = Ie(), [r, o] = Z(!1), u = N(!1), p = N(t.pathname), m = N(null);
500
+ return y(() => {
501
+ m.current = p.current, p.current = t.pathname;
502
+ }, [t.pathname]), y(() => {
503
+ u.current || (u.current = !0, re(e).then(() => {
504
+ o(!0);
505
+ }).catch((l) => {
1181
506
  console.error(
1182
507
  "[ReactEventTracker] Worker initialization failed:",
1183
- u
508
+ l
1184
509
  );
1185
510
  }));
1186
- }, [t]), W(() => {
511
+ }, [e]), y(() => {
1187
512
  if (!r) return;
1188
- const u = h.current, l = a.current;
1189
- u && u !== l && ae(u, l, l).catch((c) => {
1190
- console.error("[ReactEventTracker] Failed to track navigation:", c);
513
+ const l = m.current, d = p.current;
514
+ l && l !== d && oe(l, d, d).catch((n) => {
515
+ console.error("[ReactEventTracker] Failed to track navigation:", n);
1191
516
  });
1192
- }, [e.pathname, r]), W(() => {
517
+ }, [t.pathname, r]), y(() => {
1193
518
  if (!r) return;
1194
- const u = (l) => {
1195
- const c = l.target;
1196
- if (!c) return;
1197
- c.tagName === "BUTTON" || c.tagName === "A" || c.closest("button") || c.closest("a") || ce(c, a.current).catch((i) => {
1198
- console.error("[ReactEventTracker] Failed to track click:", i);
519
+ const l = (d) => {
520
+ const n = d.target;
521
+ if (!n) return;
522
+ n.tagName === "BUTTON" || n.tagName === "A" || n.closest("button") || n.closest("a") || ue(n, p.current).catch((c) => {
523
+ console.error("[ReactEventTracker] Failed to track click:", c);
1199
524
  });
1200
525
  };
1201
- return document.addEventListener("click", u, !0), () => document.removeEventListener("click", u, !0);
1202
- }, [r]), W(() => {
526
+ return document.addEventListener("click", l, !0), () => document.removeEventListener("click", l, !0);
527
+ }, [r]), y(() => {
1203
528
  if (!r) return;
1204
- let u;
1205
- const l = (c) => {
1206
- const s = c.target;
1207
- s && (s.tagName === "INPUT" || s.tagName === "TEXTAREA") && (clearTimeout(u), u = setTimeout(() => {
1208
- ue(s, s.value, a.current).catch(
1209
- (i) => {
529
+ let l;
530
+ const d = (n) => {
531
+ const i = n.target;
532
+ i && (i.tagName === "INPUT" || i.tagName === "TEXTAREA") && (clearTimeout(l), l = setTimeout(() => {
533
+ ae(i, i.value, p.current).catch(
534
+ (c) => {
1210
535
  console.error(
1211
536
  "[ReactEventTracker] Failed to track input:",
1212
- i
537
+ c
1213
538
  );
1214
539
  }
1215
540
  );
1216
541
  }, 1e3));
1217
542
  };
1218
- return document.addEventListener("input", l, !0), () => {
1219
- clearTimeout(u), document.removeEventListener("input", l, !0);
543
+ return document.addEventListener("input", d, !0), () => {
544
+ clearTimeout(l), document.removeEventListener("input", d, !0);
1220
545
  };
1221
546
  }, [r]), {
1222
- setAuthToken: se
547
+ setAuthToken: ne
1223
548
  };
1224
549
  }
1225
550
  export {
1226
- Ve as useReactRouterEventTracker,
1227
- xe as useTanstackRouterEventTracker
551
+ Pe as useReactRouterEventTracker,
552
+ Ae as useTanstackRouterEventTracker
1228
553
  };