@mcp-fe/react-event-tracker 0.0.5 → 0.0.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.
@@ -0,0 +1,2 @@
1
+ export declare function useReactRouterEventTracker(): void;
2
+ //# sourceMappingURL=useReactRouterEventTracker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useReactRouterEventTracker.d.ts","sourceRoot":"","sources":["../../../../libs/react-event-tracker/src/hooks/useReactRouterEventTracker.ts"],"names":[],"mappings":"AASA,wBAAgB,0BAA0B,IAAI,IAAI,CAuFjD"}
@@ -0,0 +1,2 @@
1
+ export declare function useTanstackRouterEventTracker(): void;
2
+ //# sourceMappingURL=useTanstackRouterEventTracker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useTanstackRouterEventTracker.d.ts","sourceRoot":"","sources":["../../../../libs/react-event-tracker/src/hooks/useTanstackRouterEventTracker.ts"],"names":[],"mappings":"AASA,wBAAgB,6BAA6B,IAAI,IAAI,CAuFpD"}
@@ -1,2 +1,3 @@
1
1
  export * from './hooks/useTanstackRouterEventTracker';
2
2
  export * from './hooks/useReactRouterEventTracker';
3
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../libs/react-event-tracker/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uCAAuC,CAAC;AACtD,cAAc,oCAAoC,CAAC"}
package/index.mjs ADDED
@@ -0,0 +1,757 @@
1
+ import * as S from "react";
2
+ import A, { useRef as R, useState as Q, useEffect as _ } from "react";
3
+ const se = Object.prototype.hasOwnProperty;
4
+ function Z(t, e, n = 0) {
5
+ if (t === e)
6
+ return t;
7
+ if (n > 500) return e;
8
+ const r = e, o = z(t) && z(r);
9
+ if (!o && !(U(t) && U(r))) return r;
10
+ const i = o ? t : x(t);
11
+ if (!i) return r;
12
+ const c = o ? r : x(r);
13
+ if (!c) return r;
14
+ const u = i.length, a = c.length, s = o ? new Array(a) : {};
15
+ let v = 0;
16
+ for (let h = 0; h < a; h++) {
17
+ const p = o ? h : c[h], l = t[p], f = r[p];
18
+ if (l === f) {
19
+ s[p] = l, (o ? h < u : se.call(t, p)) && v++;
20
+ continue;
21
+ }
22
+ if (l === null || f === null || typeof l != "object" || typeof f != "object") {
23
+ s[p] = f;
24
+ continue;
25
+ }
26
+ const d = Z(l, f, n + 1);
27
+ s[p] = d, d === l && v++;
28
+ }
29
+ return u === a && v === u ? t : s;
30
+ }
31
+ function x(t) {
32
+ const e = [], n = Object.getOwnPropertyNames(t);
33
+ for (const o of n) {
34
+ if (!Object.prototype.propertyIsEnumerable.call(t, o)) return !1;
35
+ e.push(o);
36
+ }
37
+ const r = Object.getOwnPropertySymbols(t);
38
+ for (const o of r) {
39
+ if (!Object.prototype.propertyIsEnumerable.call(t, o)) return !1;
40
+ e.push(o);
41
+ }
42
+ return e;
43
+ }
44
+ function U(t) {
45
+ if (!H(t))
46
+ return !1;
47
+ const e = t.constructor;
48
+ if (typeof e > "u")
49
+ return !0;
50
+ const n = e.prototype;
51
+ return !(!H(n) || !n.hasOwnProperty("isPrototypeOf"));
52
+ }
53
+ function H(t) {
54
+ return Object.prototype.toString.call(t) === "[object Object]";
55
+ }
56
+ function z(t) {
57
+ return Array.isArray(t) && t.length === Object.keys(t).length;
58
+ }
59
+ var ce = process.env.NODE_ENV === "production";
60
+ function ue(t, e) {
61
+ if (!ce) {
62
+ if (t)
63
+ return;
64
+ var n = "Warning: " + e;
65
+ typeof console < "u" && console.warn(n);
66
+ try {
67
+ throw Error(n);
68
+ } catch {
69
+ }
70
+ }
71
+ }
72
+ var C = { exports: {} }, L = {}, N = { exports: {} }, P = {};
73
+ var K;
74
+ function le() {
75
+ if (K) return P;
76
+ K = 1;
77
+ var t = A;
78
+ function e(h, p) {
79
+ return h === p && (h !== 0 || 1 / h === 1 / p) || h !== h && p !== p;
80
+ }
81
+ var n = typeof Object.is == "function" ? Object.is : e, r = t.useState, o = t.useEffect, i = t.useLayoutEffect, c = t.useDebugValue;
82
+ function u(h, p) {
83
+ var l = p(), f = r({ inst: { value: l, getSnapshot: p } }), d = f[0].inst, k = f[1];
84
+ return i(
85
+ function() {
86
+ d.value = l, d.getSnapshot = p, a(d) && k({ inst: d });
87
+ },
88
+ [h, l, p]
89
+ ), o(
90
+ function() {
91
+ return a(d) && k({ inst: d }), h(function() {
92
+ a(d) && k({ inst: d });
93
+ });
94
+ },
95
+ [h]
96
+ ), c(l), l;
97
+ }
98
+ function a(h) {
99
+ var p = h.getSnapshot;
100
+ h = h.value;
101
+ try {
102
+ var l = p();
103
+ return !n(h, l);
104
+ } catch {
105
+ return !0;
106
+ }
107
+ }
108
+ function s(h, p) {
109
+ return p();
110
+ }
111
+ var v = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? s : u;
112
+ return P.useSyncExternalStore = t.useSyncExternalStore !== void 0 ? t.useSyncExternalStore : v, P;
113
+ }
114
+ var b = {};
115
+ var F;
116
+ function fe() {
117
+ return F || (F = 1, process.env.NODE_ENV !== "production" && (function() {
118
+ function t(l, f) {
119
+ return l === f && (l !== 0 || 1 / l === 1 / f) || l !== l && f !== f;
120
+ }
121
+ function e(l, f) {
122
+ v || o.startTransition === void 0 || (v = !0, console.error(
123
+ "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
+ var d = f();
126
+ if (!h) {
127
+ var k = f();
128
+ i(d, k) || (console.error(
129
+ "The result of getSnapshot should be cached to avoid an infinite loop"
130
+ ), h = !0);
131
+ }
132
+ k = c({
133
+ inst: { value: d, getSnapshot: f }
134
+ });
135
+ var g = k[0].inst, T = k[1];
136
+ return a(
137
+ function() {
138
+ g.value = d, g.getSnapshot = f, n(g) && T({ inst: g });
139
+ },
140
+ [l, d, f]
141
+ ), u(
142
+ function() {
143
+ return n(g) && T({ inst: g }), l(function() {
144
+ n(g) && T({ inst: g });
145
+ });
146
+ },
147
+ [l]
148
+ ), s(d), d;
149
+ }
150
+ function n(l) {
151
+ var f = l.getSnapshot;
152
+ l = l.value;
153
+ try {
154
+ var d = f();
155
+ return !i(l, d);
156
+ } catch {
157
+ return !0;
158
+ }
159
+ }
160
+ function r(l, f) {
161
+ return f();
162
+ }
163
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
164
+ var o = A, i = typeof Object.is == "function" ? Object.is : t, c = o.useState, u = o.useEffect, a = o.useLayoutEffect, s = o.useDebugValue, v = !1, h = !1, p = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? r : e;
165
+ b.useSyncExternalStore = o.useSyncExternalStore !== void 0 ? o.useSyncExternalStore : p, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
166
+ })()), b;
167
+ }
168
+ var G;
169
+ function ee() {
170
+ return G || (G = 1, process.env.NODE_ENV === "production" ? N.exports = le() : N.exports = fe()), N.exports;
171
+ }
172
+ var q;
173
+ function de() {
174
+ if (q) return L;
175
+ q = 1;
176
+ var t = A, e = ee();
177
+ function n(s, v) {
178
+ return s === v && (s !== 0 || 1 / s === 1 / v) || s !== s && v !== v;
179
+ }
180
+ var r = typeof Object.is == "function" ? Object.is : n, o = e.useSyncExternalStore, i = t.useRef, c = t.useEffect, u = t.useMemo, a = t.useDebugValue;
181
+ return L.useSyncExternalStoreWithSelector = function(s, v, h, p, l) {
182
+ var f = i(null);
183
+ if (f.current === null) {
184
+ var d = { hasValue: !1, value: null };
185
+ f.current = d;
186
+ } else d = f.current;
187
+ f = u(
188
+ function() {
189
+ function g(m) {
190
+ if (!T) {
191
+ if (T = !0, y = m, m = p(m), l !== void 0 && d.hasValue) {
192
+ var E = d.value;
193
+ if (l(E, m))
194
+ return O = E;
195
+ }
196
+ return O = m;
197
+ }
198
+ if (E = O, r(y, m)) return E;
199
+ var W = p(m);
200
+ return l !== void 0 && l(E, W) ? (y = m, E) : (y = m, O = W);
201
+ }
202
+ var T = !1, y, O, w = h === void 0 ? null : h;
203
+ return [
204
+ function() {
205
+ return g(v());
206
+ },
207
+ w === null ? void 0 : function() {
208
+ return g(w());
209
+ }
210
+ ];
211
+ },
212
+ [v, h, p, l]
213
+ );
214
+ var k = o(s, f[0], f[1]);
215
+ return c(
216
+ function() {
217
+ d.hasValue = !0, d.value = k;
218
+ },
219
+ [k]
220
+ ), a(k), k;
221
+ }, L;
222
+ }
223
+ var I = {};
224
+ var X;
225
+ function he() {
226
+ return X || (X = 1, process.env.NODE_ENV !== "production" && (function() {
227
+ function t(s, v) {
228
+ return s === v && (s !== 0 || 1 / s === 1 / v) || s !== s && v !== v;
229
+ }
230
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
231
+ var e = A, n = ee(), r = typeof Object.is == "function" ? Object.is : t, o = n.useSyncExternalStore, i = e.useRef, c = e.useEffect, u = e.useMemo, a = e.useDebugValue;
232
+ I.useSyncExternalStoreWithSelector = function(s, v, h, p, l) {
233
+ var f = i(null);
234
+ if (f.current === null) {
235
+ var d = { hasValue: !1, value: null };
236
+ f.current = d;
237
+ } else d = f.current;
238
+ f = u(
239
+ function() {
240
+ function g(m) {
241
+ if (!T) {
242
+ if (T = !0, y = m, m = p(m), l !== void 0 && d.hasValue) {
243
+ var E = d.value;
244
+ if (l(E, m))
245
+ return O = E;
246
+ }
247
+ return O = m;
248
+ }
249
+ if (E = O, r(y, m))
250
+ return E;
251
+ var W = p(m);
252
+ return l !== void 0 && l(E, W) ? (y = m, E) : (y = m, O = W);
253
+ }
254
+ var T = !1, y, O, w = h === void 0 ? null : h;
255
+ return [
256
+ function() {
257
+ return g(v());
258
+ },
259
+ w === null ? void 0 : function() {
260
+ return g(w());
261
+ }
262
+ ];
263
+ },
264
+ [v, h, p, l]
265
+ );
266
+ var k = o(s, f[0], f[1]);
267
+ return c(
268
+ function() {
269
+ d.hasValue = !0, d.value = k;
270
+ },
271
+ [k]
272
+ ), a(k), k;
273
+ }, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
274
+ })()), I;
275
+ }
276
+ var $;
277
+ function pe() {
278
+ return $ || ($ = 1, process.env.NODE_ENV === "production" ? C.exports = de() : C.exports = he()), C.exports;
279
+ }
280
+ var ve = pe();
281
+ function ke(t, e = (r) => r, n = {}) {
282
+ const r = n.equal ?? me;
283
+ return ve.useSyncExternalStoreWithSelector(
284
+ t.subscribe,
285
+ () => t.state,
286
+ () => t.state,
287
+ e,
288
+ r
289
+ );
290
+ }
291
+ function me(t, e) {
292
+ if (Object.is(t, e))
293
+ return !0;
294
+ if (typeof t != "object" || t === null || typeof e != "object" || e === null)
295
+ return !1;
296
+ if (t instanceof Map && e instanceof Map) {
297
+ if (t.size !== e.size) return !1;
298
+ for (const [r, o] of t)
299
+ if (!e.has(r) || !Object.is(o, e.get(r))) return !1;
300
+ return !0;
301
+ }
302
+ if (t instanceof Set && e instanceof Set) {
303
+ if (t.size !== e.size) return !1;
304
+ for (const r of t)
305
+ if (!e.has(r)) return !1;
306
+ return !0;
307
+ }
308
+ if (t instanceof Date && e instanceof Date)
309
+ return t.getTime() === e.getTime();
310
+ const n = j(t);
311
+ if (n.length !== j(e).length)
312
+ return !1;
313
+ for (let r = 0; r < n.length; r++)
314
+ if (!Object.prototype.hasOwnProperty.call(e, n[r]) || !Object.is(t[n[r]], e[n[r]]))
315
+ return !1;
316
+ return !0;
317
+ }
318
+ function j(t) {
319
+ return Object.keys(t).concat(
320
+ Object.getOwnPropertySymbols(t)
321
+ );
322
+ }
323
+ const D = S.createContext(null);
324
+ function ge() {
325
+ return typeof document > "u" ? D : window.__TSR_ROUTER_CONTEXT__ ? window.__TSR_ROUTER_CONTEXT__ : (window.__TSR_ROUTER_CONTEXT__ = D, D);
326
+ }
327
+ function Ee(t) {
328
+ const e = S.useContext(ge());
329
+ return ue(
330
+ !((t?.warn ?? !0) && !e),
331
+ "useRouter must be used inside a <RouterProvider> component!"
332
+ ), e;
333
+ }
334
+ function Se(t) {
335
+ const e = Ee({
336
+ warn: t?.router === void 0
337
+ }), n = t?.router || e, r = R(void 0);
338
+ return ke(n.__store, (o) => {
339
+ if (t?.select) {
340
+ if (t.structuralSharing ?? n.options.defaultStructuralSharing) {
341
+ const i = Z(
342
+ r.current,
343
+ t.select(o)
344
+ );
345
+ return r.current = i, i;
346
+ }
347
+ return t.select(o);
348
+ }
349
+ return o;
350
+ });
351
+ }
352
+ function _e(t) {
353
+ return Se({
354
+ select: (e) => e.location
355
+ });
356
+ }
357
+ class Te {
358
+ serviceWorkerRegistration = null;
359
+ sharedWorker = null;
360
+ sharedWorkerPort = null;
361
+ workerType = null;
362
+ pendingAuthToken = null;
363
+ // connection status subscribers
364
+ connectionStatusCallbacks = /* @__PURE__ */ new Set();
365
+ serviceWorkerMessageHandler = null;
366
+ // Mutex/promise to prevent concurrent init runs
367
+ initPromise = null;
368
+ // Initialize and choose worker implementation (prefer SharedWorker)
369
+ async init(e) {
370
+ return this.initPromise ? this.initPromise.then(async () => {
371
+ e && this.workerType !== "service" && await this.init(e);
372
+ }) : (this.initPromise = (async () => {
373
+ try {
374
+ if (e) {
375
+ this.serviceWorkerRegistration = e, this.workerType = "service", console.log("[WorkerClient] Using ServiceWorker (explicit registration)"), this.pendingAuthToken && (this.sendAuthTokenToServiceWorker(this.pendingAuthToken), this.pendingAuthToken = null);
376
+ return;
377
+ }
378
+ if (typeof SharedWorker < "u")
379
+ try {
380
+ if (this.sharedWorker = new SharedWorker("/shared-worker.js", { type: "module" }), this.sharedWorkerPort = this.sharedWorker.port, this.sharedWorkerPort.start(), this.pendingAuthToken && this.sharedWorkerPort)
381
+ try {
382
+ this.sharedWorkerPort.postMessage({ type: "SET_AUTH_TOKEN", token: this.pendingAuthToken });
383
+ } catch (r) {
384
+ console.warn("[WorkerClient] Immediate postMessage to SharedWorker failed (will retry after init):", r);
385
+ }
386
+ this.sharedWorker.onerror = (r) => {
387
+ console.error("[WorkerClient] SharedWorker error:", r.message || r.error || r), this.workerType !== "shared" && this.initServiceWorkerFallback().catch((o) => {
388
+ console.error("[WorkerClient] Failed to initialize ServiceWorker fallback:", o);
389
+ });
390
+ }, await new Promise((r, o) => {
391
+ let i = !1;
392
+ const c = setTimeout(() => {
393
+ if (!i) {
394
+ const a = this.sharedWorkerPort;
395
+ a && (a.onmessage = null), o(new Error("SharedWorker initialization timeout"));
396
+ }
397
+ }, 2e3), u = this.sharedWorkerPort;
398
+ if (!u)
399
+ return clearTimeout(c), o(new Error("SharedWorker port not available"));
400
+ u.onmessage = (a) => {
401
+ try {
402
+ const s = a.data;
403
+ s && s.type === "CONNECTION_STATUS" && (clearTimeout(c), i = !0, this.workerType = "shared", u.onmessage = null, r());
404
+ } catch {
405
+ }
406
+ };
407
+ });
408
+ const n = this.sharedWorkerPort;
409
+ if (this.pendingAuthToken && n)
410
+ try {
411
+ n.postMessage({ type: "SET_AUTH_TOKEN", token: this.pendingAuthToken }), this.pendingAuthToken = null;
412
+ } catch (r) {
413
+ console.error("[WorkerClient] Failed to send pending auth token to SharedWorker:", r);
414
+ }
415
+ n && (n.onmessage = (r) => {
416
+ try {
417
+ const o = r.data;
418
+ if (o && o.type === "CONNECTION_STATUS") {
419
+ const i = !!o.connected;
420
+ this.connectionStatusCallbacks.forEach((c) => {
421
+ try {
422
+ c(i);
423
+ } catch {
424
+ }
425
+ });
426
+ }
427
+ } catch {
428
+ }
429
+ }), console.log("[WorkerClient] Using SharedWorker");
430
+ return;
431
+ } catch (n) {
432
+ console.warn("[WorkerClient] SharedWorker not available, falling back to ServiceWorker:", n);
433
+ }
434
+ console.log("this should not be called"), await this.initServiceWorkerFallback(), this.pendingAuthToken && this.workerType === "service" && (this.sendAuthTokenToServiceWorker(this.pendingAuthToken), this.pendingAuthToken = null);
435
+ } finally {
436
+ this.initPromise = null;
437
+ }
438
+ })(), this.initPromise);
439
+ }
440
+ async initServiceWorkerFallback() {
441
+ if (console.log("initServiceWorkerFallback called"), "serviceWorker" in navigator)
442
+ try {
443
+ const e = await navigator.serviceWorker.getRegistration();
444
+ if (e) {
445
+ this.serviceWorkerRegistration = e, this.workerType = "service", console.log("[WorkerClient] Using existing ServiceWorker registration");
446
+ return;
447
+ }
448
+ const n = await navigator.serviceWorker.register("/sw.js");
449
+ this.serviceWorkerRegistration = n, this.workerType = "service", console.log("[WorkerClient] Using ServiceWorker (fallback)"), this.serviceWorkerMessageHandler && (navigator.serviceWorker.removeEventListener("message", this.serviceWorkerMessageHandler), this.serviceWorkerMessageHandler = null), this.serviceWorkerMessageHandler = (r) => {
450
+ try {
451
+ const o = r.data;
452
+ if (o && o.type === "CONNECTION_STATUS") {
453
+ const i = !!o.connected;
454
+ this.connectionStatusCallbacks.forEach((c) => {
455
+ try {
456
+ c(i);
457
+ } catch {
458
+ }
459
+ });
460
+ }
461
+ } catch {
462
+ }
463
+ }, navigator.serviceWorker.addEventListener("message", this.serviceWorkerMessageHandler);
464
+ } catch (e) {
465
+ throw console.error("[WorkerClient] Failed to register ServiceWorker:", e), e;
466
+ }
467
+ else
468
+ throw new Error("Neither SharedWorker nor ServiceWorker is supported");
469
+ }
470
+ // Low-level request that expects a reply via MessageChannel
471
+ async request(e, n, r = 5e3) {
472
+ if (this.workerType === "shared" && this.sharedWorkerPort)
473
+ return new Promise((o, i) => {
474
+ const c = new MessageChannel(), u = setTimeout(() => {
475
+ c.port1.onmessage = null, i(new Error("Request timeout"));
476
+ }, r);
477
+ c.port1.onmessage = (a) => {
478
+ clearTimeout(u), a.data && a.data.success ? o(a.data) : a.data && a.data.success === !1 ? i(new Error(a.data.error || "Worker error")) : o(a.data);
479
+ };
480
+ try {
481
+ const a = this.sharedWorkerPort;
482
+ if (!a)
483
+ return clearTimeout(u), i(new Error("SharedWorker port not available"));
484
+ a.postMessage({ type: e, ...n || {} }, [c.port2]);
485
+ } catch (a) {
486
+ clearTimeout(u), i(a instanceof Error ? a : new Error(String(a)));
487
+ }
488
+ });
489
+ if (this.workerType === "service" && this.serviceWorkerRegistration) {
490
+ const o = this.serviceWorkerRegistration;
491
+ if (!o) throw new Error("Service worker registration missing");
492
+ if (!o.active && (await navigator.serviceWorker.ready, !o.active))
493
+ throw new Error("Service worker not active");
494
+ return new Promise((i, c) => {
495
+ const u = new MessageChannel(), a = setTimeout(() => {
496
+ u.port1.onmessage = null, c(new Error("Request timeout"));
497
+ }, r);
498
+ u.port1.onmessage = (s) => {
499
+ clearTimeout(a), s.data && s.data.success ? i(s.data) : s.data && s.data.success === !1 ? c(new Error(s.data.error || "Worker error")) : i(s.data);
500
+ };
501
+ try {
502
+ const s = o.active;
503
+ if (!s)
504
+ return clearTimeout(a), c(new Error("Service worker active instance not available"));
505
+ s.postMessage({ type: e, ...n || {} }, [u.port2]);
506
+ } catch (s) {
507
+ clearTimeout(a), c(s instanceof Error ? s : new Error(String(s)));
508
+ }
509
+ });
510
+ }
511
+ throw new Error("No worker registered");
512
+ }
513
+ // Fire-and-forget postMessage (no response expected)
514
+ async post(e, n) {
515
+ if (this.workerType === "shared" && this.sharedWorkerPort) {
516
+ try {
517
+ this.sharedWorkerPort.postMessage({ type: e, ...n || {} });
518
+ } catch (r) {
519
+ console.error("[WorkerClient] Failed to post to SharedWorker:", r);
520
+ }
521
+ return;
522
+ }
523
+ if (this.workerType === "service" && this.serviceWorkerRegistration?.active) {
524
+ try {
525
+ this.serviceWorkerRegistration.active.postMessage({ type: e, ...n || {} });
526
+ } catch (r) {
527
+ console.error("[WorkerClient] Failed to post to ServiceWorker (active):", r);
528
+ }
529
+ return;
530
+ }
531
+ if ("serviceWorker" in navigator && navigator.serviceWorker.controller) {
532
+ try {
533
+ navigator.serviceWorker.controller.postMessage({ type: e, ...n || {} });
534
+ } catch (r) {
535
+ console.error("[WorkerClient] Failed to post to ServiceWorker.controller:", r);
536
+ }
537
+ return;
538
+ }
539
+ if (e === "SET_AUTH_TOKEN" && n) {
540
+ const r = n.token;
541
+ typeof r == "string" && (this.pendingAuthToken = r);
542
+ }
543
+ }
544
+ sendAuthTokenToServiceWorker(e) {
545
+ if (this.serviceWorkerRegistration?.active)
546
+ try {
547
+ this.serviceWorkerRegistration.active.postMessage({ type: "SET_AUTH_TOKEN", token: e });
548
+ } catch (n) {
549
+ console.error("[WorkerClient] Failed to send auth token to ServiceWorker:", n);
550
+ }
551
+ else if ("serviceWorker" in navigator && navigator.serviceWorker.controller)
552
+ try {
553
+ navigator.serviceWorker.controller.postMessage({ type: "SET_AUTH_TOKEN", token: e });
554
+ } catch (n) {
555
+ console.error("[WorkerClient] Failed to send auth token to ServiceWorker.controller:", n);
556
+ }
557
+ else
558
+ this.pendingAuthToken = e;
559
+ }
560
+ // Subscription API for consumers to listen for connection status updates
561
+ onConnectionStatus(e) {
562
+ this.connectionStatusCallbacks.add(e);
563
+ }
564
+ offConnectionStatus(e) {
565
+ this.connectionStatusCallbacks.delete(e);
566
+ }
567
+ async getConnectionStatus() {
568
+ try {
569
+ const e = await this.request("GET_CONNECTION_STATUS", void 0, 2e3);
570
+ return e && typeof e == "object" && "connected" in e, !!e.connected;
571
+ } catch {
572
+ return !1;
573
+ }
574
+ }
575
+ setAuthToken(e) {
576
+ if (this.pendingAuthToken = e, this.workerType === "shared" && this.sharedWorkerPort)
577
+ try {
578
+ this.sharedWorkerPort.postMessage({ type: "SET_AUTH_TOKEN", token: e }), this.pendingAuthToken = null;
579
+ } catch (n) {
580
+ console.error("[WorkerClient] Failed to set auth token on SharedWorker:", n);
581
+ }
582
+ else this.workerType === "service" && (this.sendAuthTokenToServiceWorker(e), this.pendingAuthToken = null);
583
+ }
584
+ }
585
+ const te = new Te();
586
+ async function re(t) {
587
+ return te.init(t);
588
+ }
589
+ async function M(t) {
590
+ const e = { ...t, timestamp: Date.now() };
591
+ await te.request("STORE_EVENT", { event: e });
592
+ }
593
+ async function ne(t, e, n) {
594
+ return M({ type: "navigation", from: t, to: e, path: n || e });
595
+ }
596
+ async function oe(t, e, n) {
597
+ const r = t.id || void 0, o = t.className || void 0, i = t.textContent?.trim().substring(0, 100) || void 0, c = t.tagName.toLowerCase();
598
+ return M({
599
+ type: "click",
600
+ element: c,
601
+ elementId: r,
602
+ elementClass: o,
603
+ elementText: i,
604
+ path: e || window.location.pathname,
605
+ metadata: n
606
+ });
607
+ }
608
+ async function ie(t, e, n) {
609
+ const r = t.id || void 0, o = t.className || void 0, i = t.tagName.toLowerCase();
610
+ return M({
611
+ type: "input",
612
+ element: i,
613
+ elementId: r,
614
+ elementClass: o,
615
+ path: n || window.location.pathname,
616
+ metadata: {
617
+ valueLength: e?.length || 0,
618
+ value: e
619
+ }
620
+ });
621
+ }
622
+ function be() {
623
+ const t = _e(), [e, n] = Q(!1), r = R(t.pathname), o = R(null);
624
+ _(() => {
625
+ r.current !== t.pathname && (o.current = r.current, r.current = t.pathname);
626
+ }, [t.pathname]), _(() => {
627
+ re().then(() => n(!0)).catch((i) => {
628
+ console.error("Worker initialization failed:", i);
629
+ });
630
+ }, []), _(() => {
631
+ if (!e) return;
632
+ const i = o.current, c = r.current;
633
+ i && i !== c && ne(i, c, c).catch((u) => {
634
+ console.error("Failed to track navigation:", u);
635
+ });
636
+ }, [t.pathname, e]), _(() => {
637
+ if (!e) return;
638
+ const i = (c) => {
639
+ const u = c.target;
640
+ if (!u) return;
641
+ u.tagName === "BUTTON" || u.tagName === "A" || u.closest("button") || u.closest("a") || oe(u, r.current).catch((s) => {
642
+ console.error("Failed to track click:", s);
643
+ });
644
+ };
645
+ return document.addEventListener("click", i, !0), () => document.removeEventListener("click", i, !0);
646
+ }, [e]), _(() => {
647
+ if (!e) return;
648
+ let i;
649
+ const c = (u) => {
650
+ const a = u.target;
651
+ a && (a.tagName === "INPUT" || a.tagName === "TEXTAREA") && (clearTimeout(i), i = setTimeout(() => {
652
+ ie(a, a.value, r.current).catch(
653
+ (s) => {
654
+ console.error("Failed to track input:", s);
655
+ }
656
+ );
657
+ }, 1e3));
658
+ };
659
+ return document.addEventListener("input", c, !0), () => {
660
+ clearTimeout(i), document.removeEventListener("input", c, !0);
661
+ };
662
+ }, [e]);
663
+ }
664
+ var Y;
665
+ (function(t) {
666
+ t.Pop = "POP", t.Push = "PUSH", t.Replace = "REPLACE";
667
+ })(Y || (Y = {}));
668
+ function B(t, e) {
669
+ throw new Error(e);
670
+ }
671
+ var J;
672
+ (function(t) {
673
+ t.data = "data", t.deferred = "deferred", t.redirect = "redirect", t.error = "error";
674
+ })(J || (J = {}));
675
+ const ae = ["post", "put", "patch", "delete"];
676
+ new Set(ae);
677
+ const ye = ["get", ...ae];
678
+ new Set(ye);
679
+ const Oe = /* @__PURE__ */ S.createContext(null);
680
+ process.env.NODE_ENV !== "production" && (Oe.displayName = "DataRouter");
681
+ const we = /* @__PURE__ */ S.createContext(null);
682
+ process.env.NODE_ENV !== "production" && (we.displayName = "DataRouterState");
683
+ const We = /* @__PURE__ */ S.createContext(null);
684
+ process.env.NODE_ENV !== "production" && (We.displayName = "Await");
685
+ const Re = /* @__PURE__ */ S.createContext(null);
686
+ process.env.NODE_ENV !== "production" && (Re.displayName = "Navigation");
687
+ const V = /* @__PURE__ */ S.createContext(null);
688
+ process.env.NODE_ENV !== "production" && (V.displayName = "Location");
689
+ const Ce = /* @__PURE__ */ S.createContext({
690
+ outlet: null,
691
+ matches: [],
692
+ isDataRoute: !1
693
+ });
694
+ process.env.NODE_ENV !== "production" && (Ce.displayName = "Route");
695
+ const Ne = /* @__PURE__ */ S.createContext(null);
696
+ process.env.NODE_ENV !== "production" && (Ne.displayName = "RouteError");
697
+ function Ae() {
698
+ return S.useContext(V) != null;
699
+ }
700
+ function Le() {
701
+ return Ae() || (process.env.NODE_ENV !== "production" ? B(
702
+ !1,
703
+ // TODO: This error is probably because they somehow have 2 versions of the
704
+ // router loaded. We can help them understand how to avoid that.
705
+ "useLocation() may be used only in the context of a <Router> component."
706
+ ) : B()), S.useContext(V).location;
707
+ }
708
+ new Promise(() => {
709
+ });
710
+ function Ie() {
711
+ const t = Le(), [e, n] = Q(!1), r = R(t.pathname), o = R(null);
712
+ _(() => {
713
+ o.current = r.current, r.current = t.pathname;
714
+ }, [t.pathname]), _(() => {
715
+ re().then(() => {
716
+ n(!0);
717
+ }).catch((i) => {
718
+ console.error("Worker initialization failed:", i);
719
+ });
720
+ }, []), _(() => {
721
+ if (!e) return;
722
+ const i = o.current, c = r.current;
723
+ i && i !== c && ne(i, c, c).catch((u) => {
724
+ console.error("Failed to track navigation:", u);
725
+ });
726
+ }, [t.pathname, e]), _(() => {
727
+ if (!e) return;
728
+ const i = (c) => {
729
+ const u = c.target;
730
+ if (!u) return;
731
+ u.tagName === "BUTTON" || u.tagName === "A" || u.closest("button") || u.closest("a") || oe(u, r.current).catch((s) => {
732
+ console.error("Failed to track click:", s);
733
+ });
734
+ };
735
+ return document.addEventListener("click", i, !0), () => document.removeEventListener("click", i, !0);
736
+ }, [e]), _(() => {
737
+ if (!e) return;
738
+ let i;
739
+ const c = (u) => {
740
+ const a = u.target;
741
+ a && (a.tagName === "INPUT" || a.tagName === "TEXTAREA") && (clearTimeout(i), i = setTimeout(() => {
742
+ ie(a, a.value, r.current).catch(
743
+ (s) => {
744
+ console.error("Failed to track input:", s);
745
+ }
746
+ );
747
+ }, 1e3));
748
+ };
749
+ return document.addEventListener("input", c, !0), () => {
750
+ clearTimeout(i), document.removeEventListener("input", c, !0);
751
+ };
752
+ }, [e]);
753
+ }
754
+ export {
755
+ Ie as useReactRouterEventTracker,
756
+ be as useTanstackRouterEventTracker
757
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcp-fe/react-event-tracker",
3
- "version": "0.0.5",
3
+ "version": "0.0.9",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -10,7 +10,7 @@
10
10
  }
11
11
  },
12
12
  "dependencies": {
13
- "@mcp-fe/event-tracker": "0.0.5"
13
+ "@mcp-fe/event-tracker": "0.0.9"
14
14
  },
15
15
  "publishConfig": {
16
16
  "access": "public"
package/.babelrc DELETED
@@ -1,12 +0,0 @@
1
- {
2
- "presets": [
3
- [
4
- "@nx/react/babel",
5
- {
6
- "runtime": "automatic",
7
- "useBuiltIns": "usage"
8
- }
9
- ]
10
- ],
11
- "plugins": []
12
- }
package/eslint.config.mjs DELETED
@@ -1,12 +0,0 @@
1
- import nx from '@nx/eslint-plugin';
2
- import baseConfig from '../../eslint.config.mjs';
3
-
4
- export default [
5
- ...baseConfig,
6
- ...nx.configs['flat/react'],
7
- {
8
- files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
9
- // Override or add rules here
10
- rules: {},
11
- },
12
- ];
package/project.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "name": "react-event-tracker",
3
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
- "sourceRoot": "libs/react-event-tracker/src",
5
- "projectType": "library",
6
- "tags": [],
7
- "// targets": "to see all targets run: nx show project react-event-tracker --web",
8
- "targets": {}
9
- }
@@ -1,97 +0,0 @@
1
- import { useEffect, useRef, useState } from 'react';
2
- import { useLocation } from 'react-router-dom';
3
- import {
4
- initEventTracker,
5
- trackNavigation,
6
- trackClick,
7
- trackInput,
8
- } from '@mcp-fe/event-tracker';
9
-
10
- export function useReactRouterEventTracker(): void {
11
- const location = useLocation();
12
- const [isInitialized, setIsInitialized] = useState(false);
13
-
14
- const currentPathRef = useRef(location.pathname);
15
- const prevPathRef = useRef<string | null>(null);
16
-
17
- useEffect(() => {
18
- prevPathRef.current = currentPathRef.current;
19
- currentPathRef.current = location.pathname;
20
- }, [location.pathname]);
21
-
22
- useEffect(() => {
23
- initEventTracker()
24
- .then(() => {
25
- setIsInitialized(true);
26
- })
27
- .catch((error) => {
28
- console.error('Worker initialization failed:', error);
29
- });
30
- }, []);
31
-
32
- useEffect(() => {
33
- if (!isInitialized) return;
34
-
35
- const prevPath = prevPathRef.current;
36
- const currentPath = currentPathRef.current;
37
-
38
- if (prevPath && prevPath !== currentPath) {
39
- trackNavigation(prevPath, currentPath, currentPath).catch((error) => {
40
- console.error('Failed to track navigation:', error);
41
- });
42
- }
43
- }, [location.pathname, isInitialized]);
44
-
45
- useEffect(() => {
46
- if (!isInitialized) return;
47
-
48
- const handleClick = (event: MouseEvent): void => {
49
- const target = event.target as HTMLElement;
50
- if (!target) return;
51
-
52
- const isInteractive =
53
- target.tagName === 'BUTTON' ||
54
- target.tagName === 'A' ||
55
- target.closest('button') ||
56
- target.closest('a');
57
-
58
- if (!isInteractive) {
59
- trackClick(target, currentPathRef.current).catch((error) => {
60
- console.error('Failed to track click:', error);
61
- });
62
- }
63
- };
64
-
65
- document.addEventListener('click', handleClick, true);
66
- return () => document.removeEventListener('click', handleClick, true);
67
- }, [isInitialized]);
68
-
69
- useEffect(() => {
70
- if (!isInitialized) return;
71
-
72
- let timeoutId: ReturnType<typeof setTimeout>;
73
-
74
- const handleInput = (event: Event): void => {
75
- const target = event.target as HTMLInputElement | HTMLTextAreaElement;
76
- if (
77
- target &&
78
- (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')
79
- ) {
80
- clearTimeout(timeoutId);
81
- timeoutId = setTimeout(() => {
82
- trackInput(target, target.value, currentPathRef.current).catch(
83
- (error) => {
84
- console.error('Failed to track input:', error);
85
- },
86
- );
87
- }, 1000); // Debounce by 1 second
88
- }
89
- };
90
-
91
- document.addEventListener('input', handleInput, true);
92
- return () => {
93
- clearTimeout(timeoutId);
94
- document.removeEventListener('input', handleInput, true);
95
- };
96
- }, [isInitialized]);
97
- }
@@ -1,97 +0,0 @@
1
- import { useEffect, useRef, useState } from 'react';
2
- import { useLocation } from '@tanstack/react-router';
3
- import {
4
- initEventTracker,
5
- trackNavigation,
6
- trackClick,
7
- trackInput,
8
- } from '@mcp-fe/event-tracker';
9
-
10
- export function useTanstackRouterEventTracker(): void {
11
- const location = useLocation();
12
- const [isInitialized, setIsInitialized] = useState(false);
13
-
14
- const currentPathRef = useRef(location.pathname);
15
- const prevPathRef = useRef<string | null>(null);
16
-
17
- useEffect(() => {
18
- if (currentPathRef.current !== location.pathname) {
19
- prevPathRef.current = currentPathRef.current;
20
- currentPathRef.current = location.pathname;
21
- }
22
- }, [location.pathname]);
23
-
24
- useEffect(() => {
25
- initEventTracker()
26
- .then(() => setIsInitialized(true))
27
- .catch((error) => {
28
- console.error('Worker initialization failed:', error);
29
- });
30
- }, []);
31
-
32
- useEffect(() => {
33
- if (!isInitialized) return;
34
-
35
- const prevPath = prevPathRef.current;
36
- const currentPath = currentPathRef.current;
37
-
38
- if (prevPath && prevPath !== currentPath) {
39
- trackNavigation(prevPath, currentPath, currentPath).catch((error) => {
40
- console.error('Failed to track navigation:', error);
41
- });
42
- }
43
- }, [location.pathname, isInitialized]);
44
-
45
- useEffect(() => {
46
- if (!isInitialized) return;
47
-
48
- const handleClick = (event: MouseEvent): void => {
49
- const target = event.target as HTMLElement;
50
- if (!target) return;
51
-
52
- const isInteractive =
53
- target.tagName === 'BUTTON' ||
54
- target.tagName === 'A' ||
55
- target.closest('button') ||
56
- target.closest('a');
57
-
58
- if (!isInteractive) {
59
- trackClick(target, currentPathRef.current).catch((error) => {
60
- console.error('Failed to track click:', error);
61
- });
62
- }
63
- };
64
-
65
- document.addEventListener('click', handleClick, true);
66
- return () => document.removeEventListener('click', handleClick, true);
67
- }, [isInitialized]);
68
-
69
- useEffect(() => {
70
- if (!isInitialized) return;
71
-
72
- let timeoutId: ReturnType<typeof setTimeout>;
73
-
74
- const handleInput = (event: Event): void => {
75
- const target = event.target as HTMLInputElement | HTMLTextAreaElement;
76
- if (
77
- target &&
78
- (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')
79
- ) {
80
- clearTimeout(timeoutId);
81
- timeoutId = setTimeout(() => {
82
- trackInput(target, target.value, currentPathRef.current).catch(
83
- (error) => {
84
- console.error('Failed to track input:', error);
85
- },
86
- );
87
- }, 1000);
88
- }
89
- };
90
-
91
- document.addEventListener('input', handleInput, true);
92
- return () => {
93
- clearTimeout(timeoutId);
94
- document.removeEventListener('input', handleInput, true);
95
- };
96
- }, [isInitialized]);
97
- }
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "jsx": "react-jsx",
4
- "allowJs": false,
5
- "esModuleInterop": false,
6
- "allowSyntheticDefaultImports": true,
7
- "strict": true,
8
- "types": ["vite/client", "vitest"],
9
- "lib": ["dom", "esnext"]
10
- },
11
- "files": [],
12
- "include": [],
13
- "references": [
14
- {
15
- "path": "./tsconfig.lib.json"
16
- },
17
- {
18
- "path": "./tsconfig.spec.json"
19
- }
20
- ],
21
- "extends": "../../tsconfig.base.json"
22
- }
package/tsconfig.lib.json DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "../../dist/out-tsc",
5
- "types": [
6
- "node",
7
- "@nx/react/typings/cssmodule.d.ts",
8
- "@nx/react/typings/image.d.ts",
9
- "vite/client"
10
- ]
11
- },
12
- "exclude": [
13
- "**/*.spec.ts",
14
- "**/*.test.ts",
15
- "**/*.spec.tsx",
16
- "**/*.test.tsx",
17
- "**/*.spec.js",
18
- "**/*.test.js",
19
- "**/*.spec.jsx",
20
- "**/*.test.jsx",
21
- "vite.config.ts",
22
- "vite.config.mts",
23
- "vitest.config.ts",
24
- "vitest.config.mts",
25
- "src/**/*.test.ts",
26
- "src/**/*.spec.ts",
27
- "src/**/*.test.tsx",
28
- "src/**/*.spec.tsx",
29
- "src/**/*.test.js",
30
- "src/**/*.spec.js",
31
- "src/**/*.test.jsx",
32
- "src/**/*.spec.jsx"
33
- ],
34
- "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"],
35
- "references": []
36
- }
@@ -1,28 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "../../dist/out-tsc",
5
- "types": [
6
- "vitest/globals",
7
- "vitest/importMeta",
8
- "vite/client",
9
- "node",
10
- "vitest"
11
- ]
12
- },
13
- "include": [
14
- "vite.config.ts",
15
- "vite.config.mts",
16
- "vitest.config.ts",
17
- "vitest.config.mts",
18
- "src/**/*.test.ts",
19
- "src/**/*.spec.ts",
20
- "src/**/*.test.tsx",
21
- "src/**/*.spec.tsx",
22
- "src/**/*.test.js",
23
- "src/**/*.spec.js",
24
- "src/**/*.test.jsx",
25
- "src/**/*.spec.jsx",
26
- "src/**/*.d.ts"
27
- ]
28
- }
package/vite.config.mts DELETED
@@ -1,61 +0,0 @@
1
- /// <reference types='vitest' />
2
- import { defineConfig } from 'vite';
3
- import react from '@vitejs/plugin-react';
4
- import dts from 'vite-plugin-dts';
5
- import * as path from 'path';
6
- import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';
7
- import { nxCopyAssetsPlugin } from '@nx/vite/plugins/nx-copy-assets.plugin';
8
-
9
- export default defineConfig(() => ({
10
- root: import.meta.dirname,
11
- cacheDir: '../../node_modules/.vite/libs/react-event-tracker',
12
- plugins: [
13
- react(),
14
- nxViteTsPaths(),
15
- nxCopyAssetsPlugin(['*.md']),
16
- dts({
17
- entryRoot: 'src',
18
- tsconfigPath: path.join(import.meta.dirname, 'tsconfig.lib.json'),
19
- pathsToAliases: false,
20
- }),
21
- ],
22
- // Uncomment this if you are using workers.
23
- // worker: {
24
- // plugins: () => [ nxViteTsPaths() ],
25
- // },
26
- // Configuration for building your library.
27
- // See: https://vite.dev/guide/build.html#library-mode
28
- build: {
29
- outDir: '../../dist/libs/react-event-tracker',
30
- emptyOutDir: true,
31
- reportCompressedSize: true,
32
- commonjsOptions: {
33
- transformMixedEsModules: true,
34
- },
35
- lib: {
36
- // Could also be a dictionary or array of multiple entry points.
37
- entry: 'src/index.ts',
38
- name: 'react-event-tracker',
39
- fileName: 'index',
40
- // Change this to the formats you want to support.
41
- // Don't forget to update your package.json as well.
42
- formats: ['es' as const],
43
- },
44
- rollupOptions: {
45
- // External packages that should not be bundled into your library.
46
- external: ['react', 'react-dom', 'react/jsx-runtime'],
47
- },
48
- },
49
- test: {
50
- name: 'react-event-tracker',
51
- watch: false,
52
- globals: true,
53
- environment: 'jsdom',
54
- include: ['{src,tests}/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
55
- reporters: ['default'],
56
- coverage: {
57
- reportsDirectory: '../../coverage/libs/react-event-tracker',
58
- provider: 'v8' as const,
59
- },
60
- },
61
- }));