@metodokorexmk/tracking 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,200 @@
1
+ # @metodokorexmk/tracking
2
+
3
+ Sistema de tracking reutilizable para landing pages con **Google Analytics 4**, **Google Tag Manager** y **video tracking multi-plataforma** (Wistia, Voomly, HTML5).
4
+
5
+ ## Características
6
+
7
+ - 🎯 **GA4 con ID multi-tenant**: Cada proyecto/colaborador puede tener su propio GA Tracking ID.
8
+ - 📊 **Integración GTM**: Envía eventos simultáneamente a GA4 y al `dataLayer` de GTM.
9
+ - 📹 **Video tracking**: Adaptadores para Wistia, Voomly e HTML5 nativo.
10
+ - 📜 **Scroll tracking**: Milestones automáticos (25%, 50%, 75%, 100%).
11
+ - 🖱️ **Click heatmap**: Captura coordenadas de clicks por sección.
12
+ - 📝 **Form auto-tracking**: Detecta automáticamente inicio, campos y envío de formularios.
13
+ - ⏱️ **Dwell time por sección**: Mide tiempo de permanencia con IntersectionObserver.
14
+ - ⚛️ **Hooks React opcionales**: Import separado que no afecta a proyectos sin React.
15
+ - 🔧 **Framework-agnostic**: Las capas core funcionan en cualquier entorno con DOM.
16
+
17
+ ## Instalación
18
+
19
+ ```bash
20
+ npm install @metodokorexmk/tracking react-ga4
21
+ # o
22
+ yarn add @metodokorexmk/tracking react-ga4
23
+ ```
24
+
25
+ > `react-ga4` es una peer dependency. Si usas los hooks React, también necesitas `react >= 18`.
26
+
27
+ ## Quick Start
28
+
29
+ ### Vanilla JavaScript / TypeScript
30
+
31
+ ```ts
32
+ import { initGA, trackPageView, trackEvent, createLandingTracker } from '@metodokorexmk/tracking'
33
+
34
+ // 1. Inicializar GA4
35
+ initGA({ trackingId: 'G-XXXXXXX' })
36
+
37
+ // 2. Trackear pageview
38
+ trackPageView('/mi-landing')
39
+
40
+ // 3. Crear tracker completo para la landing
41
+ const tracker = createLandingTracker({
42
+ pagePath: '/mi-landing',
43
+ pageName: 'Mi Landing Page',
44
+ gtmId: 'GTM-XXXXXXX', // Opcional
45
+ })
46
+
47
+ // 4. Trackear eventos manuales
48
+ trackEvent('CTA', 'click', 'Botón Principal')
49
+
50
+ // 5. Al desmontar:
51
+ tracker.destroy()
52
+ ```
53
+
54
+ ### React / Next.js
55
+
56
+ ```tsx
57
+ import { initGA } from '@metodokorexmk/tracking'
58
+ import { useLandingPageTracking, useVideoTracking } from '@metodokorexmk/tracking/react'
59
+
60
+ // Inicializar una vez en la app
61
+ initGA({ trackingId: 'G-XXXXXXX' })
62
+
63
+ function MiLanding() {
64
+ // Tracking automático de la landing
65
+ const tracker = useLandingPageTracking({
66
+ pagePath: '/mi-landing',
67
+ pageName: 'Mi Landing Page',
68
+ })
69
+
70
+ // Tracking de video HTML5
71
+ const videoRef = useRef<HTMLVideoElement>(null)
72
+ const { progress, isPlaying } = useVideoTracking({
73
+ videoId: 'hero-video',
74
+ videoElement: videoRef.current,
75
+ onComplete: () => console.log('Video completado'),
76
+ })
77
+
78
+ return (
79
+ <>
80
+ <video ref={videoRef} src="/video.mp4" />
81
+ <button onClick={() => tracker?.trackCTAClick('Unirse', 'hero')}>
82
+ Unirse
83
+ </button>
84
+ </>
85
+ )
86
+ }
87
+ ```
88
+
89
+ ## Documentación
90
+
91
+ | Doc | Descripción |
92
+ |---|---|
93
+ | [ARCHITECTURE.md](./docs/ARCHITECTURE.md) | Arquitectura de 4 capas, patrones de diseño, reglas de implementación y convenciones de código |
94
+ | [INTEGRATION-GUIDE.md](./docs/INTEGRATION-GUIDE.md) | Guía paso a paso de integración + tabla de migración desde KOREX-WEB-PROD |
95
+
96
+ ## Arquitectura
97
+
98
+ La librería usa una arquitectura de **4 capas** con dependencias unidireccionales:
99
+
100
+ ```
101
+ React Hooks (opcional) ← @metodokorexmk/tracking/react
102
+
103
+ Orchestrator ← LandingTracker (sesión completa)
104
+
105
+ Trackers ← video-tracker, events, wistia/voomly/html5 adapters
106
+
107
+ Core ← analytics (GA4), gtm, types
108
+ ```
109
+
110
+ > **Regla:** Las capas 1-3 son **framework-agnostic**. Solo la capa 4 importa React.
111
+
112
+ ### Patrones de diseño aplicados
113
+
114
+ | Patrón | Uso | Archivo |
115
+ |---|---|---|
116
+ | **Singleton** | Una instancia global de VideoTracker | `video-tracker.ts` |
117
+ | **Factory** | `createLandingTracker(config)` crea instancias | `landing-tracker.ts` |
118
+ | **Observer** | Callbacks `onUpdate()` en adaptadores de video | `wistia-adapter.ts`, `voomly-adapter.ts` |
119
+ | **Strategy** | `resolveTrackingId` inyecta lógica de resolución de GA ID | `analytics.ts` |
120
+ | **Dual Send** | Cada evento se envía por `gtag` + `ReactGA` simultáneamente | `analytics.ts` |
121
+
122
+ Ver [ARCHITECTURE.md](./docs/ARCHITECTURE.md) para detalles completos.
123
+
124
+ ## Convenciones de nombrado de archivos
125
+
126
+ | Tipo | Patrón | Ejemplo |
127
+ |---|---|---|
128
+ | Módulo core | `{nombre}.ts` | `analytics.ts`, `gtm.ts` |
129
+ | Adaptador video | `{plataforma}-adapter.ts` | `wistia-adapter.ts` |
130
+ | Clase tracker | `{nombre}-tracker.ts` | `video-tracker.ts` |
131
+ | Hook React | `use-{nombre}.ts` | `use-landing-tracking.ts` |
132
+ | Test unitario | `{módulo}.test.ts` | `analytics.test.ts` |
133
+
134
+ > Todos los archivos usan **kebab-case**. Exports usan `camelCase` (funciones) y `PascalCase` (clases/tipos).
135
+
136
+ ## API Pública
137
+
138
+ ### Core (`@metodokorexmk/tracking`)
139
+
140
+ | Export | Descripción |
141
+ |---|---|
142
+ | `initGA(config)` | Inicializa Google Analytics 4 |
143
+ | `trackEvent(cat, action, label?, value?, data?)` | Envía evento a GA4 |
144
+ | `trackPageView(path)` | Envía pageview |
145
+ | `captureUTMParams()` | Extrae UTM params de la URL |
146
+ | `captureUserIdFromURL()` | Lee `?user_id=` de la URL |
147
+ | `createLandingTracker(config)` | Crea orquestador de sesión completa |
148
+ | `trackWistiaByMediaId(id)` | Tracking de video Wistia |
149
+ | `trackVoomlyByEmbedId(id)` | Tracking de video Voomly |
150
+ | `trackHTML5Video(id, element)` | Tracking de `<video>` nativo |
151
+ | `trackCTAClick(btn, section)` | Evento CTA click |
152
+ | `trackFormSubmit(name, success)` | Evento formulario enviado |
153
+ | `trackConversion(type, value?)` | Evento de conversión |
154
+ | `pushToDataLayer(event, data)` | Push directo al GTM dataLayer |
155
+ | `injectGTMScript(gtmId)` | Inyecta script de GTM |
156
+
157
+ ### React Hooks (`@metodokorexmk/tracking/react`)
158
+
159
+ | Export | Descripción |
160
+ |---|---|
161
+ | `useLandingPageTracking(config)` | Hook orquestador de landing |
162
+ | `useVideoTracking(options)` | Hook para HTML5 video |
163
+ | `useWistiaVideoTracking(mediaId)` | Hook para Wistia video |
164
+
165
+ ## Calidad de código
166
+
167
+ La librería usa **ESLint (Airbnb)** + **Prettier** para mantener estándares de código consistentes:
168
+
169
+ ```bash
170
+ npm run lint # Verificar errores de ESLint
171
+ npm run lint:fix # Auto-corregir errores de ESLint
172
+ npm run format # Formatear código con Prettier
173
+ npm run format:check # Verificar formato sin modificar
174
+ ```
175
+
176
+ ### Config
177
+
178
+ | Herramienta | Config | Estilo |
179
+ |---|---|---|
180
+ | **ESLint** | `.eslintrc.json` | Airbnb base + TypeScript + Prettier |
181
+ | **Prettier** | `.prettierrc` | `singleQuote`, `semi`, `printWidth: 140`, `tabWidth: 2` |
182
+ | **TypeScript** | `tsconfig.json` | `strict: true`, ES2020, bundler module resolution |
183
+
184
+ ## Scripts
185
+
186
+ ```bash
187
+ npm run build # Build ESM + CJS + d.ts con tsup
188
+ npm test # Tests unitarios con Vitest
189
+ npm run test:coverage # Tests con cobertura
190
+ npm run typecheck # Verificación de tipos
191
+ npm run lint # Lint con ESLint Airbnb
192
+ npm run lint:fix # Lint + auto-fix
193
+ npm run format # Formatear con Prettier
194
+ npm run format:check # Verificar formato
195
+ ```
196
+
197
+ ## Licencia
198
+
199
+ MIT
200
+