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

@gnpdev/rpa-tools

v1.0.16

Published

Libreria para logs y screenshot de bots

Readme

@gnpdev/rpa-tools

Herramientas de automatización para bots RPA: logging estructurado con Pino, almacenamiento en MinIO con optimización de imágenes (WebP) y monitoreo de flags en base de datos para capturas de pantalla en tiempo real con Playwright.

Requisitos

  • Node.js v18+
  • pnpm (recomendado)
  • Instancia de MinIO activa.
  • Base de datos PostgreSQL.

Instalación

pnpm add @gnpdev/rpa-tools

Configuración Centralizada (Best Practice)

Crea un archivo en tu proyecto (ej. src/lib/rpa.js) para inicializar y exportar las herramientas. Esto asegura que uses la misma instancia en toda la aplicación.

// src/lib/rpa.js
import { createRpaTools } from '@gnpdev/rpa-tools';
import { Pool } from 'pg';
import * as dotenv from 'dotenv';
dotenv.config();

// 1. Configura tu pool de base de datos (usualmente ya lo tienes)
const pool = new Pool({
  connectionString: process.env.DATABASE_URL
});

// 2. Inicializa las herramientas
export const rpa = await createRpaTools({
  botId: process.env.RPA_BOT_ID,
  db: pool,
  minio: {
    endPoint: process.env.MINIO_ENDPOINT,
    port: parseInt(process.env.MINIO_PORT || '9000'),
    useSSL: process.env.MINIO_USE_SSL === 'true',
    accessKey: process.env.MINIO_ACCESS_KEY,
    secretKey: process.env.MINIO_SECRET_KEY,
    bucket: 'rpa-screenshots'
  },
  log: {
    level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
    pretty: process.env.NODE_ENV !== 'production',
  }
})

// 3. Exporta las herramientas
export const { logger, state, step } = rpa;

Uso en la Aplicación

1. Gestión de Pasos y Estado

La librería mantiene el rastro del paso actual del bot. Cada vez que llamas a step(), se actualiza el estado interno y se genera un log automático.

import { step, state } from './lib/rpa.js';

step('Inicio de Sesión');
console.log(state.currentStep); // 'Inicio de Sesión'

step('Extracción de Datos');
// Genera log: info { "step": "Extracción de Datos" } "Nuevo paso"

2. Logging Estructurado

Usa el logger preconfigurado que ya incluye el botId en cada entrada.

import { logger } from './lib/rpa.js';

logger.info('Procesando orden');

3. Gestión de Credenciales

Recupera de forma segura el usuario, password e idUsuario de una aplicación específica vinculada al bot.

import { rpa, logger } from './lib/rpa.js';

logger.info('Obtener credenciales');
const credentials = await rpa.getCredentials('Portal CRM');

if (credentials) {
  const { usuario, password, idUsuario } = credentials;
  // usar en el login de la web
}

4. Capturas de Pantalla bajo demanda (Playwright)

Activa el watcher pasando la instancia de page. El bot detectará cambios en la tabla de la DB para tomar screenshots automáticamente.

import { chromium } from 'playwright';
import { rpa } from './lib/rpa.js';

const browser = await chromium.launch();
const page = await browser.newPage();

// Inicia el monitoreo (polling cada 3s por defecto)
rpa.watchDebugFlag(page);


// Al terminar el proceso del bot
rpa.destroy(); 

// Sugerencia: limpiar al desconectar
browser.on('disconnected', () => rpa.destroy());

5. Captura Automática de Errores (Screenshot + Trace)

Captura el estado completo del bot cuando ocurre una excepción. captureError detecta automáticamente el paso actual definido con step().

import { chromium } from 'playwright';
import { rpa, logger, step } from './lib/rpa.js';

const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
const page    = await context.newPage();

// ── Activar tracing ANTES de que empiece la sesión ──────────────────────
await context.tracing.start({ screenshots: true, snapshots: true });

browser.on('disconnected', () => rpa.destroy());

try {
  step('Navegación');
  await page.goto('https://example.com');
  
  step('Login');
  await login(page);

  step('Procesar Datos');
  await page.click('#boton-inexistente');

} catch (err) {
  // Captura automática de evidencia (usa el paso 'Procesar Datos' automáticamente)
  const { errorId } = await rpa.captureError({ page, context, err });

  logger.error({ errorId }, 'Fallo crítico capturado');
  rpa.destroy();
  throw err;
}

Variables de Entorno Sugeridas

MINIO_ENDPOINT=localhost
MINIO_PORT=9000
MINIO_USE_SSL=false
MINIO_ACCESS_KEY=admin
MINIO_SECRET_KEY=password
MINIO_BUCKET=rpa-screenshots
DATABASE_URL=postgres://user:pass@localhost:5432/db