npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@imleosky/uconsumer-tracker

v1.1.0

Published

SDK de telemetría para registrar la actividad de los usuarios en la web.

Readme

uTracker SDK

uTracker es una librería (SDK) ligera, modular y eficiente en TypeScript diseñada para registrar de forma automática la actividad de los usuarios en una aplicación web o Single Page Application (SPA).

Ideal para integrarse en un ecosistema de analítica propio (como uConsumer) sin depender de terceros, asegurando la privacidad, propiedad de los datos y control total sobre qué y cuándo se envía.

🚀 Características

  • Registro de Clics: Captura las coordenadas exactas del clic (normalizadas entre 0 y 1 para hacerlas independientes de la resolución) y el selector CSS completo del elemento interactuado.
  • Registro de Scroll: Captura la profundidad de desplazamiento del usuario (Scroll Depth) de forma porcentual para entender qué partes de la página reciben más atención.
  • Integración con Dashboards en Vivo: Emite automáticamente eventos vía postMessage con las dimensiones exactas de la página (docHeight) para una sincronización perfecta cuando la web es renderizada dentro de un iframe (Ej. uInsights).
  • Navegación SPA: Detecta cambios de URL internamente al escuchar la API History (pushState, replaceState) sin recargar la página.
  • Tiempo Activo (Engagement Time): Mide el tiempo real que el usuario pasa interactuando con la pestaña usando la Page Visibility API y rastreando la inactividad.
  • Medición de Latencia: Detecta y registra el tiempo que tarda el DOM en reaccionar tras un clic usando MutationObserver.
  • Eficiencia de Red (Batching): Agrupa múltiples eventos en una "cola" (Queue) y los envía en lotes para minimizar la cantidad de peticiones de red.
  • Rendimiento UI: Utiliza requestIdleCallback para enviar los datos en momentos de inactividad del navegador, evitando bloquear el hilo principal (Main Thread).
  • Seguridad en la Salida: Si el usuario cierra la pestaña o cambia de app, hace uso de navigator.sendBeacon para garantizar el envío de los eventos pendientes sin cancelar la petición.

📦 Instalación

Vía NPM / Yarn / PNPM

Si utilizas un empaquetador (Webpack, Vite, Rollup) o un framework (React, Vue, Next.js):

npm install @uconsumer/tracker

Vía CDN

Si prefieres incrustarlo directamente en tu HTML, puedes usar el build global:

<script src="https://tu-cdn.com/utracker.global.js"></script>

💻 Uso en el Cliente (Frontend)

Inicializar el SDK es tan sencillo como llamar al método .init() en el punto de entrada principal de tu aplicación web (por ejemplo: main.ts, App.tsx, o dentro de la etiqueta <head>).

Ejemplo con Módulos ES (React, Vue, etc.)

import uTracker from '@uconsumer/tracker';

uTracker.init({
  endpoint: 'https://api.tu-dominio.com/v1/telemetry', // URL de tu servidor
  apiKey: 'tu_api_key_secreta_aqui',                   // Llave de autorización
  samplingRate: 1.0,                                   // 1.0 = Rastrear al 100% de usuarios
  batchSize: 15                                        // Enviar eventos cada 15 acciones
});

Ejemplo vía CDN (HTML)

<script>
  window.uTracker.init({
    endpoint: 'https://api.tu-dominio.com/v1/telemetry',
    apiKey: 'tu_api_key_secreta_aqui'
  });
</script>

Opciones de Configuración

| Opción | Tipo | Defecto | Descripción | | :--- | :--- | :--- | :--- | | endpoint | string | (Requerido) | URL a donde se enviarán los datos. | | apiKey | string | (Requerido) | Clave para autenticar el origen en el backend. | | samplingRate | number | 1.0 | Valor entre 0.0 y 1.0. Permite tomar una muestra estadística en lugar del tráfico total. | | batchSize | number | 10 | Cantidad de eventos a acumular antes de enviar una solicitud de red HTTP al backend. |


📡 Integración en el Servidor (Backend)

El SDK uTracker envía automáticamente un payload en formato JSON utilizando el método POST (vía sendBeacon o fetch).

Formato del Payload Recibido

{
  "apiKey": "tu_api_key_secreta_aqui",
  "events": [
    {
      "id": "abc123xyz456",
      "type": "click",
      "timestamp": 1700000100000,
      "url": "https://tienda.com/productos",
      "sessionId": "ses_987654",
      "device": "desktop",
      "data": {
        "x": 0.45,
        "y": 0.81,
        "docHeight": 2500,
        "selector": "body > div.app > main > button.btn-primary"
      }
    },
    {
      "id": "def456uvw789",
      "type": "scroll",
      "timestamp": 1700000160000,
      "url": "https://tienda.com/productos",
      "sessionId": "ses_987654",
      "device": "desktop",
      "data": {
        "depthPercent": 85
      }
    }
  ]
}

Procesamiento con @uconsumer/tracker/server

Para facilitar la integración, el SDK provee utilidades de backend listas para usar, incluyendo adaptadores para entornos de producción y desarrollo local.

import { 
  createTelemetryProcessor, 
  LocalJSONAdapter, 
  ConsoleAdapter 
} from '@uconsumer/tracker/server';

// 1. Elegir adaptador según el entorno
// En local, podemos guardar en un JSON o imprimir en consola.
// En producción, usaríamos un MongoAdapter (o similar).
const adapter = process.env.NODE_ENV === 'development'
  ? new LocalJSONAdapter('./utracker-db.json')
  : new ConsoleAdapter(); // Reemplazar por Base de Datos Real

// 2. Crear el procesador
const processTelemetry = createTelemetryProcessor({
  apiKey: 'tu_api_key_secreta_aqui',
  adapter
});

// 3. Consumirlo en tu framework (Ej. Next.js App Router: app/api/telemetry/route.ts)
export async function POST(request: Request) {
  const { apiKey, events } = await request.json();
  
  try {
    const result = await processTelemetry(apiKey, events);
    return Response.json(result);
  } catch (error: any) {
    return Response.json({ error: error.message }, { status: 401 });
  }
}

Adaptadores Disponibles

  • LocalJSONAdapter: Ideal para pruebas locales. Crea un archivo JSON físico y añade los eventos dinámicamente como si fuera una base de datos local (estilo SQLite).
  • ConsoleAdapter: Imprime los eventos directamente en la consola de tu terminal backend.
  • (Próximamente) MongoAdapter y PostgresAdapter para persistencia en entornos de producción.

🛠 Desarrollo

Para compilar el SDK para producción, generando las versiones CommonJS, ECMAScript Modules y el Bundle global IIFE (para CDN), utilizamos tsup.

# 1. Instalar dependencias
npm install

# 2. Compilar
npm run build

# 3. Compilar en modo observación (Watch)
npm run dev

Las versiones compiladas y sus correspondientes archivos de declaración de tipos (.d.ts) quedarán disponibles en el directorio /dist.