dengun_ai-admin-client
Version:
Cliente simples para integração com o AI Admin Dashboard - Plug and Play
237 lines (236 loc) • 8.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AiAdminClient = void 0;
const events_1 = require("events");
const ConnectionManager_1 = require("./services/ConnectionManager");
const TelemetryReporter_1 = require("./services/TelemetryReporter");
const ErrorReporter_1 = require("./services/ErrorReporter");
/**
* Cliente principal para integração com o AI Admin Dashboard
*
* Objetivos:
* 1. Garantir conexão entre apps
* 2. Suporte a múltiplos usuários simultâneos
* 3. Relatório automático de uso
* 4. Relatório automático de erros
*/
class AiAdminClient extends events_1.EventEmitter {
constructor(config) {
super();
this.activeSessions = new Map();
this.isInitialized = false;
this.config = {
...config,
options: {
autoReportUsage: true,
autoReportErrors: true,
reportInterval: 30000, // 30 segundos
maxRetries: 3,
timeout: 10000,
debug: false,
...config.options
}
};
this.connectionManager = new ConnectionManager_1.ConnectionManager(this.config);
this.telemetryReporter = new TelemetryReporter_1.TelemetryReporter(this.config);
this.errorReporter = new ErrorReporter_1.ErrorReporter(this.config);
this.setupEventListeners();
}
/**
* Inicializa o cliente e estabelece conexão com o dashboard
*/
async initialize() {
var _a, _b;
try {
this.log('Inicializando cliente AI Admin...');
// Estabelecer conexão
await this.connectionManager.connect();
// Configurar referência do ConnectionManager nos serviços
this.telemetryReporter.setConnectionManager(this.connectionManager);
this.errorReporter.setConnectionManager(this.connectionManager);
// Inicializar serviços de relatório
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.autoReportUsage) {
await this.telemetryReporter.start();
}
if ((_b = this.config.options) === null || _b === void 0 ? void 0 : _b.autoReportErrors) {
await this.errorReporter.start();
}
this.isInitialized = true;
this.emit('initialized');
this.log('Cliente inicializado com sucesso');
}
catch (error) {
this.logError('Erro ao inicializar cliente:', error);
throw error;
}
}
/**
* Objetivo 2: Criar sessão para usuário usar o bot
*/
async createUserSession(userId, tenantId, metadata) {
var _a;
this.ensureInitialized();
try {
const sessionId = this.generateSessionId();
// Validar usuário no dashboard
const validation = await this.connectionManager.validateUser(userId, tenantId);
if (!validation.success) {
throw new Error(`Usuário não autorizado: ${validation.error}`);
}
const session = {
userId,
tenantId,
sessionId,
permissions: ((_a = validation.data) === null || _a === void 0 ? void 0 : _a.permissions) || [],
metadata
};
this.activeSessions.set(sessionId, session);
this.emit('sessionCreated', session);
this.log(`Sessão criada para usuário ${userId} (${sessionId})`);
return session;
}
catch (error) {
this.logError('Erro ao criar sessão:', error);
throw error;
}
}
/**
* Objetivo 3: Reportar uso do bot pelo usuário
*/
async reportUsage(usage) {
var _a;
const session = this.activeSessions.get(usage.sessionId);
if (!session) {
throw new Error('Sessão não encontrada');
}
const fullUsage = {
...usage,
timestamp: Date.now()
};
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.autoReportUsage) {
await this.telemetryReporter.reportUsage(fullUsage);
}
this.emit('usageReported', fullUsage);
this.log(`Uso reportado: ${usage.action} - ${usage.tokensUsed} tokens`);
}
/**
* Objetivo 4: Reportar erros da aplicação
*/
async reportError(error) {
var _a;
const fullError = {
...error,
timestamp: Date.now()
};
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.autoReportErrors) {
await this.errorReporter.reportError(fullError);
}
this.emit('errorReported', fullError);
this.log(`Erro reportado: ${error.error}`);
}
/**
* Encerrar sessão de usuário
*/
async endUserSession(sessionId) {
const session = this.activeSessions.get(sessionId);
if (session) {
this.activeSessions.delete(sessionId);
this.emit('sessionEnded', session);
this.log(`Sessão encerrada: ${sessionId}`);
}
}
/**
* Objetivo 1: Verificar status da conexão
*/
async getConnectionStatus() {
return this.connectionManager.getStatus();
}
/**
* Obter sessões ativas
*/
getActiveSessions() {
return Array.from(this.activeSessions.values());
}
/**
* Obter estatísticas de uso
*/
async getUsageStats(timeRange) {
return this.telemetryReporter.getStats(timeRange);
}
/**
* Encerrar cliente e limpar recursos
*/
async shutdown() {
try {
this.log('Encerrando cliente...');
// Encerrar todas as sessões ativas
for (const sessionId of this.activeSessions.keys()) {
await this.endUserSession(sessionId);
}
// Parar serviços
await this.telemetryReporter.stop();
await this.errorReporter.stop();
await this.connectionManager.disconnect();
this.isInitialized = false;
this.emit('shutdown');
this.log('Cliente encerrado');
}
catch (error) {
this.logError('Erro ao encerrar cliente:', error);
throw error;
}
}
// Métodos privados
setupEventListeners() {
var _a;
this.connectionManager.on('connected', () => {
this.emit('connected');
this.log('Conectado ao dashboard');
});
this.connectionManager.on('disconnected', () => {
this.emit('disconnected');
this.log('Desconectado do dashboard');
});
this.connectionManager.on('error', (error) => {
this.emit('error', error);
this.logError('Erro de conexão:', error);
});
// Auto-reportar erros internos
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.autoReportErrors) {
this.on('error', async (error) => {
try {
await this.reportError({
error: error.message || String(error),
errorCode: 'INTERNAL_ERROR',
stack: error.stack,
context: { component: 'AiAdminClient' }
});
}
catch (reportError) {
this.logError('Erro ao reportar erro interno:', reportError);
}
});
}
}
ensureInitialized() {
if (!this.isInitialized) {
throw new Error('Cliente não foi inicializado. Chame initialize() primeiro.');
}
}
generateSessionId() {
return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
log(message) {
var _a;
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.debug) {
console.log(`[AiAdminClient] ${message}`);
}
}
logError(message, error) {
var _a;
if ((_a = this.config.options) === null || _a === void 0 ? void 0 : _a.debug) {
console.error(`[AiAdminClient] ${message}`, error);
}
}
}
exports.AiAdminClient = AiAdminClient;