@mcp-fe/event-tracker 0.0.15 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -188,7 +188,7 @@
188
188
  same page as the copyright notice for easier identification within
189
189
  third-party archives.
190
190
 
191
- Copyright 2026 [name of copyright owner]
191
+ Copyright 2026 Michal Kopecky
192
192
 
193
193
  Licensed under the Apache License, Version 2.0 (the "License");
194
194
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -1,11 +1,460 @@
1
- # event-tracker
1
+ # @mcp-fe/event-tracker
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ Framework-agnostic event tracking library for the MCP-FE (Model Context Protocol - Frontend Edge) ecosystem. This library provides a simple, clean API for tracking user interactions and making them available to AI agents through the MCP protocol.
4
4
 
5
- ## Building
5
+ ## Overview
6
6
 
7
- Run `nx build event-tracker` to build the library.
7
+ `@mcp-fe/event-tracker` is a lightweight wrapper around [`@mcp-fe/mcp-worker`](../mcp-worker/README.md) that provides an ergonomic API for tracking user events in any JavaScript application. It serves as the foundation for framework-specific integrations like [`@mcp-fe/react-event-tracker`](../react-event-tracker/README.md).
8
8
 
9
- ## Running unit tests
9
+ ### Key Features
10
10
 
11
- Run `nx test event-tracker` to execute the unit tests via [Vitest](https://vitest.dev/).
11
+ - **Framework Agnostic**: Works with any JavaScript framework or vanilla JS
12
+ - **Simple API**: Clean, intuitive functions for common tracking needs
13
+ - **Rich Event Data**: Captures element details, metadata, and context
14
+ - **Connection Management**: Built-in WebSocket connection status monitoring
15
+ - **Authentication Support**: Token-based authentication for user-specific events
16
+ - **TypeScript Support**: Full type definitions included
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @mcp-fe/event-tracker
22
+ # or
23
+ pnpm add @mcp-fe/event-tracker
24
+ # or
25
+ yarn add @mcp-fe/event-tracker
26
+ ```
27
+
28
+ ### Dependencies
29
+
30
+ This package requires [`@mcp-fe/mcp-worker`](../mcp-worker/README.md) which is automatically installed as a dependency. Make sure to set up the worker files as described in the mcp-worker documentation.
31
+
32
+ ## Quick Start
33
+
34
+ ```typescript
35
+ import {
36
+ initEventTracker,
37
+ trackEvent,
38
+ trackNavigation,
39
+ trackClick
40
+ } from '@mcp-fe/event-tracker';
41
+
42
+ // Initialize the event tracker
43
+ await initEventTracker({
44
+ backendWsUrl: 'ws://localhost:3001'
45
+ });
46
+
47
+ // Track user interactions
48
+ await trackNavigation('/home', '/products');
49
+ await trackClick(document.getElementById('buy-button'));
50
+
51
+ // Track custom events
52
+ await trackEvent({
53
+ type: 'custom',
54
+ metadata: {
55
+ eventName: 'purchase_completed',
56
+ orderId: '12345',
57
+ amount: 99.99
58
+ }
59
+ });
60
+ ```
61
+
62
+ ## API Reference
63
+
64
+ ### Initialization
65
+
66
+ #### `initEventTracker(options?)`
67
+
68
+ Initialize the event tracking system. This sets up the underlying MCP worker.
69
+
70
+ **Parameters:**
71
+ - `options?: ServiceWorkerRegistration | WorkerClientInitOptions`
72
+
73
+ **WorkerClientInitOptions:**
74
+ ```typescript
75
+ interface WorkerClientInitOptions {
76
+ sharedWorkerUrl?: string; // Default: '/mcp-shared-worker.js'
77
+ serviceWorkerUrl?: string; // Default: '/mcp-service-worker.js'
78
+ backendWsUrl?: string; // Default: 'ws://localhost:3001'
79
+ }
80
+ ```
81
+
82
+ **Examples:**
83
+ ```typescript
84
+ // Basic initialization
85
+ await initEventTracker();
86
+
87
+ // With custom WebSocket URL
88
+ await initEventTracker({
89
+ backendWsUrl: 'wss://my-mcp-server.com/ws'
90
+ });
91
+
92
+ // With custom worker paths
93
+ await initEventTracker({
94
+ sharedWorkerUrl: '/assets/workers/mcp-shared-worker.js',
95
+ backendWsUrl: 'ws://localhost:3001'
96
+ });
97
+
98
+ // Using existing ServiceWorker registration
99
+ const registration = await navigator.serviceWorker.register('/mcp-service-worker.js');
100
+ await initEventTracker(registration);
101
+ ```
102
+
103
+ ### Event Tracking
104
+
105
+ #### `trackEvent(eventData)`
106
+
107
+ Track a generic user event with custom data.
108
+
109
+ **Parameters:**
110
+ - `eventData: UserEventData`
111
+
112
+ **UserEventData Interface:**
113
+ ```typescript
114
+ interface UserEventData {
115
+ type: 'navigation' | 'click' | 'input' | 'custom';
116
+ path?: string; // Current page path
117
+ from?: string; // Previous location (navigation events)
118
+ to?: string; // Next location (navigation events)
119
+ element?: string; // HTML element tag name
120
+ elementId?: string; // Element ID attribute
121
+ elementClass?: string; // Element CSS classes
122
+ elementText?: string; // Element text content (truncated to 100 chars)
123
+ metadata?: Record<string, unknown>; // Additional event data
124
+ }
125
+ ```
126
+
127
+ **Example:**
128
+ ```typescript
129
+ await trackEvent({
130
+ type: 'custom',
131
+ path: '/dashboard',
132
+ metadata: {
133
+ eventName: 'feature_used',
134
+ feature: 'export_data',
135
+ format: 'csv',
136
+ recordCount: 150
137
+ }
138
+ });
139
+ ```
140
+
141
+ #### `trackNavigation(from, to, path?)`
142
+
143
+ Track navigation between routes or pages.
144
+
145
+ **Parameters:**
146
+ - `from: string` - Previous route/URL
147
+ - `to: string` - Current route/URL
148
+ - `path?: string` - Optional explicit path (defaults to `to`)
149
+
150
+ **Example:**
151
+ ```typescript
152
+ // Basic navigation tracking
153
+ await trackNavigation('/home', '/products');
154
+
155
+ // With explicit path
156
+ await trackNavigation('/users/123', '/users/456', '/users');
157
+ ```
158
+
159
+ #### `trackClick(element, path?, metadata?)`
160
+
161
+ Track click events on HTML elements with automatic element data extraction.
162
+
163
+ **Parameters:**
164
+ - `element: HTMLElement` - The clicked element
165
+ - `path?: string` - Current page path (defaults to `window.location.pathname`)
166
+ - `metadata?: Record<string, unknown>` - Additional click data
167
+
168
+ **Example:**
169
+ ```typescript
170
+ // Track button click
171
+ const button = document.getElementById('submit-btn');
172
+ await trackClick(button);
173
+
174
+ // With additional metadata
175
+ const link = document.querySelector('a[data-product-id="123"]');
176
+ await trackClick(link, '/products', {
177
+ productId: '123',
178
+ category: 'electronics',
179
+ price: 299.99
180
+ });
181
+
182
+ // Event listener example
183
+ document.addEventListener('click', async (event) => {
184
+ if (event.target instanceof HTMLElement) {
185
+ await trackClick(event.target);
186
+ }
187
+ });
188
+ ```
189
+
190
+ #### `trackInput(element, value?, path?)`
191
+
192
+ Track input changes in forms with debouncing and value length tracking.
193
+
194
+ **Parameters:**
195
+ - `element: HTMLElement` - The input element
196
+ - `value?: string` - Input value (stored securely with length tracking)
197
+ - `path?: string` - Current page path
198
+
199
+ **Example:**
200
+ ```typescript
201
+ // Track input change
202
+ const emailInput = document.getElementById('email');
203
+ await trackInput(emailInput, emailInput.value);
204
+
205
+ // Event listener with debouncing
206
+ let timeoutId;
207
+ document.addEventListener('input', (event) => {
208
+ if (event.target instanceof HTMLInputElement) {
209
+ clearTimeout(timeoutId);
210
+ timeoutId = setTimeout(async () => {
211
+ await trackInput(event.target, event.target.value);
212
+ }, 1000); // 1 second debounce
213
+ }
214
+ });
215
+ ```
216
+
217
+ #### `trackCustom(eventName, metadata?, path?)`
218
+
219
+ Convenient wrapper for tracking custom business events.
220
+
221
+ **Parameters:**
222
+ - `eventName: string` - Name of the custom event
223
+ - `metadata?: Record<string, unknown>` - Event-specific data
224
+ - `path?: string` - Current page path
225
+
226
+ **Example:**
227
+ ```typescript
228
+ // Track business events
229
+ await trackCustom('purchase_completed', {
230
+ orderId: '12345',
231
+ amount: 99.99,
232
+ currency: 'USD',
233
+ items: ['product-1', 'product-2']
234
+ });
235
+
236
+ await trackCustom('search_performed', {
237
+ query: 'javascript tutorials',
238
+ results: 42,
239
+ filters: ['beginner', 'video']
240
+ });
241
+
242
+ await trackCustom('error_occurred', {
243
+ errorType: 'validation',
244
+ field: 'email',
245
+ message: 'Invalid email format'
246
+ });
247
+ ```
248
+
249
+ ### Connection Management
250
+
251
+ #### `getConnectionStatus()`
252
+
253
+ Check if the MCP worker is connected to the proxy server.
254
+
255
+ **Returns:** `Promise<boolean>`
256
+
257
+ **Example:**
258
+ ```typescript
259
+ const isConnected = await getConnectionStatus();
260
+ if (!isConnected) {
261
+ console.warn('MCP connection lost, events may not be available to AI agents');
262
+ }
263
+ ```
264
+
265
+ #### `onConnectionStatus(callback)` / `offConnectionStatus(callback)`
266
+
267
+ Subscribe to connection status changes.
268
+
269
+ **Parameters:**
270
+ - `callback: (connected: boolean) => void` - Status change callback
271
+
272
+ **Example:**
273
+ ```typescript
274
+ const handleConnectionChange = (connected) => {
275
+ console.log('MCP connection:', connected ? 'Connected' : 'Disconnected');
276
+
277
+ // Update UI indicator
278
+ const indicator = document.getElementById('connection-status');
279
+ indicator.className = connected ? 'connected' : 'disconnected';
280
+ indicator.textContent = connected ? '🟢 Connected' : '🔴 Offline';
281
+ };
282
+
283
+ // Start listening
284
+ onConnectionStatus(handleConnectionChange);
285
+
286
+ // Stop listening (e.g., on component unmount)
287
+ offConnectionStatus(handleConnectionChange);
288
+ ```
289
+
290
+ ### Authentication
291
+
292
+ #### `setAuthToken(token)`
293
+
294
+ Set authentication token for associating events with specific users.
295
+
296
+ **Parameters:**
297
+ - `token: string` - Authentication token (e.g., JWT)
298
+
299
+ **Example:**
300
+ ```typescript
301
+ // After user login
302
+ async function handleLogin(credentials) {
303
+ const response = await authenticateUser(credentials);
304
+
305
+ // Set token for MCP tracking
306
+ setAuthToken(response.accessToken);
307
+
308
+ // Track login event
309
+ await trackCustom('user_logged_in', {
310
+ userId: response.user.id,
311
+ method: 'password'
312
+ });
313
+ }
314
+
315
+ // On logout
316
+ async function handleLogout() {
317
+ await trackCustom('user_logged_out');
318
+
319
+ // Clear authentication
320
+ setAuthToken('');
321
+ }
322
+ ```
323
+
324
+
325
+ ## Integration with AI Agents
326
+
327
+ Once events are tracked and stored, AI agents can query them through the MCP protocol:
328
+
329
+ ```json
330
+ {
331
+ "jsonrpc": "2.0",
332
+ "method": "tools/call",
333
+ "params": {
334
+ "name": "get_user_events",
335
+ "arguments": {
336
+ "type": "click",
337
+ "limit": 10,
338
+ "startTime": 1705712400000
339
+ }
340
+ }
341
+ }
342
+ ```
343
+
344
+ This enables AI agents to:
345
+ - Provide context-aware customer support
346
+ - Debug user interface issues
347
+ - Analyze user behavior patterns
348
+ - Guide users through complex workflows
349
+ - Understand error scenarios and user frustration points
350
+
351
+ ## Best Practices
352
+
353
+ ### Event Granularity
354
+
355
+ ```typescript
356
+ // ✅ Good: Track meaningful interactions
357
+ await trackClick(submitButton, '/checkout', {
358
+ step: 'payment',
359
+ amount: totalAmount
360
+ });
361
+
362
+ // ❌ Too granular: Don't track every mouseover
363
+ document.addEventListener('mouseover', trackEvent); // Avoid this
364
+ ```
365
+
366
+ ### Sensitive Data
367
+
368
+ ```typescript
369
+ // ✅ Good: Track input activity without sensitive values
370
+ await trackInput(passwordInput, undefined, '/login'); // Don't pass actual password
371
+
372
+ // ✅ Good: Track metadata about sensitive operations
373
+ await trackCustom('payment_submitted', {
374
+ amount: 99.99,
375
+ currency: 'USD',
376
+ // Don't include card numbers or CVV
377
+ });
378
+ ```
379
+
380
+ ### Performance
381
+
382
+ ```typescript
383
+ // ✅ Good: Debounce high-frequency events
384
+ let searchTimeout;
385
+ searchInput.addEventListener('input', () => {
386
+ clearTimeout(searchTimeout);
387
+ searchTimeout = setTimeout(async () => {
388
+ await trackInput(searchInput, searchInput.value);
389
+ }, 500);
390
+ });
391
+
392
+ // ✅ Good: Batch related events
393
+ await Promise.all([
394
+ trackCustom('form_submitted'),
395
+ trackNavigation('/form', '/success')
396
+ ]);
397
+ ```
398
+
399
+ ## Error Handling
400
+
401
+ ```typescript
402
+ // Wrap tracking calls in try-catch for production resilience
403
+ async function safeTrackEvent(eventData) {
404
+ try {
405
+ await trackEvent(eventData);
406
+ } catch (error) {
407
+ // Log error but don't break user experience
408
+ console.warn('Failed to track event:', error);
409
+ }
410
+ }
411
+
412
+ // Check connection before critical tracking
413
+ const isConnected = await getConnectionStatus();
414
+ if (isConnected) {
415
+ await trackCustom('critical_business_event', eventData);
416
+ } else {
417
+ // Store locally or queue for later
418
+ localStorage.setItem('pending_events', JSON.stringify([eventData]));
419
+ }
420
+ ```
421
+
422
+ ## Troubleshooting
423
+
424
+ ### Events Not Being Stored
425
+
426
+ 1. **Check worker initialization**: Ensure `initEventTracker()` completed successfully
427
+ 2. **Verify worker files**: Make sure MCP worker files are in your public directory
428
+ 3. **Check connection**: Use `getConnectionStatus()` to verify proxy connection
429
+
430
+ ### Connection Issues
431
+
432
+ 1. **Proxy server**: Verify the MCP proxy server is running at the specified WebSocket URL
433
+ 2. **CORS**: Check browser console for CORS errors
434
+ 3. **WebSocket**: Verify WebSocket connection in browser Developer Tools
435
+
436
+ ### Memory Usage
437
+
438
+ 1. **Event cleanup**: Periodically clean old events from IndexedDB
439
+ 2. **Debouncing**: Use appropriate debouncing for high-frequency events
440
+ 3. **Selective tracking**: Only track events that provide value to AI agents
441
+
442
+ ## Requirements
443
+
444
+ - **Modern Browser**: ES2020+ support
445
+ - **MCP Worker Setup**: Requires [`@mcp-fe/mcp-worker`](../mcp-worker/README.md) configuration
446
+ - **MCP Proxy Server**: A running MCP proxy server to collect events
447
+
448
+ ## Related Packages
449
+
450
+ - **[@mcp-fe/mcp-worker](../mcp-worker/README.md)**: Core MCP worker implementation
451
+ - **[@mcp-fe/react-event-tracker](../react-event-tracker/README.md)**: React-specific integration
452
+ - **[Main MCP-FE Project](../../README.md)**: Complete ecosystem documentation
453
+
454
+ ## Credits
455
+
456
+ Created and maintained with ❤️ by [Michal Kopecký](https://github.com/kopecmi8).
457
+
458
+ ## License
459
+
460
+ Licensed under the Apache License, Version 2.0. See the [LICENSE](../../LICENSE) file for details.
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Copyright 2026 MCP-FE Contributors
2
+ * Copyright 2026 Michal Kopecky
3
3
  *
4
4
  * Licensed under the Apache License, Version 2.0 (the "License");
5
5
  * you may not use this file except in compliance with the License.
package/index.js CHANGED
@@ -1,4 +1,21 @@
1
- class g {
1
+ const m = typeof process < "u" && process.env?.NODE_ENV === "production", f = typeof process < "u" && process.env?.MCP_DEBUG, p = f === "true" || !m && f !== "false", n = {
2
+ log: (...t) => {
3
+ p && console.log(...t);
4
+ },
5
+ debug: (...t) => {
6
+ p && console.debug(...t);
7
+ },
8
+ info: (...t) => {
9
+ console.info(...t);
10
+ },
11
+ error: (...t) => {
12
+ console.error(...t);
13
+ },
14
+ warn: (...t) => {
15
+ p && console.warn(...t);
16
+ }
17
+ };
18
+ class w {
2
19
  // Configurable worker script URLs (defaults kept for backward compatibility)
3
20
  sharedWorkerUrl = "/mcp-shared-worker.js";
4
21
  serviceWorkerUrl = "/mcp-service-worker.js";
@@ -16,25 +33,34 @@ class g {
16
33
  // Initialize and choose worker implementation (prefer SharedWorker)
17
34
  // Accept either a ServiceWorkerRegistration OR WorkerInitOptions to configure URLs
18
35
  async init(e) {
36
+ n.log("[WorkerClient] init() called", {
37
+ hasOptions: !!e,
38
+ currentWorkerType: this.workerType,
39
+ initInProgress: !!this.initPromise,
40
+ timestamp: Date.now()
41
+ });
19
42
  let r;
20
- const i = e;
21
- if (i && typeof i.scope == "string")
22
- r = e;
43
+ const o = e;
44
+ if (o && typeof o.scope == "string")
45
+ r = e, n.log("[WorkerClient] Using explicit ServiceWorker registration");
23
46
  else if (e) {
24
- const o = e;
25
- o.sharedWorkerUrl && (this.sharedWorkerUrl = o.sharedWorkerUrl), o.serviceWorkerUrl && (this.serviceWorkerUrl = o.serviceWorkerUrl), o.backendWsUrl && (this.backendWsUrl = o.backendWsUrl);
47
+ const i = e;
48
+ n.log("[WorkerClient] Using WorkerClientInitOptions:", i), i.sharedWorkerUrl && (this.sharedWorkerUrl = i.sharedWorkerUrl), i.serviceWorkerUrl && (this.serviceWorkerUrl = i.serviceWorkerUrl), i.backendWsUrl && (this.backendWsUrl = i.backendWsUrl);
26
49
  }
27
50
  return this.initPromise ? this.initPromise.then(async () => {
28
51
  r && this.workerType !== "service" && await this.init(r);
29
52
  }) : (this.initPromise = (async () => {
30
53
  try {
31
54
  if (r) {
32
- this.serviceWorkerRegistration = r, this.workerType = "service", console.log(
55
+ this.serviceWorkerRegistration = r, this.workerType = "service", n.info(
33
56
  "[WorkerClient] Using ServiceWorker (explicit registration)"
34
57
  );
35
58
  try {
36
- const n = { type: "INIT", backendUrl: this.backendWsUrl };
37
- this.pendingAuthToken && (n.token = this.pendingAuthToken), this.serviceWorkerRegistration.active ? this.serviceWorkerRegistration.active.postMessage(n) : "serviceWorker" in navigator && navigator.serviceWorker.controller && navigator.serviceWorker.controller.postMessage(n);
59
+ const s = {
60
+ type: "INIT",
61
+ backendUrl: this.backendWsUrl
62
+ };
63
+ this.pendingAuthToken && (s.token = this.pendingAuthToken), this.serviceWorkerRegistration.active ? this.serviceWorkerRegistration.active.postMessage(s) : "serviceWorker" in navigator && navigator.serviceWorker.controller && navigator.serviceWorker.controller.postMessage(s);
38
64
  } catch {
39
65
  }
40
66
  return;
@@ -52,20 +78,20 @@ class g {
52
78
  try {
53
79
  this.sharedWorker = new SharedWorker(this.sharedWorkerUrl, {
54
80
  type: "module"
55
- }), this.sharedWorkerPort = this.sharedWorker.port, this.sharedWorkerPort.start(), await new Promise((r, i) => {
56
- let o = !1;
57
- const n = setTimeout(() => {
58
- if (!o) {
59
- const a = this.sharedWorkerPort;
60
- a && (a.onmessage = null), i(new Error("SharedWorker initialization timeout"));
81
+ }), this.sharedWorkerPort = this.sharedWorker.port, this.sharedWorkerPort.start(), await new Promise((r, o) => {
82
+ let i = !1;
83
+ const s = setTimeout(() => {
84
+ if (!i) {
85
+ const k = this.sharedWorkerPort;
86
+ k && (k.onmessage = null), o(new Error("SharedWorker initialization timeout"));
61
87
  }
62
- }, 2e3), c = this.sharedWorkerPort;
63
- if (!c)
64
- return clearTimeout(n), i(new Error("SharedWorker port not available"));
65
- c.onmessage = (a) => {
88
+ }, 2e3), l = this.sharedWorkerPort;
89
+ if (!l)
90
+ return clearTimeout(s), o(new Error("SharedWorker port not available"));
91
+ l.onmessage = (k) => {
66
92
  try {
67
- const s = a.data;
68
- s && s.type === "CONNECTION_STATUS" && (clearTimeout(n), o = !0, this.workerType = "shared", c.onmessage = null, r());
93
+ const h = k.data;
94
+ h && h.type === "CONNECTION_STATUS" && (clearTimeout(s), i = !0, this.workerType = "shared", l.onmessage = null, r());
69
95
  } catch {
70
96
  }
71
97
  };
@@ -73,19 +99,25 @@ class g {
73
99
  const e = this.sharedWorkerPort;
74
100
  if (e) {
75
101
  try {
76
- const r = { type: "INIT", backendUrl: this.backendWsUrl };
102
+ const r = {
103
+ type: "INIT",
104
+ backendUrl: this.backendWsUrl
105
+ };
77
106
  this.pendingAuthToken && (r.token = this.pendingAuthToken), e.postMessage(r), this.pendingAuthToken = null;
78
107
  } catch (r) {
79
- console.warn("[WorkerClient] Failed to send INIT to SharedWorker port:", r);
108
+ n.warn(
109
+ "[WorkerClient] Failed to send INIT to SharedWorker port:",
110
+ r
111
+ );
80
112
  }
81
113
  e.onmessage = (r) => {
82
114
  try {
83
- const i = r.data;
84
- if (i && i.type === "CONNECTION_STATUS") {
85
- const o = !!i.connected;
86
- this.connectionStatusCallbacks.forEach((n) => {
115
+ const o = r.data;
116
+ if (o && o.type === "CONNECTION_STATUS") {
117
+ const i = !!o.connected;
118
+ this.connectionStatusCallbacks.forEach((s) => {
87
119
  try {
88
- n(o);
120
+ s(i);
89
121
  } catch {
90
122
  }
91
123
  });
@@ -94,9 +126,9 @@ class g {
94
126
  }
95
127
  };
96
128
  }
97
- return console.log("[WorkerClient] Using SharedWorker"), !0;
129
+ return n.info("[WorkerClient] Using SharedWorker"), !0;
98
130
  } catch (e) {
99
- return console.warn(
131
+ return n.warn(
100
132
  "[WorkerClient] SharedWorker not available, falling back to ServiceWorker:",
101
133
  e
102
134
  ), !1;
@@ -107,68 +139,122 @@ class g {
107
139
  try {
108
140
  const e = await navigator.serviceWorker.getRegistration();
109
141
  if (e) {
110
- this.serviceWorkerRegistration = e, this.workerType = "service", console.log(
142
+ this.serviceWorkerRegistration = e, this.workerType = "service", n.info(
111
143
  "[WorkerClient] Using existing ServiceWorker registration"
112
144
  );
113
145
  return;
114
146
  }
115
147
  this.serviceWorkerRegistration = await navigator.serviceWorker.register(
116
148
  this.serviceWorkerUrl
117
- ), this.workerType = "service", console.log("[WorkerClient] Using MCP ServiceWorker (fallback)");
149
+ ), this.workerType = "service", n.info("[WorkerClient] Using MCP ServiceWorker (fallback)");
118
150
  try {
119
- const r = { type: "INIT", backendUrl: this.backendWsUrl };
151
+ const r = {
152
+ type: "INIT",
153
+ backendUrl: this.backendWsUrl
154
+ };
120
155
  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;
121
156
  } catch {
122
157
  }
123
158
  } catch (e) {
124
- throw console.error(
125
- "[WorkerClient] Failed to register ServiceWorker:",
126
- e
127
- ), e;
159
+ throw n.error("[WorkerClient] Failed to register ServiceWorker:", e), e;
128
160
  }
129
161
  else
130
162
  throw new Error("Neither SharedWorker nor ServiceWorker is supported");
131
163
  }
132
164
  // Low-level request that expects a reply via MessageChannel
133
- async request(e, r, i = 5e3) {
134
- if (this.workerType === "shared" && this.sharedWorkerPort)
135
- return new Promise((o, n) => {
136
- const c = new MessageChannel(), a = setTimeout(() => {
137
- c.port1.onmessage = null, n(new Error("Request timeout"));
138
- }, i);
139
- c.port1.onmessage = (s) => {
140
- clearTimeout(a), s.data && s.data.success ? o(s.data) : s.data && s.data.success === !1 ? n(new Error(s.data.error || "Worker error")) : o(s.data);
165
+ async request(e, r, o = 5e3) {
166
+ if (n.log("[WorkerClient] Request started:", {
167
+ type: e,
168
+ payload: r,
169
+ timeoutMs: o,
170
+ workerType: this.workerType,
171
+ hasSharedWorkerPort: !!this.sharedWorkerPort,
172
+ hasServiceWorkerReg: !!this.serviceWorkerRegistration
173
+ }), this.workerType === "shared" && this.sharedWorkerPort)
174
+ return new Promise((i, s) => {
175
+ const l = new MessageChannel(), k = Math.random().toString(36).substring(7), h = Date.now(), d = setTimeout(() => {
176
+ const a = Date.now() - h;
177
+ n.error("[WorkerClient] Request timeout:", {
178
+ type: e,
179
+ requestId: k,
180
+ elapsed: a,
181
+ timeoutMs: o
182
+ }), l.port1.onmessage = null, s(new Error("Request timeout"));
183
+ }, o);
184
+ l.port1.onmessage = (a) => {
185
+ try {
186
+ const c = Date.now() - h;
187
+ n.log("[WorkerClient] Request response received:", {
188
+ type: e,
189
+ requestId: k,
190
+ elapsed: c,
191
+ success: a.data?.success
192
+ }), clearTimeout(d), a.data && a.data.success ? i(a.data) : a.data && a.data.success === !1 ? s(new Error(a.data.error || "Worker error")) : i(a.data);
193
+ } catch (c) {
194
+ clearTimeout(d), l.port1.onmessage = null, s(
195
+ c instanceof Error ? c : new Error(String(c))
196
+ );
197
+ }
141
198
  };
142
199
  try {
143
- const s = this.sharedWorkerPort;
144
- if (!s)
145
- return clearTimeout(a), n(new Error("SharedWorker port not available"));
146
- s.postMessage({ type: e, ...r || {} }, [c.port2]);
147
- } catch (s) {
148
- clearTimeout(a), n(s instanceof Error ? s : new Error(String(s)));
200
+ const a = this.sharedWorkerPort;
201
+ if (!a)
202
+ return clearTimeout(d), n.error("[WorkerClient] SharedWorker port not available"), s(new Error("SharedWorker port not available"));
203
+ n.log("[WorkerClient] Posting message to SharedWorker:", {
204
+ type: e,
205
+ requestId: k
206
+ }), a.postMessage({ type: e, ...r || {} }, [l.port2]);
207
+ } catch (a) {
208
+ clearTimeout(d), n.error("[WorkerClient] Failed to post message:", a), s(a instanceof Error ? a : new Error(String(a)));
149
209
  }
150
210
  });
151
211
  if (this.workerType === "service" && this.serviceWorkerRegistration) {
152
- const o = this.serviceWorkerRegistration;
153
- if (!o) throw new Error("Service worker registration missing");
154
- if (!o.active && (await navigator.serviceWorker.ready, !o.active))
212
+ const i = this.serviceWorkerRegistration;
213
+ if (!i) throw new Error("Service worker registration missing");
214
+ if (!i.active && (n.log("[WorkerClient] ServiceWorker not active, waiting..."), await navigator.serviceWorker.ready, !i.active))
155
215
  throw new Error("Service worker not active");
156
- return new Promise((n, c) => {
157
- const a = new MessageChannel(), s = setTimeout(() => {
158
- a.port1.onmessage = null, c(new Error("Request timeout"));
159
- }, i);
160
- a.port1.onmessage = (l) => {
161
- clearTimeout(s), l.data && l.data.success ? n(l.data) : l.data && l.data.success === !1 ? c(new Error(l.data.error || "Worker error")) : n(l.data);
216
+ return new Promise((s, l) => {
217
+ const k = new MessageChannel(), h = Math.random().toString(36).substring(7), d = Date.now(), a = setTimeout(() => {
218
+ const c = Date.now() - d;
219
+ n.error("[WorkerClient] ServiceWorker request timeout:", {
220
+ type: e,
221
+ requestId: h,
222
+ elapsed: c,
223
+ timeoutMs: o
224
+ }), k.port1.onmessage = null, l(new Error("Request timeout"));
225
+ }, o);
226
+ k.port1.onmessage = (c) => {
227
+ try {
228
+ const g = Date.now() - d;
229
+ n.log("[WorkerClient] ServiceWorker response received:", {
230
+ type: e,
231
+ requestId: h,
232
+ elapsed: g,
233
+ success: c.data?.success
234
+ }), clearTimeout(a), c.data && c.data.success ? s(c.data) : c.data && c.data.success === !1 ? l(new Error(c.data.error || "Worker error")) : s(c.data);
235
+ } catch (g) {
236
+ clearTimeout(a), k.port1.onmessage = null, l(
237
+ g instanceof Error ? g : new Error(String(g))
238
+ );
239
+ }
162
240
  };
163
241
  try {
164
- const l = o.active;
165
- if (!l)
166
- return clearTimeout(s), c(
242
+ const c = i.active;
243
+ if (!c)
244
+ return clearTimeout(a), n.error(
245
+ "[WorkerClient] ServiceWorker active instance not available"
246
+ ), l(
167
247
  new Error("Service worker active instance not available")
168
248
  );
169
- l.postMessage({ type: e, ...r || {} }, [a.port2]);
170
- } catch (l) {
171
- clearTimeout(s), c(l instanceof Error ? l : new Error(String(l)));
249
+ n.log("[WorkerClient] Posting message to ServiceWorker:", {
250
+ type: e,
251
+ requestId: h
252
+ }), c.postMessage({ type: e, ...r || {} }, [k.port2]);
253
+ } catch (c) {
254
+ clearTimeout(a), n.error(
255
+ "[WorkerClient] Failed to post message to ServiceWorker:",
256
+ c
257
+ ), l(c instanceof Error ? c : new Error(String(c)));
172
258
  }
173
259
  });
174
260
  }
@@ -179,8 +265,8 @@ class g {
179
265
  if (this.workerType === "shared" && this.sharedWorkerPort) {
180
266
  try {
181
267
  this.sharedWorkerPort.postMessage({ type: e, ...r || {} });
182
- } catch (i) {
183
- console.error("[WorkerClient] Failed to post to SharedWorker:", i);
268
+ } catch (o) {
269
+ n.error("[WorkerClient] Failed to post to SharedWorker:", o);
184
270
  }
185
271
  return;
186
272
  }
@@ -190,10 +276,10 @@ class g {
190
276
  type: e,
191
277
  ...r || {}
192
278
  });
193
- } catch (i) {
194
- console.error(
279
+ } catch (o) {
280
+ n.error(
195
281
  "[WorkerClient] Failed to post to ServiceWorker (active):",
196
- i
282
+ o
197
283
  );
198
284
  }
199
285
  return;
@@ -204,17 +290,17 @@ class g {
204
290
  type: e,
205
291
  ...r || {}
206
292
  });
207
- } catch (i) {
208
- console.error(
293
+ } catch (o) {
294
+ n.error(
209
295
  "[WorkerClient] Failed to post to ServiceWorker.controller:",
210
- i
296
+ o
211
297
  );
212
298
  }
213
299
  return;
214
300
  }
215
301
  if (e === "SET_AUTH_TOKEN" && r) {
216
- const i = r.token;
217
- typeof i == "string" && (this.pendingAuthToken = i);
302
+ const o = r.token;
303
+ typeof o == "string" && (this.pendingAuthToken = o);
218
304
  }
219
305
  }
220
306
  sendAuthTokenToServiceWorker(e) {
@@ -225,7 +311,7 @@ class g {
225
311
  token: e
226
312
  });
227
313
  } catch (r) {
228
- console.error(
314
+ n.error(
229
315
  "[WorkerClient] Failed to send auth token to ServiceWorker:",
230
316
  r
231
317
  );
@@ -237,7 +323,7 @@ class g {
237
323
  token: e
238
324
  });
239
325
  } catch (r) {
240
- console.error(
326
+ n.error(
241
327
  "[WorkerClient] Failed to send auth token to ServiceWorker.controller:",
242
328
  r
243
329
  );
@@ -269,7 +355,7 @@ class g {
269
355
  try {
270
356
  this.sharedWorkerPort.postMessage({ type: "SET_AUTH_TOKEN", token: e }), this.pendingAuthToken = null;
271
357
  } catch (r) {
272
- console.error(
358
+ n.error(
273
359
  "[WorkerClient] Failed to set auth token on SharedWorker:",
274
360
  r
275
361
  );
@@ -277,75 +363,75 @@ class g {
277
363
  else this.workerType === "service" && (this.sendAuthTokenToServiceWorker(e), this.pendingAuthToken = null);
278
364
  }
279
365
  }
280
- const W = "user-activity-db", v = 1, k = "user-events";
281
- async function p() {
366
+ const T = "user-activity-db", S = 1, W = "user-events";
367
+ async function y() {
282
368
  return new Promise((t, e) => {
283
- const r = indexedDB.open(W, v);
284
- r.onerror = () => e(r.error), r.onsuccess = () => t(r.result), r.onupgradeneeded = (i) => {
285
- const o = i.target.result;
286
- if (!o.objectStoreNames.contains(k)) {
287
- const n = o.createObjectStore(k, { keyPath: "id" });
288
- n.createIndex("timestamp", "timestamp", { unique: !1 }), n.createIndex("type", "type", { unique: !1 }), n.createIndex("path", "path", { unique: !1 });
369
+ const r = indexedDB.open(T, S);
370
+ r.onerror = () => e(r.error), r.onsuccess = () => t(r.result), r.onupgradeneeded = (o) => {
371
+ const i = o.target.result;
372
+ if (!i.objectStoreNames.contains(W)) {
373
+ const s = i.createObjectStore(W, { keyPath: "id" });
374
+ s.createIndex("timestamp", "timestamp", { unique: !1 }), s.createIndex("type", "type", { unique: !1 }), s.createIndex("path", "path", { unique: !1 });
289
375
  }
290
376
  };
291
377
  });
292
378
  }
293
- async function f(t) {
294
- const o = (await p()).transaction([k], "readonly").objectStore(k).index("timestamp");
295
- return new Promise((n, c) => {
296
- const a = o.getAll();
297
- a.onsuccess = () => {
298
- let s = a.result;
299
- s.sort((l, d) => d.timestamp - l.timestamp), n(s);
300
- }, a.onerror = () => c(a.error);
379
+ async function C(t) {
380
+ const i = (await y()).transaction([W], "readonly").objectStore(W).index("timestamp");
381
+ return new Promise((s, l) => {
382
+ const k = i.getAll();
383
+ k.onsuccess = () => {
384
+ let h = k.result;
385
+ h.sort((d, a) => a.timestamp - d.timestamp), s(h);
386
+ }, k.onerror = () => l(k.error);
301
387
  });
302
388
  }
303
- const h = new g();
304
- async function T(t) {
305
- return h.init(t);
389
+ const u = new w();
390
+ async function E(t) {
391
+ return u.init(t);
306
392
  }
307
- async function u(t) {
393
+ async function v(t) {
308
394
  const e = { ...t, timestamp: Date.now() };
309
- await h.request("STORE_EVENT", { event: e });
395
+ await u.request("STORE_EVENT", { event: e });
310
396
  }
311
- async function m() {
312
- const t = await f();
397
+ async function b() {
398
+ const t = await C();
313
399
  return Array.isArray(t) ? t : [];
314
400
  }
315
- async function w() {
316
- return h.getConnectionStatus();
401
+ async function U() {
402
+ return u.getConnectionStatus();
317
403
  }
318
- function y(t) {
319
- h.setAuthToken(t);
404
+ function N(t) {
405
+ u.setAuthToken(t);
320
406
  }
321
- function S(t) {
322
- h.onConnectionStatus(t);
407
+ function P(t) {
408
+ u.onConnectionStatus(t);
323
409
  }
324
- function C(t) {
325
- h.offConnectionStatus(t);
410
+ function A(t) {
411
+ u.offConnectionStatus(t);
326
412
  }
327
- async function E(t, e, r) {
328
- return u({ type: "navigation", from: t, to: e, path: r || e });
413
+ async function R(t, e, r) {
414
+ return v({ type: "navigation", from: t, to: e, path: r || e });
329
415
  }
330
- async function b(t, e, r) {
331
- const i = t.id || void 0, o = t.className || void 0, n = t.textContent?.trim().substring(0, 100) || void 0, c = t.tagName.toLowerCase();
332
- return u({
416
+ async function I(t, e, r) {
417
+ const o = t.id || void 0, i = t.className || void 0, s = t.textContent?.trim().substring(0, 100) || void 0, l = t.tagName.toLowerCase();
418
+ return v({
333
419
  type: "click",
334
- element: c,
335
- elementId: i,
336
- elementClass: o,
337
- elementText: n,
420
+ element: l,
421
+ elementId: o,
422
+ elementClass: i,
423
+ elementText: s,
338
424
  path: e || window.location.pathname,
339
425
  metadata: r
340
426
  });
341
427
  }
342
- async function A(t, e, r) {
343
- const i = t.id || void 0, o = t.className || void 0, n = t.tagName.toLowerCase();
344
- return u({
428
+ async function M(t, e, r) {
429
+ const o = t.id || void 0, i = t.className || void 0, s = t.tagName.toLowerCase();
430
+ return v({
345
431
  type: "input",
346
- element: n,
347
- elementId: i,
348
- elementClass: o,
432
+ element: s,
433
+ elementId: o,
434
+ elementClass: i,
349
435
  path: r || window.location.pathname,
350
436
  metadata: {
351
437
  valueLength: e?.length || 0,
@@ -353,8 +439,8 @@ async function A(t, e, r) {
353
439
  }
354
440
  });
355
441
  }
356
- async function N(t, e, r) {
357
- return u({
442
+ async function _(t, e, r) {
443
+ return v({
358
444
  type: "custom",
359
445
  path: r || window.location.pathname,
360
446
  metadata: {
@@ -364,15 +450,15 @@ async function N(t, e, r) {
364
450
  });
365
451
  }
366
452
  export {
367
- w as getConnectionStatus,
368
- m as getStoredEvents,
369
- T as initEventTracker,
370
- C as offConnectionStatus,
371
- S as onConnectionStatus,
372
- y as setAuthToken,
373
- b as trackClick,
374
- N as trackCustom,
375
- u as trackEvent,
376
- A as trackInput,
377
- E as trackNavigation
453
+ U as getConnectionStatus,
454
+ b as getStoredEvents,
455
+ E as initEventTracker,
456
+ A as offConnectionStatus,
457
+ P as onConnectionStatus,
458
+ N as setAuthToken,
459
+ I as trackClick,
460
+ _ as trackCustom,
461
+ v as trackEvent,
462
+ M as trackInput,
463
+ R as trackNavigation
378
464
  };
package/package.json CHANGED
@@ -1,13 +1,19 @@
1
1
  {
2
2
  "name": "@mcp-fe/event-tracker",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "license": "Apache-2.0",
5
+ "homepage": "https://mcp-fe.ai",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/mcp-fe/mcp-fe.git",
9
+ "directory": "libs/event-tracker"
10
+ },
5
11
  "private": false,
6
12
  "type": "module",
7
13
  "main": "./index.js",
8
14
  "types": "./index.d.ts",
9
15
  "dependencies": {
10
- "@mcp-fe/mcp-worker": "0.0.15"
16
+ "@mcp-fe/mcp-worker": "0.0.17"
11
17
  },
12
18
  "publishConfig": {
13
19
  "access": "public"