veo-sdk 0.1.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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Configuración de la autocaptura de interacciones del DOM.
3
+ */
4
+ interface VeoAutocaptureConfig {
5
+ /** Habilitar autocaptura. Default: true. */
6
+ enabled?: boolean;
7
+ /** Capturar clicks. Default: true. */
8
+ captureClicks?: boolean;
9
+ /** Capturar submits de formularios. Default: true. */
10
+ captureSubmits?: boolean;
11
+ /** Capturar changes en inputs/selects. Default: true. */
12
+ captureChanges?: boolean;
13
+ /** NO capturar value de inputs (privacidad). Default: true. */
14
+ maskAllInputs?: boolean;
15
+ /** NO capturar texto visible de elementos. Default: false. */
16
+ maskAllText?: boolean;
17
+ /** Selectores CSS a ignorar completamente (y sus descendientes). */
18
+ blockSelectors?: string[];
19
+ /** Throttle: no duplicar eventos del mismo elemento en N ms. Default: 100. */
20
+ throttleMs?: number;
21
+ /** Truncar textos a N caracteres. Default: 200. */
22
+ maxTextLength?: number;
23
+ /** Incluir classes/attrs/position en cada evento. Default: true. */
24
+ captureElementMetadata?: boolean;
25
+ /** Niveles de ancestros a capturar. Default: 5. Max: 10. */
26
+ captureAncestors?: number;
27
+ }
28
+ /**
29
+ * Configuración del cliente Veo.
30
+ */
31
+ interface VeoConfig {
32
+ /** API key pública del workspace (formato pk_xxx). */
33
+ apiKey: string;
34
+ /** URL base del backend de Veo. */
35
+ apiUrl: string;
36
+ /** Intervalo en ms para flush automático de la queue. Default: 5000. */
37
+ flushInterval?: number;
38
+ /** Tamaño máximo del batch antes de flush. Default: 20. */
39
+ flushBatchSize?: number;
40
+ /** Activar logs en consola. Default: false. */
41
+ debug?: boolean;
42
+ /** Backend de almacenamiento para IDs persistentes. Default: 'localStorage'. */
43
+ storage?: 'localStorage' | 'cookie' | 'memory';
44
+ /** Configuración de autocaptura. `false` la deshabilita por completo. */
45
+ autocapture?: VeoAutocaptureConfig | false;
46
+ /**
47
+ * Renderer de guías in-app. Opt-in: si es `true`, el SDK consulta
48
+ * `/v1/guides/resolve` en cada pageview y renderiza modales/banners/
49
+ * tooltips. Default: `false`.
50
+ */
51
+ guides?: boolean;
52
+ }
53
+ /**
54
+ * Información del end user (usuario final).
55
+ */
56
+ interface VeoVisitor {
57
+ id: string;
58
+ anonymousId?: string;
59
+ traits?: Record<string, unknown>;
60
+ }
61
+ /**
62
+ * Información de la organization (B2B SaaS).
63
+ */
64
+ interface VeoOrganization {
65
+ id: string;
66
+ attributes?: Record<string, unknown>;
67
+ }
68
+ /**
69
+ * Plugin del SDK. Permite extender funcionalidad.
70
+ */
71
+ interface VeoPlugin {
72
+ name: string;
73
+ install(client: VeoClient): void;
74
+ destroy?(): void;
75
+ }
76
+ /**
77
+ * Eventos internos que el Client emite para que los plugins se enganchen
78
+ * (e.g. el plugin de guides escucha `pageview` para chequear qué guías
79
+ * debe mostrar). No tienen nada que ver con los eventos analíticos que
80
+ * llegan al backend.
81
+ *
82
+ * El payload incluye `sessionId` y `endUserId` para evitar que los plugins
83
+ * tengan que consultar al client en cada disparo y para garantizar que
84
+ * todos los listeners ven el mismo snapshot del momento del evento.
85
+ */
86
+ interface VeoClientEvents {
87
+ pageview: {
88
+ url: string;
89
+ path: string;
90
+ sessionId: string;
91
+ endUserId: string | null;
92
+ };
93
+ identify: {
94
+ endUserId: string;
95
+ sessionId: string;
96
+ };
97
+ }
98
+ type VeoClientEventName = keyof VeoClientEvents;
99
+ type VeoClientEventListener<E extends VeoClientEventName> = (payload: VeoClientEvents[E]) => void;
100
+ /**
101
+ * Forward declaration del client (implementación viene en core/client.ts).
102
+ */
103
+ interface VeoClient {
104
+ identify(payload: {
105
+ visitor: VeoVisitor;
106
+ organization?: VeoOrganization;
107
+ }): void;
108
+ track(name: string, properties?: Record<string, unknown>): void;
109
+ pageview(path?: string): void;
110
+ reset(): void;
111
+ flush(): Promise<void>;
112
+ use(plugin: VeoPlugin): VeoClient;
113
+ /** Suscribirse a eventos internos del Client. Devuelve el unsubscribe. */
114
+ on<E extends VeoClientEventName>(event: E, listener: VeoClientEventListener<E>): () => void;
115
+ /**
116
+ * @internal Consumido por plugins (e.g. guides) que necesitan el ID
117
+ * actual al momento de hacer un POST. NO es API estable para usuarios.
118
+ */
119
+ getEndUserId(): string | null;
120
+ /** @internal Consumido por plugins. NO es API estable para usuarios. */
121
+ getSessionId(): string;
122
+ }
123
+
124
+ /**
125
+ * Tipos del contrato HTTP entre el SDK y el backend.
126
+ * Versión 1.
127
+ *
128
+ * IMPORTANTE: Si cambias algo aquí, debes actualizar también:
129
+ * - veo-backend/src/modules/identity/dto/*.dto.ts
130
+ * - veo-backend/src/modules/ingest/dto/*.dto.ts
131
+ * - CONTRACT.md
132
+ */
133
+ declare const SDK_VERSION = "0.0.1";
134
+
135
+ /**
136
+ * Cliente principal del SDK. Expone la API pública (`identify`, `track`,
137
+ * `pageview`, `reset`, `flush`, `use`). Toda la API salvo `flush()` es síncrona:
138
+ * los eventos se encolan y la llamada retorna de inmediato.
139
+ */
140
+ declare class Client implements VeoClient {
141
+ private readonly config;
142
+ private readonly transport;
143
+ private readonly storage;
144
+ private readonly session;
145
+ private readonly queue;
146
+ private readonly plugins;
147
+ private currentOrganizationId;
148
+ private readonly listeners;
149
+ constructor(config: VeoConfig);
150
+ identify(payload: {
151
+ visitor: VeoVisitor;
152
+ organization?: VeoOrganization;
153
+ }): void;
154
+ track(name: string, properties?: Record<string, unknown>): void;
155
+ pageview(path?: string): void;
156
+ reset(): void;
157
+ flush(): Promise<void>;
158
+ use(plugin: VeoPlugin): VeoClient;
159
+ getEndUserId(): string | null;
160
+ getSessionId(): string;
161
+ /**
162
+ * Suscribe `listener` a `event`. Devuelve una función para desuscribir.
163
+ * Los errores en listeners se logean en debug mode pero NO se propagan
164
+ * (un plugin no debe poder romper a otro).
165
+ */
166
+ on<E extends VeoClientEventName>(event: E, listener: VeoClientEventListener<E>): () => void;
167
+ private emit;
168
+ /**
169
+ * Construye el evento completo y lo agrega a la queue. Omite los campos
170
+ * opcionales no definidos (exigido por `exactOptionalPropertyTypes`).
171
+ * @internal
172
+ */
173
+ private enqueue;
174
+ private setupUnloadHandlers;
175
+ }
176
+
177
+ /**
178
+ * Plugin de autocaptura de eventos del DOM.
179
+ * Captura clicks, submits y changes automáticamente y los emite como
180
+ * eventos `track('$autocapture', …)` por la Queue del cliente.
181
+ */
182
+ declare function autocapturePlugin(config?: VeoAutocaptureConfig): VeoPlugin;
183
+
184
+ interface GuidesPluginConfig {
185
+ apiUrl: string;
186
+ apiKey: string;
187
+ debug?: boolean;
188
+ }
189
+ /**
190
+ * Plugin que renderiza guías in-app (modal/banner/tooltip) consultando
191
+ * `GET /v1/guides/resolve` y registra las interacciones en
192
+ * `POST /v1/guides/:id/interactions` vía queue dedicada con retry y
193
+ * sendBeacon en pagehide.
194
+ *
195
+ * Opt-in: `init({ ..., guides: true })`. El plugin escucha
196
+ * `pageview` e `identify` del client; el payload del evento ya trae
197
+ * `sessionId` y `endUserId` para que no necesitemos consultar al
198
+ * client en cada disparo.
199
+ *
200
+ * Frequency híbrida: el backend filtra autoritariamente; el cache
201
+ * local (`GuideFrequencyCache`) solo previene el flash visual cuando
202
+ * la interaction aún no se persistió.
203
+ */
204
+ declare function guidesPlugin(config: GuidesPluginConfig): VeoPlugin;
205
+
206
+ /**
207
+ * Helper de identidad para definir un plugin con inferencia de tipos.
208
+ * No transforma nada; mejora la ergonomía y deja un punto de extensión futuro.
209
+ */
210
+ declare function definePlugin(plugin: VeoPlugin): VeoPlugin;
211
+
212
+ /**
213
+ * Plugin que auto-emite `pageview` en cambios de ruta de una SPA.
214
+ * Cubre `history.pushState`, `history.replaceState`, `popstate` y `hashchange`.
215
+ */
216
+ declare function spaRouterPlugin(): VeoPlugin;
217
+
218
+ /**
219
+ * Inicializa el SDK de Veo. Instala por defecto el plugin de SPA router
220
+ * (auto-pageview) y, en browser, expone la instancia en `window.veo` drenando
221
+ * la cola del snippet stub si existe.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * import { init } from '@veo/sdk';
226
+ *
227
+ * const veo = init({
228
+ * apiKey: 'pk_xxx',
229
+ * apiUrl: 'https://api.veo.io'
230
+ * });
231
+ *
232
+ * veo.identify({ visitor: { id: 'user_123' } });
233
+ * veo.track('button_clicked');
234
+ * ```
235
+ */
236
+ declare function init(config: VeoConfig): VeoClient;
237
+
238
+ export { Client, SDK_VERSION, type VeoAutocaptureConfig, type VeoClient, type VeoConfig, type VeoOrganization, type VeoPlugin, type VeoVisitor, autocapturePlugin, definePlugin, guidesPlugin, init, spaRouterPlugin };
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Configuración de la autocaptura de interacciones del DOM.
3
+ */
4
+ interface VeoAutocaptureConfig {
5
+ /** Habilitar autocaptura. Default: true. */
6
+ enabled?: boolean;
7
+ /** Capturar clicks. Default: true. */
8
+ captureClicks?: boolean;
9
+ /** Capturar submits de formularios. Default: true. */
10
+ captureSubmits?: boolean;
11
+ /** Capturar changes en inputs/selects. Default: true. */
12
+ captureChanges?: boolean;
13
+ /** NO capturar value de inputs (privacidad). Default: true. */
14
+ maskAllInputs?: boolean;
15
+ /** NO capturar texto visible de elementos. Default: false. */
16
+ maskAllText?: boolean;
17
+ /** Selectores CSS a ignorar completamente (y sus descendientes). */
18
+ blockSelectors?: string[];
19
+ /** Throttle: no duplicar eventos del mismo elemento en N ms. Default: 100. */
20
+ throttleMs?: number;
21
+ /** Truncar textos a N caracteres. Default: 200. */
22
+ maxTextLength?: number;
23
+ /** Incluir classes/attrs/position en cada evento. Default: true. */
24
+ captureElementMetadata?: boolean;
25
+ /** Niveles de ancestros a capturar. Default: 5. Max: 10. */
26
+ captureAncestors?: number;
27
+ }
28
+ /**
29
+ * Configuración del cliente Veo.
30
+ */
31
+ interface VeoConfig {
32
+ /** API key pública del workspace (formato pk_xxx). */
33
+ apiKey: string;
34
+ /** URL base del backend de Veo. */
35
+ apiUrl: string;
36
+ /** Intervalo en ms para flush automático de la queue. Default: 5000. */
37
+ flushInterval?: number;
38
+ /** Tamaño máximo del batch antes de flush. Default: 20. */
39
+ flushBatchSize?: number;
40
+ /** Activar logs en consola. Default: false. */
41
+ debug?: boolean;
42
+ /** Backend de almacenamiento para IDs persistentes. Default: 'localStorage'. */
43
+ storage?: 'localStorage' | 'cookie' | 'memory';
44
+ /** Configuración de autocaptura. `false` la deshabilita por completo. */
45
+ autocapture?: VeoAutocaptureConfig | false;
46
+ /**
47
+ * Renderer de guías in-app. Opt-in: si es `true`, el SDK consulta
48
+ * `/v1/guides/resolve` en cada pageview y renderiza modales/banners/
49
+ * tooltips. Default: `false`.
50
+ */
51
+ guides?: boolean;
52
+ }
53
+ /**
54
+ * Información del end user (usuario final).
55
+ */
56
+ interface VeoVisitor {
57
+ id: string;
58
+ anonymousId?: string;
59
+ traits?: Record<string, unknown>;
60
+ }
61
+ /**
62
+ * Información de la organization (B2B SaaS).
63
+ */
64
+ interface VeoOrganization {
65
+ id: string;
66
+ attributes?: Record<string, unknown>;
67
+ }
68
+ /**
69
+ * Plugin del SDK. Permite extender funcionalidad.
70
+ */
71
+ interface VeoPlugin {
72
+ name: string;
73
+ install(client: VeoClient): void;
74
+ destroy?(): void;
75
+ }
76
+ /**
77
+ * Eventos internos que el Client emite para que los plugins se enganchen
78
+ * (e.g. el plugin de guides escucha `pageview` para chequear qué guías
79
+ * debe mostrar). No tienen nada que ver con los eventos analíticos que
80
+ * llegan al backend.
81
+ *
82
+ * El payload incluye `sessionId` y `endUserId` para evitar que los plugins
83
+ * tengan que consultar al client en cada disparo y para garantizar que
84
+ * todos los listeners ven el mismo snapshot del momento del evento.
85
+ */
86
+ interface VeoClientEvents {
87
+ pageview: {
88
+ url: string;
89
+ path: string;
90
+ sessionId: string;
91
+ endUserId: string | null;
92
+ };
93
+ identify: {
94
+ endUserId: string;
95
+ sessionId: string;
96
+ };
97
+ }
98
+ type VeoClientEventName = keyof VeoClientEvents;
99
+ type VeoClientEventListener<E extends VeoClientEventName> = (payload: VeoClientEvents[E]) => void;
100
+ /**
101
+ * Forward declaration del client (implementación viene en core/client.ts).
102
+ */
103
+ interface VeoClient {
104
+ identify(payload: {
105
+ visitor: VeoVisitor;
106
+ organization?: VeoOrganization;
107
+ }): void;
108
+ track(name: string, properties?: Record<string, unknown>): void;
109
+ pageview(path?: string): void;
110
+ reset(): void;
111
+ flush(): Promise<void>;
112
+ use(plugin: VeoPlugin): VeoClient;
113
+ /** Suscribirse a eventos internos del Client. Devuelve el unsubscribe. */
114
+ on<E extends VeoClientEventName>(event: E, listener: VeoClientEventListener<E>): () => void;
115
+ /**
116
+ * @internal Consumido por plugins (e.g. guides) que necesitan el ID
117
+ * actual al momento de hacer un POST. NO es API estable para usuarios.
118
+ */
119
+ getEndUserId(): string | null;
120
+ /** @internal Consumido por plugins. NO es API estable para usuarios. */
121
+ getSessionId(): string;
122
+ }
123
+
124
+ /**
125
+ * Tipos del contrato HTTP entre el SDK y el backend.
126
+ * Versión 1.
127
+ *
128
+ * IMPORTANTE: Si cambias algo aquí, debes actualizar también:
129
+ * - veo-backend/src/modules/identity/dto/*.dto.ts
130
+ * - veo-backend/src/modules/ingest/dto/*.dto.ts
131
+ * - CONTRACT.md
132
+ */
133
+ declare const SDK_VERSION = "0.0.1";
134
+
135
+ /**
136
+ * Cliente principal del SDK. Expone la API pública (`identify`, `track`,
137
+ * `pageview`, `reset`, `flush`, `use`). Toda la API salvo `flush()` es síncrona:
138
+ * los eventos se encolan y la llamada retorna de inmediato.
139
+ */
140
+ declare class Client implements VeoClient {
141
+ private readonly config;
142
+ private readonly transport;
143
+ private readonly storage;
144
+ private readonly session;
145
+ private readonly queue;
146
+ private readonly plugins;
147
+ private currentOrganizationId;
148
+ private readonly listeners;
149
+ constructor(config: VeoConfig);
150
+ identify(payload: {
151
+ visitor: VeoVisitor;
152
+ organization?: VeoOrganization;
153
+ }): void;
154
+ track(name: string, properties?: Record<string, unknown>): void;
155
+ pageview(path?: string): void;
156
+ reset(): void;
157
+ flush(): Promise<void>;
158
+ use(plugin: VeoPlugin): VeoClient;
159
+ getEndUserId(): string | null;
160
+ getSessionId(): string;
161
+ /**
162
+ * Suscribe `listener` a `event`. Devuelve una función para desuscribir.
163
+ * Los errores en listeners se logean en debug mode pero NO se propagan
164
+ * (un plugin no debe poder romper a otro).
165
+ */
166
+ on<E extends VeoClientEventName>(event: E, listener: VeoClientEventListener<E>): () => void;
167
+ private emit;
168
+ /**
169
+ * Construye el evento completo y lo agrega a la queue. Omite los campos
170
+ * opcionales no definidos (exigido por `exactOptionalPropertyTypes`).
171
+ * @internal
172
+ */
173
+ private enqueue;
174
+ private setupUnloadHandlers;
175
+ }
176
+
177
+ /**
178
+ * Plugin de autocaptura de eventos del DOM.
179
+ * Captura clicks, submits y changes automáticamente y los emite como
180
+ * eventos `track('$autocapture', …)` por la Queue del cliente.
181
+ */
182
+ declare function autocapturePlugin(config?: VeoAutocaptureConfig): VeoPlugin;
183
+
184
+ interface GuidesPluginConfig {
185
+ apiUrl: string;
186
+ apiKey: string;
187
+ debug?: boolean;
188
+ }
189
+ /**
190
+ * Plugin que renderiza guías in-app (modal/banner/tooltip) consultando
191
+ * `GET /v1/guides/resolve` y registra las interacciones en
192
+ * `POST /v1/guides/:id/interactions` vía queue dedicada con retry y
193
+ * sendBeacon en pagehide.
194
+ *
195
+ * Opt-in: `init({ ..., guides: true })`. El plugin escucha
196
+ * `pageview` e `identify` del client; el payload del evento ya trae
197
+ * `sessionId` y `endUserId` para que no necesitemos consultar al
198
+ * client en cada disparo.
199
+ *
200
+ * Frequency híbrida: el backend filtra autoritariamente; el cache
201
+ * local (`GuideFrequencyCache`) solo previene el flash visual cuando
202
+ * la interaction aún no se persistió.
203
+ */
204
+ declare function guidesPlugin(config: GuidesPluginConfig): VeoPlugin;
205
+
206
+ /**
207
+ * Helper de identidad para definir un plugin con inferencia de tipos.
208
+ * No transforma nada; mejora la ergonomía y deja un punto de extensión futuro.
209
+ */
210
+ declare function definePlugin(plugin: VeoPlugin): VeoPlugin;
211
+
212
+ /**
213
+ * Plugin que auto-emite `pageview` en cambios de ruta de una SPA.
214
+ * Cubre `history.pushState`, `history.replaceState`, `popstate` y `hashchange`.
215
+ */
216
+ declare function spaRouterPlugin(): VeoPlugin;
217
+
218
+ /**
219
+ * Inicializa el SDK de Veo. Instala por defecto el plugin de SPA router
220
+ * (auto-pageview) y, en browser, expone la instancia en `window.veo` drenando
221
+ * la cola del snippet stub si existe.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * import { init } from '@veo/sdk';
226
+ *
227
+ * const veo = init({
228
+ * apiKey: 'pk_xxx',
229
+ * apiUrl: 'https://api.veo.io'
230
+ * });
231
+ *
232
+ * veo.identify({ visitor: { id: 'user_123' } });
233
+ * veo.track('button_clicked');
234
+ * ```
235
+ */
236
+ declare function init(config: VeoConfig): VeoClient;
237
+
238
+ export { Client, SDK_VERSION, type VeoAutocaptureConfig, type VeoClient, type VeoConfig, type VeoOrganization, type VeoPlugin, type VeoVisitor, autocapturePlugin, definePlugin, guidesPlugin, init, spaRouterPlugin };