@agroideas/event-tracker-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,308 @@
1
+ # @agroideas/event-tracker-sdk
2
+
3
+ A lightweight, framework-agnostic TypeScript SDK for tracking frontend user behavior. Automatically captures page views, session duration, and user interactions, sending them to a centralized analytics API.
4
+
5
+ ## Features
6
+
7
+ - 馃殌 **Lightweight**: Zero dependencies, built with native Fetch API and DOM APIs
8
+ - 馃攧 **SPA Support**: Handles navigation in Single Page Applications via History API interception
9
+ - 馃摝 **Smart Batching**: Events are batched by size and time interval for optimal performance
10
+ - 馃敀 **Reliable Delivery**: Uses `sendBeacon` with `keepalive` to ensure events are sent on page unload
11
+ - 馃寪 **Framework Agnostic**: Works with any frontend framework (React, Vue, Angular, Vanilla JS)
12
+ - 馃搳 **Rich Context**: Automatically captures device, browser, and session metadata
13
+
14
+ ## Installation
15
+
16
+ ### npm
17
+
18
+ ```bash
19
+ npm install @agroideas/event-tracker-sdk
20
+ ```
21
+
22
+ ### pnpm
23
+
24
+ ```bash
25
+ pnpm add @agroideas/event-tracker-sdk
26
+ ```
27
+
28
+ ### yarn
29
+
30
+ ```bash
31
+ yarn add @agroideas/event-tracker-sdk
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ### ESM / TypeScript
37
+
38
+ ```typescript
39
+ import { tracker } from '@agroideas/event-tracker-sdk';
40
+
41
+ // Initialize with required configuration
42
+ tracker.init({
43
+ apiKey: 'your-api-key',
44
+ endpoint: 'https://your-api.com/events',
45
+ debug: true, // Optional: logs events to console
46
+ });
47
+
48
+ // Identify users when they log in
49
+ tracker.identify('user-123', 'John Doe');
50
+
51
+ // Events are now being tracked automatically!
52
+ ```
53
+
54
+ ### IIFE / Script Tag
55
+
56
+ ```html
57
+ <script src="https://cdn.your-domain.com/event-tracker.global.js"></script>
58
+ <script>
59
+ window.EventTracker.init({
60
+ apiKey: 'your-api-key',
61
+ endpoint: 'https://your-api.com/events',
62
+ });
63
+
64
+ window.EventTracker.identify('user-123', 'John Doe');
65
+ </script>
66
+ ```
67
+
68
+ ## API Reference
69
+
70
+ ### `tracker.init(config)`
71
+
72
+ Initializes the tracker with configuration options.
73
+
74
+ | Parameter | Type | Required | Default | Description |
75
+ | --------------- | --------- | -------- | ------- | ---------------------------------------- |
76
+ | `apiKey` | `string` | Yes | - | Your API key for authentication |
77
+ | `endpoint` | `string` | Yes | - | URL to send events to |
78
+ | `batchInterval` | `number` | No | `10000` | Milliseconds between batch sends |
79
+ | `maxBufferSize` | `number` | No | `15` | Maximum events before forced send |
80
+ | `debug` | `boolean` | No | `false` | Log events to console instead of sending |
81
+ | `userId` | `string` | No | - | Initial user ID |
82
+ | `userName` | `string` | No | - | Initial user name |
83
+
84
+ ```typescript
85
+ tracker.init({
86
+ apiKey: 'your-api-key',
87
+ endpoint: 'https://api.example.com/track',
88
+ batchInterval: 5000,
89
+ maxBufferSize: 20,
90
+ debug: true,
91
+ });
92
+ ```
93
+
94
+ ### `tracker.identify(userId, userName?)`
95
+
96
+ Identifies a user. Call this when a user logs in or when their information changes.
97
+
98
+ ```typescript
99
+ // After user logs in
100
+ tracker.identify('user-123', 'John Doe');
101
+
102
+ // Update user name
103
+ tracker.identify('user-123', 'Jane Doe');
104
+ ```
105
+
106
+ ### `tracker.trackEvent(eventType, data)`
107
+
108
+ Tracks a custom event.
109
+
110
+ ```typescript
111
+ // Track a custom event
112
+ tracker.trackEvent('button_click', {
113
+ buttonId: 'signup',
114
+ buttonText: 'Sign Up',
115
+ });
116
+
117
+ // Track form submission
118
+ tracker.trackEvent('form_submit', {
119
+ formId: 'contact-form',
120
+ formName: 'Contact Us',
121
+ });
122
+ ```
123
+
124
+ ### `tracker.flush()`
125
+
126
+ Immediately sends all pending events. Useful before critical actions like form submissions.
127
+
128
+ ```typescript
129
+ await tracker.flush();
130
+ ```
131
+
132
+ ### `tracker.destroy()`
133
+
134
+ Stops all tracking and clears event buffers. Call this when users log out.
135
+
136
+ ```typescript
137
+ tracker.destroy();
138
+ ```
139
+
140
+ ## Automatically Tracked Events
141
+
142
+ The SDK automatically captures the following events:
143
+
144
+ ### `page_view`
145
+
146
+ Fired on initial page load and when the URL changes (including SPA navigation).
147
+
148
+ **Data:**
149
+
150
+ - `path`: The current URL path
151
+
152
+ ### `page_leave`
153
+
154
+ Fired when the user leaves a page or closes the tab.
155
+
156
+ **Data:**
157
+
158
+ - `path`: The page path
159
+ - `duration`: Time spent on the page in seconds
160
+
161
+ ### `user_click`
162
+
163
+ Fired when the user clicks on interactive elements.
164
+
165
+ **Data:**
166
+
167
+ - `tagName`: HTML element tag (e.g., "BUTTON", "A")
168
+ - `id`: Element ID (if present)
169
+ - `classes`: CSS classes (if present)
170
+ - `text`: Inner text (truncated to 30 characters)
171
+ - `selector`: CSS selector path to the element
172
+
173
+ ## Context Data
174
+
175
+ All events include automatic context data:
176
+
177
+ | Field | Description |
178
+ | -------------- | -------------------------------------- |
179
+ | `sessionId` | Unique UUID stored in sessionStorage |
180
+ | `userId` | Current user ID (from `identify()`) |
181
+ | `userName` | Current user name (from `identify()`) |
182
+ | `url` | Full current URL |
183
+ | `referrer` | Document referrer |
184
+ | `screenSize` | Screen resolution (e.g., "1920x1080") |
185
+ | `viewportSize` | Viewport dimensions (e.g., "1280x720") |
186
+ | `deviceType` | Desktop, Mobile, or Tablet |
187
+ | `browser` | Browser name and version |
188
+ | `os` | Operating system |
189
+ | `language` | Browser language |
190
+ | `timestamp` | ISO 8601 timestamp |
191
+
192
+ ## Configuration Example
193
+
194
+ ### React Application
195
+
196
+ ```tsx
197
+ import { useEffect } from 'react';
198
+ import { tracker } from '@agroideas/event-tracker-sdk';
199
+
200
+ function App() {
201
+ useEffect(() => {
202
+ tracker.init({
203
+ apiKey: process.env.REACT_APP_TRACKER_API_KEY,
204
+ endpoint: process.env.REACT_APP_TRACKER_ENDPOINT,
205
+ });
206
+
207
+ return () => {
208
+ tracker.destroy();
209
+ };
210
+ }, []);
211
+
212
+ const handleLogin = () => {
213
+ // ... login logic
214
+ tracker.identify('user-123', 'John Doe');
215
+ };
216
+
217
+ const handleSubmit = async () => {
218
+ await tracker.flush();
219
+ // Submit form
220
+ };
221
+
222
+ return (
223
+ <button onClick={handleLogin}>Login</button>
224
+ <form onSubmit={handleSubmit}>
225
+ {/* form fields */}
226
+ </form>
227
+ );
228
+ }
229
+ ```
230
+
231
+ ### Vue 3 Application
232
+
233
+ ```typescript
234
+ import { tracker } from '@agroideas/event-tracker-sdk';
235
+ import { onMounted, onUnmounted } from 'vue';
236
+
237
+ export default {
238
+ setup() {
239
+ onMounted(() => {
240
+ tracker.init({
241
+ apiKey: import.meta.env.VITE_TRACKER_API_KEY,
242
+ endpoint: import.meta.env.VITE_TRACKER_ENDPOINT,
243
+ });
244
+ });
245
+
246
+ onUnmounted(() => {
247
+ tracker.destroy();
248
+ });
249
+
250
+ const login = (userId: string, userName: string) => {
251
+ tracker.identify(userId, userName);
252
+ };
253
+
254
+ return { login };
255
+ },
256
+ };
257
+ ```
258
+
259
+ ## Privacy Considerations
260
+
261
+ - **Input Fields**: The SDK automatically excludes password field values from click tracking
262
+ - **Sensitive Data**: No user data is stored locally; all data is sent directly to your endpoint
263
+ - **User Consent**: Implement your own consent management before initializing the tracker if required by GDPR/CCPA
264
+
265
+ ## Build Outputs
266
+
267
+ The SDK is compiled to multiple formats:
268
+
269
+ | Format | File | Usage |
270
+ | ---------- | ---------------------- | ------------------------------- |
271
+ | ES Module | `dist/index.mjs` | Modern browsers, bundlers |
272
+ | CommonJS | `dist/index.js` | Node.js, older bundlers |
273
+ | IIFE | `dist/index.global.js` | Direct script inclusion |
274
+ | TypeScript | `dist/index.d.ts` | IDE autocomplete, type checking |
275
+
276
+ ## Development
277
+
278
+ ```bash
279
+ # Install dependencies
280
+ pnpm install
281
+
282
+ # Start development mode (watch mode)
283
+ pnpm dev
284
+
285
+ # Run linter
286
+ pnpm lint
287
+
288
+ # Format code
289
+ pnpm format
290
+
291
+ # Build for production
292
+ pnpm build
293
+
294
+ # Run type checking
295
+ pnpm type-check
296
+ ```
297
+
298
+ ## Contributing
299
+
300
+ 1. Fork the repository
301
+ 2. Create a feature branch
302
+ 3. Make your changes
303
+ 4. Run `pnpm lint` and `pnpm build`
304
+ 5. Submit a pull request
305
+
306
+ ## License
307
+
308
+ MIT License - see LICENSE file for details
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Tipos compartidos para el Event Tracker SDK
3
+ */
4
+ /** Configuraci贸n del Tracker */
5
+ interface TrackerConfig {
6
+ apiKey: string;
7
+ endpoint: string;
8
+ userId?: string;
9
+ userName?: string;
10
+ debug?: string;
11
+ batchInterval?: number;
12
+ maxBufferSize?: number;
13
+ }
14
+ /** Metadatos de contexto incluidos en cada evento */
15
+ interface EventContext {
16
+ sessionId: string;
17
+ userId: string | null;
18
+ userName: string | null;
19
+ url: string;
20
+ referrer: string;
21
+ screenSize: string;
22
+ viewportSize: string;
23
+ deviceType: 'mobile' | 'desktop' | 'tablet' | 'unknown';
24
+ browser: string;
25
+ os: string;
26
+ language: string;
27
+ timestamp: string;
28
+ }
29
+ /** Eventos capturados por el SDK */
30
+ type EventType = 'page_view' | 'page_leave' | 'user_click';
31
+ /** Payload base de un evento */
32
+ interface BaseEvent {
33
+ eventType: EventType;
34
+ eventId: string;
35
+ context: EventContext;
36
+ }
37
+ /** Evento de vista de p谩gina */
38
+ interface PageViewEvent extends BaseEvent {
39
+ eventType: 'page_view';
40
+ data: {
41
+ pageTitle?: string;
42
+ path: string;
43
+ };
44
+ }
45
+ /** Evento de salida de p谩gina */
46
+ interface PageLeaveEvent extends BaseEvent {
47
+ eventType: 'page_leave';
48
+ data: {
49
+ duration: number;
50
+ path: string;
51
+ };
52
+ }
53
+ /** Evento de clic de usuario */
54
+ interface UserClickEvent extends BaseEvent {
55
+ eventType: 'user_click';
56
+ data: {
57
+ tagName: string;
58
+ id?: string;
59
+ className?: string;
60
+ title?: string;
61
+ text?: string;
62
+ selector: string;
63
+ };
64
+ }
65
+ /** Uni贸n de todos los tipos de eventos */
66
+ type TrackerEvent = PageViewEvent | PageLeaveEvent | UserClickEvent;
67
+
68
+ /**
69
+ * Tracker: Singleton principal que coordina observers y EventBuffer
70
+ */
71
+
72
+ declare class Tracker {
73
+ private static _instance;
74
+ private _eventBuffer;
75
+ private _clickObserver;
76
+ private _historyObserver;
77
+ private _userIdentity;
78
+ private _sessionId;
79
+ private _isInitialized;
80
+ private constructor();
81
+ /** Obtiene la instancia 煤nica del Tracker */
82
+ static getInstance(): Tracker;
83
+ /** Construye el contexto completo del evento */
84
+ private _buildContext;
85
+ /** Inicializa el tracker con la configuraci贸n */
86
+ init(config: TrackerConfig): void;
87
+ /** Identifica al usuario */
88
+ identify(userId: string, userName?: string): void;
89
+ /** Registra un evento */
90
+ trackEvent(event: TrackerEvent): void;
91
+ /** Crea un evento de page view */
92
+ trackPageView(): void;
93
+ /** Crea un evento de page leave */
94
+ trackPageLeave(duration: number): void;
95
+ /** Fuerza el env铆o de todos los eventos pendientes */
96
+ flush(): Promise<void>;
97
+ /** Verifica si el tracker est谩 inicializado */
98
+ isInitialized(): boolean;
99
+ /** Destruye el tracker */
100
+ destroy(): void;
101
+ }
102
+
103
+ /**
104
+ * Event Tracker SDK
105
+ *
106
+ * SDK ligero y agn贸stico al framework para tracking de comportamiento frontend.
107
+ *
108
+ * @example
109
+ * import { tracker } from '@agroideas/event-tracker-sdk';
110
+ *
111
+ * tracker.init({
112
+ * apiKey: 'tu-api-key',
113
+ * endpoint: 'https://tu-api.com/events'
114
+ * });
115
+ *
116
+ * // Identificar usuario
117
+ * tracker.identify('user-123', 'Juan P茅rez');
118
+ */
119
+
120
+ /** Instancia 煤nica exportada del Tracker */
121
+ declare const tracker: Tracker;
122
+ /**
123
+ * Inicializa el tracker con configuraci贸n requerida (apiKey y endpoint).
124
+ */
125
+ declare function init(config: TrackerConfig): void;
126
+ /** Identifica al usuario */
127
+ declare function identify(userId: string, userName?: string): void;
128
+ /** Fuerza el env铆o de eventos pendientes */
129
+ declare function flush(): Promise<void>;
130
+ /** Destruye el tracker */
131
+ declare function destroy(): void;
132
+
133
+ export { type TrackerConfig, destroy, flush, identify, init, tracker };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Tipos compartidos para el Event Tracker SDK
3
+ */
4
+ /** Configuraci贸n del Tracker */
5
+ interface TrackerConfig {
6
+ apiKey: string;
7
+ endpoint: string;
8
+ userId?: string;
9
+ userName?: string;
10
+ debug?: string;
11
+ batchInterval?: number;
12
+ maxBufferSize?: number;
13
+ }
14
+ /** Metadatos de contexto incluidos en cada evento */
15
+ interface EventContext {
16
+ sessionId: string;
17
+ userId: string | null;
18
+ userName: string | null;
19
+ url: string;
20
+ referrer: string;
21
+ screenSize: string;
22
+ viewportSize: string;
23
+ deviceType: 'mobile' | 'desktop' | 'tablet' | 'unknown';
24
+ browser: string;
25
+ os: string;
26
+ language: string;
27
+ timestamp: string;
28
+ }
29
+ /** Eventos capturados por el SDK */
30
+ type EventType = 'page_view' | 'page_leave' | 'user_click';
31
+ /** Payload base de un evento */
32
+ interface BaseEvent {
33
+ eventType: EventType;
34
+ eventId: string;
35
+ context: EventContext;
36
+ }
37
+ /** Evento de vista de p谩gina */
38
+ interface PageViewEvent extends BaseEvent {
39
+ eventType: 'page_view';
40
+ data: {
41
+ pageTitle?: string;
42
+ path: string;
43
+ };
44
+ }
45
+ /** Evento de salida de p谩gina */
46
+ interface PageLeaveEvent extends BaseEvent {
47
+ eventType: 'page_leave';
48
+ data: {
49
+ duration: number;
50
+ path: string;
51
+ };
52
+ }
53
+ /** Evento de clic de usuario */
54
+ interface UserClickEvent extends BaseEvent {
55
+ eventType: 'user_click';
56
+ data: {
57
+ tagName: string;
58
+ id?: string;
59
+ className?: string;
60
+ title?: string;
61
+ text?: string;
62
+ selector: string;
63
+ };
64
+ }
65
+ /** Uni贸n de todos los tipos de eventos */
66
+ type TrackerEvent = PageViewEvent | PageLeaveEvent | UserClickEvent;
67
+
68
+ /**
69
+ * Tracker: Singleton principal que coordina observers y EventBuffer
70
+ */
71
+
72
+ declare class Tracker {
73
+ private static _instance;
74
+ private _eventBuffer;
75
+ private _clickObserver;
76
+ private _historyObserver;
77
+ private _userIdentity;
78
+ private _sessionId;
79
+ private _isInitialized;
80
+ private constructor();
81
+ /** Obtiene la instancia 煤nica del Tracker */
82
+ static getInstance(): Tracker;
83
+ /** Construye el contexto completo del evento */
84
+ private _buildContext;
85
+ /** Inicializa el tracker con la configuraci贸n */
86
+ init(config: TrackerConfig): void;
87
+ /** Identifica al usuario */
88
+ identify(userId: string, userName?: string): void;
89
+ /** Registra un evento */
90
+ trackEvent(event: TrackerEvent): void;
91
+ /** Crea un evento de page view */
92
+ trackPageView(): void;
93
+ /** Crea un evento de page leave */
94
+ trackPageLeave(duration: number): void;
95
+ /** Fuerza el env铆o de todos los eventos pendientes */
96
+ flush(): Promise<void>;
97
+ /** Verifica si el tracker est谩 inicializado */
98
+ isInitialized(): boolean;
99
+ /** Destruye el tracker */
100
+ destroy(): void;
101
+ }
102
+
103
+ /**
104
+ * Event Tracker SDK
105
+ *
106
+ * SDK ligero y agn贸stico al framework para tracking de comportamiento frontend.
107
+ *
108
+ * @example
109
+ * import { tracker } from '@agroideas/event-tracker-sdk';
110
+ *
111
+ * tracker.init({
112
+ * apiKey: 'tu-api-key',
113
+ * endpoint: 'https://tu-api.com/events'
114
+ * });
115
+ *
116
+ * // Identificar usuario
117
+ * tracker.identify('user-123', 'Juan P茅rez');
118
+ */
119
+
120
+ /** Instancia 煤nica exportada del Tracker */
121
+ declare const tracker: Tracker;
122
+ /**
123
+ * Inicializa el tracker con configuraci贸n requerida (apiKey y endpoint).
124
+ */
125
+ declare function init(config: TrackerConfig): void;
126
+ /** Identifica al usuario */
127
+ declare function identify(userId: string, userName?: string): void;
128
+ /** Fuerza el env铆o de eventos pendientes */
129
+ declare function flush(): Promise<void>;
130
+ /** Destruye el tracker */
131
+ declare function destroy(): void;
132
+
133
+ export { type TrackerConfig, destroy, flush, identify, init, tracker };