@ai-growth/n8n-nodes-wordpress
Version:
n8n node for WordPress integration with AI GROWTH - SEO WP plugin
279 lines • 9.54 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = exports.LogLevel = void 0;
/**
* Níveis de log
*/
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["NONE"] = 0] = "NONE";
LogLevel[LogLevel["ERROR"] = 1] = "ERROR";
LogLevel[LogLevel["WARN"] = 2] = "WARN";
LogLevel[LogLevel["INFO"] = 3] = "INFO";
LogLevel[LogLevel["DEBUG"] = 4] = "DEBUG";
LogLevel[LogLevel["TRACE"] = 5] = "TRACE";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
/**
* Classe para gerenciar logs da aplicação
*/
class Logger {
/**
* Construtor do logger
* @param options Opções de configuração
*/
constructor(options = {}) {
var _a, _b, _c;
this.level = (_a = options.level) !== null && _a !== void 0 ? _a : LogLevel.ERROR;
this.prefix = (_b = options.prefix) !== null && _b !== void 0 ? _b : '[WordPress API]';
this.timestamp = options.timestamp !== undefined ? options.timestamp : true;
this.logFn = (_c = options.logFn) !== null && _c !== void 0 ? _c : console.log;
}
/**
* Define o nível de log
* @param level Novo nível de log
*/
setLevel(level) {
this.level = level;
}
/**
* Obtém o nível de log atual
* @returns Nível de log atual
*/
getLevel() {
return this.level;
}
/**
* Verifica se um nível específico está habilitado
* @param level Nível a verificar
* @returns Verdadeiro se o nível estiver habilitado
*/
isLevelEnabled(level) {
return this.level >= level;
}
/**
* Formata a mensagem de log
* @param level Nível do log
* @param message Mensagem ou objeto a ser logado
* @returns Mensagem formatada
*/
format(level, message) {
const timestamp = this.timestamp ? `[${new Date().toISOString()}] ` : '';
const prefix = this.prefix ? `${this.prefix} ` : '';
// Formatar objetos
let formattedMessage = message;
if (typeof message === 'object') {
try {
formattedMessage = JSON.stringify(message, null, 2);
}
catch (error) {
formattedMessage = `[Object: ${message.toString()}]`;
}
}
return `${timestamp}${prefix}${level}: ${formattedMessage}`;
}
/**
* Registra um log de nível ERROR
* @param message Mensagem ou objeto a ser logado
* @param data Dados adicionais (opcional)
*/
error(message, data) {
if (this.level >= LogLevel.ERROR) {
this.logFn(this.format('ERROR', message));
if (data !== undefined) {
this.logFn(this.format('ERROR_DATA', data));
}
}
}
/**
* Registra um log de nível WARN
* @param message Mensagem ou objeto a ser logado
* @param data Dados adicionais (opcional)
*/
warn(message, data) {
if (this.level >= LogLevel.WARN) {
this.logFn(this.format('WARN', message));
if (data !== undefined) {
this.logFn(this.format('WARN_DATA', data));
}
}
}
/**
* Registra um log de nível INFO
* @param message Mensagem ou objeto a ser logado
* @param data Dados adicionais (opcional)
*/
info(message, data) {
if (this.level >= LogLevel.INFO) {
this.logFn(this.format('INFO', message));
if (data !== undefined) {
this.logFn(this.format('INFO_DATA', data));
}
}
}
/**
* Registra um log de nível DEBUG
* @param message Mensagem ou objeto a ser logado
* @param data Dados adicionais (opcional)
*/
debug(message, data) {
if (this.level >= LogLevel.DEBUG) {
this.logFn(this.format('DEBUG', message));
if (data !== undefined) {
this.logFn(this.format('DEBUG_DATA', data));
}
}
}
/**
* Registra uma requisição HTTP
* @param method Método HTTP
* @param url URL da requisição
* @param params Parâmetros da requisição (opcional)
* @param data Dados da requisição (opcional)
*/
request(method, url, params, data) {
if (this.level >= LogLevel.DEBUG) {
this.debug(`${method.toUpperCase()} ${url}`);
if (params) {
this.debug('Request params:', params);
}
if (data) {
this.debug('Request data:', data);
}
}
}
/**
* Registra uma resposta HTTP
* @param method Método HTTP da requisição
* @param url URL da requisição
* @param status Status HTTP da resposta
* @param data Dados da resposta (opcional)
*/
response(method, url, status, data) {
if (this.level >= LogLevel.DEBUG) {
this.debug(`${method.toUpperCase()} ${url} => ${status}`);
if (data) {
this.debug('Response data:', data);
}
}
}
/**
* Registra um erro HTTP
* @param method Método HTTP da requisição
* @param url URL da requisição
* @param error Erro ocorrido
*/
httpError(method, url, error) {
if (this.level >= LogLevel.ERROR) {
this.error(`${method.toUpperCase()} ${url} => ERROR: ${error.message || error}`);
if (error.response) {
this.error('Response error:', {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data,
});
}
else if (error.request) {
this.error('Request error: No response received');
}
if (error.stack) {
this.error('Stack trace:', error.stack);
}
}
}
/**
* Registra um log de nível TRACE (mais detalhado que DEBUG)
* @param message Mensagem ou objeto a ser logado
* @param data Dados adicionais (opcional)
*/
trace(message, data) {
if (this.level >= LogLevel.TRACE) {
this.logFn(this.format('TRACE', message));
if (data !== undefined) {
this.logFn(this.format('TRACE_DATA', data));
}
}
}
/**
* Registra detalhes de conexão
* @param url URL da conexão
* @param status Status da conexão
* @param details Detalhes adicionais
*/
connection(url, status, details) {
if (this.level >= LogLevel.INFO) {
const statusEmoji = status === 'success' ? '✅' : status === 'failed' ? '❌' : '🔄';
this.info(`${statusEmoji} Connection ${status}: ${url}`);
if (details && this.level >= LogLevel.DEBUG) {
this.debug('Connection details:', details);
}
}
}
/**
* Registra detalhes de autenticação
* @param method Método de autenticação
* @param status Status da autenticação
* @param details Detalhes adicionais (sem credenciais sensíveis)
*/
auth(method, status, details) {
if (this.level >= LogLevel.INFO) {
const statusEmoji = status === 'success' ? '🔐' : status === 'failed' ? '🚫' : '🔑';
this.info(`${statusEmoji} Auth ${method} ${status}`);
if (details && this.level >= LogLevel.DEBUG) {
// Filtrar informações sensíveis
const safeDetails = this.sanitizeAuthDetails(details);
this.debug('Auth details:', safeDetails);
}
}
}
/**
* Registra informações de DNS/Network
* @param operation Operação de rede
* @param details Detalhes da operação
*/
network(operation, details) {
if (this.level >= LogLevel.DEBUG) {
this.debug(`🌐 Network ${operation}:`, details);
}
}
/**
* Registra tentativas de retry
* @param attempt Número da tentativa
* @param maxAttempts Máximo de tentativas
* @param error Erro que causou o retry
* @param nextRetryIn Tempo até próxima tentativa em ms
*/
retry(attempt, maxAttempts, error, nextRetryIn) {
if (this.level >= LogLevel.WARN) {
const message = `🔄 Retry ${attempt}/${maxAttempts}: ${error.message || error}`;
this.warn(message);
if (nextRetryIn && this.level >= LogLevel.DEBUG) {
this.debug(`Next retry in ${nextRetryIn}ms`);
}
}
}
/**
* Remove informações sensíveis dos detalhes de autenticação
* @param details Detalhes originais
* @returns Detalhes sanitizados
*/
sanitizeAuthDetails(details) {
if (!details || typeof details !== 'object') {
return details;
}
const sanitized = { ...details };
// Lista de campos sensíveis para mascarar
const sensitiveFields = ['password', 'token', 'authorization', 'auth', 'secret', 'key'];
for (const field of sensitiveFields) {
if (sanitized[field]) {
sanitized[field] = '***REDACTED***';
}
}
// Mascarar headers de autorização
if (sanitized.headers && sanitized.headers.Authorization) {
sanitized.headers.Authorization = 'Basic ***REDACTED***';
}
return sanitized;
}
}
exports.Logger = Logger;
//# sourceMappingURL=Logger.js.map