@gnpdev/rpa-tools 1.0.0 → 1.0.4

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 CHANGED
@@ -1,93 +1,105 @@
1
- # @gnpdev/rpa-tools
2
-
3
- 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**.
4
-
5
- ## Requisitos
6
-
7
- - **Node.js** v18+
8
- - **pnpm** (recomendado)
9
- - Instancia de **MinIO** activa.
10
- - Base de datos **PostgreSQL**.
11
-
12
- ## Instalación
13
-
14
- ```bash
15
- pnpm add @gnpdev/rpa-tools
16
- ```
17
-
18
- ## Configuración Centralizada (Best Practice)
19
-
20
- 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.
21
-
22
- ```javascript
23
- // src/lib/rpa.js
24
- const { createRpaTools } = require('@gnpdev/rpa-tools');
25
- const { Pool } = require('pg');
26
-
27
- // 1. Configura tu pool de base de datos (usualmente ya lo tienes)
28
- const pool = new Pool({
29
- connectionString: process.env.DATABASE_URL
30
- });
31
-
32
- // 2. Inicializa las herramientas
33
- async function initRpa() {
34
- const rpa = await createRpaTools({
35
- botId: 'BOT-VENTAS-01',
36
- db: pool,
37
- minio: {
38
- endPoint: process.env.MINIO_ENDPOINT,
39
- port: parseInt(process.env.MINIO_PORT || '9000'),
40
- useSSL: process.env.MINIO_USE_SSL === 'true',
41
- accessKey: process.env.MINIO_ACCESS_KEY,
42
- secretKey: process.env.MINIO_SECRET_KEY,
43
- bucket: 'rpa-screenshots'
44
- },
45
- log: {
46
- level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
47
- pretty: process.env.NODE_ENV === 'development'
48
- }
49
- });
50
- return rpa;
51
- }
52
-
53
- module.exports = initRpa;
54
- ```
55
-
56
- ## Uso en la Aplicación
57
-
58
- ### 1. Logging Estructurado
59
- Usa el logger preconfigurado que ya incluye el `botId` en cada entrada.
60
-
61
- ```javascript
62
- const rpa = await initRpa();
63
- rpa.logger.info({ orderId: '123' }, 'Procesando orden');
64
- ```
65
-
66
- ### 2. Capturas de Pantalla bajo demanda (Playwright)
67
- Activa el watcher pasando la instancia de `page`. El bot detectará cambios en la tabla de la DB para tomar screenshots automáticamente.
68
-
69
- ```javascript
70
- const { chromium } = require('playwright');
71
- const rpa = await initRpa();
72
-
73
- const browser = await chromium.launch();
74
- const page = await browser.newPage();
75
-
76
- // Inicia el monitoreo (polling cada 3s por defecto)
77
- rpa.watchDebugFlag(page);
78
-
79
- // Al terminar el proceso del bot
80
- // rpa.destroy();
81
- ```
82
-
83
- ## Variables de Entorno Sugeridas
84
-
85
- ```env
86
- MINIO_ENDPOINT=localhost
87
- MINIO_PORT=9000
88
- MINIO_USE_SSL=false
89
- MINIO_ACCESS_KEY=admin
90
- MINIO_SECRET_KEY=password
91
- MINIO_BUCKET=rpa-screenshots
92
- DATABASE_URL=postgres://user:pass@localhost:5432/db
93
- ```
1
+ # @gnpdev/rpa-tools
2
+
3
+ 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**.
4
+
5
+ ## Requisitos
6
+
7
+ - **Node.js** v18+
8
+ - **pnpm** (recomendado)
9
+ - Instancia de **MinIO** activa.
10
+ - Base de datos **PostgreSQL**.
11
+
12
+ ## Instalación
13
+
14
+ ```bash
15
+ pnpm add @gnpdev/rpa-tools
16
+ ```
17
+
18
+ ## Configuración Centralizada (Best Practice)
19
+
20
+ 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.
21
+
22
+ ```javascript
23
+ // src/lib/rpa.js
24
+ const { createRpaTools } = require('@gnpdev/rpa-tools');
25
+ const { Pool } = require('pg');
26
+
27
+ // 1. Configura tu pool de base de datos (usualmente ya lo tienes)
28
+ const pool = new Pool({
29
+ connectionString: process.env.DATABASE_URL
30
+ });
31
+
32
+ // 2. Inicializa las herramientas
33
+ async function initRpa() {
34
+ const rpa = await createRpaTools({
35
+ botId: 'BOT-VENTAS-01',
36
+ db: pool,
37
+ minio: {
38
+ endPoint: process.env.MINIO_ENDPOINT,
39
+ port: parseInt(process.env.MINIO_PORT || '9000'),
40
+ useSSL: process.env.MINIO_USE_SSL === 'true',
41
+ accessKey: process.env.MINIO_ACCESS_KEY,
42
+ secretKey: process.env.MINIO_SECRET_KEY,
43
+ bucket: 'rpa-screenshots'
44
+ },
45
+ log: {
46
+ level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
47
+ pretty: process.env.NODE_ENV === 'development'
48
+ }
49
+ });
50
+ return rpa;
51
+ }
52
+
53
+ module.exports = initRpa;
54
+ ```
55
+
56
+ ## Uso en la Aplicación
57
+
58
+ ### 1. Logging Estructurado
59
+ Usa el logger preconfigurado que ya incluye el `botId` en cada entrada.
60
+
61
+ ```javascript
62
+ const rpa = await initRpa();
63
+ rpa.logger.info({ orderId: '123' }, 'Procesando orden');
64
+ ```
65
+
66
+ ### 2. Gestión de Credenciales
67
+ Recupera de forma segura el `usuario`, `password` e `idUsuario` de una aplicación específica vinculada al bot.
68
+
69
+ ```javascript
70
+ const credentials = await rpa.getCredentials('Portal CRM');
71
+
72
+ if (credentials) {
73
+ const { usuario, password, idUsuario } = credentials;
74
+ // usar en el login de la web
75
+ }
76
+ ```
77
+
78
+ ### 3. Capturas de Pantalla bajo demanda (Playwright)
79
+ Activa el watcher pasando la instancia de `page`. El bot detectará cambios en la tabla de la DB para tomar screenshots automáticamente.
80
+
81
+ ```javascript
82
+ const { chromium } = require('playwright');
83
+ const rpa = await initRpa();
84
+
85
+ const browser = await chromium.launch();
86
+ const page = await browser.newPage();
87
+
88
+ // Inicia el monitoreo (polling cada 3s por defecto)
89
+ rpa.watchDebugFlag(page);
90
+
91
+ // Al terminar el proceso del bot
92
+ // rpa.destroy();
93
+ ```
94
+
95
+ ## Variables de Entorno Sugeridas
96
+
97
+ ```env
98
+ MINIO_ENDPOINT=localhost
99
+ MINIO_PORT=9000
100
+ MINIO_USE_SSL=false
101
+ MINIO_ACCESS_KEY=admin
102
+ MINIO_SECRET_KEY=password
103
+ MINIO_BUCKET=rpa-screenshots
104
+ DATABASE_URL=postgres://user:pass@localhost:5432/db
105
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gnpdev/rpa-tools",
3
- "version": "1.0.0",
3
+ "version": "1.0.4",
4
4
  "description": "Libreria para logs y screenshot de bots",
5
5
  "author": "Sergio Antonio Trujillo del Valle",
6
6
  "main": "src/index.js",
@@ -22,6 +22,15 @@
22
22
  "sharp": "^0.34.5"
23
23
  },
24
24
  "devDependencies": {
25
- "pino-pretty": "^13.1.3"
25
+ "@commitlint/cli": "^20.5.0",
26
+ "@commitlint/config-conventional": "^20.5.0",
27
+ "@release-it/conventional-changelog": "^10.0.6",
28
+ "husky": "^9.1.7",
29
+ "pino-pretty": "^13.1.3",
30
+ "release-it": "^19.2.4"
31
+ },
32
+ "scripts": {
33
+ "prepare": "husky",
34
+ "release": "release-it"
26
35
  }
27
36
  }
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Gestor de credenciales de aplicaciones para bots.
5
+ */
6
+ class CredentialManager {
7
+ /**
8
+ * @param {object} params
9
+ * @param {import('pg').Pool} params.pool - Pool de pg
10
+ * @param {string} params.botId - UUID del bot
11
+ */
12
+ constructor({ pool, botId }) {
13
+ this.pool = pool;
14
+ this.botId = botId;
15
+ }
16
+
17
+ /**
18
+ * Obtiene las credenciales de una aplicación.
19
+ * @param {string} nombre - Nombre de la aplicación
20
+ * @returns {Promise<{usuario: string, password: string, idUsuario: string}|null>}
21
+ */
22
+ async getAppCredentials(nombre) {
23
+ const { rows } = await this.pool.query(
24
+ `SELECT usuario, password, "idUsuario"
25
+ FROM bots.tb_aplicaciones_bots
26
+ WHERE nombre = $1 AND bot_id = $2
27
+ LIMIT 1`,
28
+ [nombre, this.botId]
29
+ );
30
+
31
+ return rows.length > 0 ? rows[0] : null;
32
+ }
33
+ }
34
+
35
+ module.exports = { CredentialManager };
package/src/index.js CHANGED
@@ -1,86 +1,56 @@
1
- 'use strict';
2
- const { createLogger } = require('./logger');
3
- const { createMinioClient, ensureBucket } = require('./storage');
4
- const { ScreenshotWatcher } = require('./watcher');
5
-
6
- /**
7
- * Factory principal de la librería.
8
- *
9
- * @param {object} opts
10
- * @param {string} opts.botId - identificador único del bot
11
- * @param {import('pg').Pool} opts.db - pool de pg ya conectado
12
- * @param {object} opts.minio - config de MinIO (ver abajo)
13
- * @param {string} opts.minio.endPoint
14
- * @param {number} [opts.minio.port=9000]
15
- * @param {boolean} [opts.minio.useSSL=false]
16
- * @param {string} opts.minio.accessKey
17
- * @param {string} opts.minio.secretKey
18
- * @param {string} [opts.minio.bucket='rpa-screenshots']
19
- * @param {object} [opts.log] - opciones de Pino
20
- * @param {string} [opts.log.level='info']
21
- * @param {boolean} [opts.log.pretty=false]
22
- *
23
- * @returns {{ logger, watchDebugFlag, destroy }}
24
- */
25
- async function createRpaTools(opts = {}) {
26
- const {
27
- botId = process.env.RPA_BOT_ID,
28
- log: logCfg = {},
29
- db,
30
- minio: minioCfg,
31
- } = opts;
32
-
33
- // Leer minio desde env si no se pasó config
34
- const minio = minioCfg ?? {
35
- endPoint: process.env.MINIO_ENDPOINT,
36
- port: Number(process.env.MINIO_PORT) || 9000,
37
- useSSL: process.env.MINIO_USE_SSL === 'true',
38
- accessKey: process.env.MINIO_ACCESS_KEY,
39
- secretKey: process.env.MINIO_SECRET_KEY,
40
- bucket: process.env.MINIO_BUCKET ?? 'rpa-screenshots',
41
- };
42
-
43
- // db se sigue pasando desde afuera (el pool ya existe en el bot)
44
- // pero puedes leer la URL para validar
45
- if (!db) throw new Error('[rpa-tools] db (pg.Pool) es requerido');
46
-
47
- // Validar que las env vars críticas existan
48
- const missing = ['endPoint', 'accessKey', 'secretKey']
49
- .filter(k => !minio[k]);
50
-
51
- if (missing.length) {
52
- throw new Error(`[rpa-tools] Faltan vars de entorno: ${missing.map(k => `MINIO_${k.toUpperCase()}`).join(', ')}`);
53
- }
54
-
55
-
56
-
57
- if (!botId) throw new Error('[rpa-tools] botId es requerido');
58
- if (!db) throw new Error('[rpa-tools] db (pg.Pool) es requerido');
59
- if (!minioCfg) throw new Error('[rpa-tools] minio config es requerida');
60
-
61
- const logger = createLogger(botId, logCfg);
62
- const minioClient = createMinioClient(minioCfg);
63
- const bucket = minioCfg.bucket ?? 'rpa-screenshots';
64
-
65
- await ensureBucket(minioClient, bucket);
66
- logger.info({ bucket }, 'MinIO listo');
67
-
68
- const watcher = new ScreenshotWatcher({ botId, pool: db, minioClient, bucket, logger });
69
-
70
- return {
71
- /** Instancia de Pino lista para usar en tu bot */
72
- logger,
73
-
74
- /**
75
- * Arranca el polling. Llama una vez, pasando el objeto `page` de Playwright.
76
- * @param {import('playwright').Page} page
77
- * @param {number} [pollMs=3000]
78
- */
79
- watchDebugFlag: (page, pollMs) => watcher.watch(page, pollMs),
80
-
81
- /** Limpia intervalos al finalizar el bot */
82
- destroy: () => watcher.destroy(),
83
- };
84
- }
85
-
86
- module.exports = { createRpaTools };
1
+ 'use strict';
2
+ const { createLogger } = require('./logger');
3
+ const { createMinioClient, ensureBucket } = require('./storage');
4
+ const { ScreenshotWatcher } = require('./watcher');
5
+ const { CredentialManager } = require('./credentials');
6
+
7
+ /**
8
+ * Factory principal de la librería.
9
+ *
10
+ * @param {object} opts
11
+ * @param {string} opts.botId - identificador único del bot
12
+ * @param {import('pg').Pool} opts.db - pool de pg ya conectado
13
+ * @param {object} opts.minio - config de MinIO
14
+ * @param {object} [opts.log] - opciones de Pino
15
+ *
16
+ * @returns {{ logger, watchDebugFlag, getCredentials, destroy }}
17
+ */
18
+ async function createRpaTools(opts = {}) {
19
+ const {
20
+ botId = process.env.RPA_BOT_ID,
21
+ log: logCfg = {},
22
+ db,
23
+ minio: minioCfg,
24
+ } = opts;
25
+
26
+ const minio = minioCfg ?? {
27
+ endPoint: process.env.MINIO_ENDPOINT,
28
+ port: Number(process.env.MINIO_PORT) || 9000,
29
+ useSSL: process.env.MINIO_USE_SSL === 'true',
30
+ accessKey: process.env.MINIO_ACCESS_KEY,
31
+ secretKey: process.env.MINIO_SECRET_KEY,
32
+ bucket: process.env.MINIO_BUCKET ?? 'rpa-screenshots',
33
+ };
34
+
35
+ if (!db) throw new Error('[rpa-tools] db (pg.Pool) es requerido');
36
+ if (!botId) throw new Error('[rpa-tools] botId es requerido');
37
+
38
+ const logger = createLogger(botId, logCfg);
39
+ const minioClient = createMinioClient(minio);
40
+ const bucket = minio.bucket ?? 'rpa-screenshots';
41
+
42
+ await ensureBucket(minioClient, bucket);
43
+ logger.info({ bucket }, 'MinIO listo');
44
+
45
+ const watcher = new ScreenshotWatcher({ botId, pool: db, minioClient, bucket, logger });
46
+ const credentials = new CredentialManager({ botId, pool: db });
47
+
48
+ return {
49
+ logger,
50
+ watchDebugFlag: (page, pollMs) => watcher.watch(page, pollMs),
51
+ getCredentials: (nombre) => credentials.getAppCredentials(nombre),
52
+ destroy: () => watcher.destroy(),
53
+ };
54
+ }
55
+
56
+ module.exports = { createRpaTools };
package/src/watcher.js CHANGED
@@ -49,7 +49,7 @@ class ScreenshotWatcher {
49
49
  this._watchTimer = setInterval(async () => {
50
50
  try {
51
51
  const { rows } = await this.pool.query(
52
- `SELECT screenshots, interval_sec
52
+ `SELECT screenshots_activo, intervalo_sec
53
53
  FROM bots.tb_bots
54
54
  WHERE bot_id = $1`,
55
55
  [this.botId]