UNPKG

external-services-automation

Version:

External services automation library for Playwright and Cucumber

148 lines (147 loc) 5.37 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GuerrillaMailClient = exports.email = void 0; const axios_1 = __importDefault(require("axios")); const axios_cookiejar_support_1 = require("axios-cookiejar-support"); const tough_cookie_1 = require("tough-cookie"); class GuerrillaMailClient { constructor() { this.API_URL = 'https://api.guerrillamail.com/ajax.php'; this.ip = '127.0.0.1'; this.agent = encodeURIComponent('qa-automation-utils/1.0'); this.seq = 0; this.emailAddress = ''; const jar = new tough_cookie_1.CookieJar(); this.client = (0, axios_cookiejar_support_1.wrapper)(axios_1.default.create({ jar, withCredentials: true, headers: { // Recommended to identify politely 'User-Agent': 'qa-automation-utils/1.0', }, })); } /** * Function 1: Crea un email temporal. Si se pasa un alias se fuerza ese usuario. * @param alias Nombre de usuario deseado (sin dominio). * @returns Dirección de email completa. */ async createMail(alias) { if (alias) { const { data } = await this.client.get(this.API_URL, { params: { f: 'set_email_user', email_user: alias, ip: this.ip, agent: this.agent, }, }); this.emailAddress = data.email_addr; } else { const { data } = await this.client.get(this.API_URL, { params: { f: 'get_email_address', ip: this.ip, agent: this.agent, }, }); this.emailAddress = data.email_addr; } return this.emailAddress; } /** * Function 2: Lee la bandeja y devuelve el email MÁS RECIENTE cuyo subject matchee con subjectRegex. * Hace polling hasta timeout. * @param subjectRegex Expresión regular a matchear con el asunto. * @param timeoutMs Tiempo máximo a esperar (ms). * @param pollMs Intervalo entre consultas (ms). */ async readMailBySubject(subjectRegex, timeoutMs = 60000, pollMs = 5000) { const start = Date.now(); while (Date.now() - start < timeoutMs) { const { data } = await this.client.get(this.API_URL, { params: { f: 'check_email', seq: this.seq, ip: this.ip, agent: this.agent, }, }); this.seq = data.seq ?? this.seq; const list = data.list ?? []; // Filtrar emails que matchean el subject const matches = list.filter(m => subjectRegex.test(m.mail_subject)); if (matches.length > 0) { // Ordenar por timestamp descendente (más reciente primero) matches.sort((a, b) => b.mail_timestamp - a.mail_timestamp); // Tomar el más reciente const mostRecent = matches[0]; const full = await this.fetchEmail(mostRecent.mail_id); return full; } await new Promise(r => setTimeout(r, pollMs)); } throw new Error(`Timeout (${timeoutMs} ms) esperando un email con asunto que matchee ${subjectRegex}`); } /** * Function 3: Elimina un correo específico del servidor. * @param mailId ID retornado por la API (mail_id). */ async deleteMail(mailId) { await this.client.get(this.API_URL, { params: { f: 'del_email', email_ids: `[${mailId}]`, // formato aceptado por la API ip: this.ip, agent: this.agent, }, }); } /** Helper interno para descargar cuerpo completo */ async fetchEmail(mailId) { const { data } = await this.client.get(this.API_URL, { params: { f: 'fetch_email', email_id: mailId, ip: this.ip, agent: this.agent, }, }); return data; } /** * Function 4: Crea una nueva instancia de email client para aislamiento entre escenarios */ static createIsolatedClient() { return new GuerrillaMailClient(); } /** * Function 5: Elimina todos los emails del buzón actual */ async clearInbox() { const { data } = await this.client.get(this.API_URL, { params: { f: 'check_email', seq: this.seq, ip: this.ip, agent: this.agent, }, }); const list = data.list ?? []; // Eliminar todos los emails uno por uno for (const email of list) { try { await this.deleteMail(email.mail_id); } catch (error) { console.warn(`Could not delete email ${email.mail_id}:`, error); } } } } exports.GuerrillaMailClient = GuerrillaMailClient; exports.email = new GuerrillaMailClient();