UNPKG

@ai-growth/n8n-nodes-wordpress

Version:

n8n node for WordPress integration with AI GROWTH - SEO WP plugin

229 lines 8.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SeoService = void 0; const ErrorUtils_1 = require("../utils/ErrorUtils"); /** * Serviço para gerenciamento de metadados SEO */ class SeoService { /** * Construtor do serviço * @param client Cliente WordPress */ constructor(client) { this.pluginEndpoint = 'ai-growth-seo/v1'; this.pluginAvailabilityChecked = false; this.pluginAvailable = false; this.pluginVersion = 'unknown'; this.pluginFeatures = []; this.client = client; } /** * Verifica se o plugin AI GROWTH - SEO WP está disponível * @param force Forçar verificação mesmo se já verificado * @returns Status do plugin */ async checkPluginAvailability(force = false) { console.log('[SeoService] Checking plugin availability:', { force, alreadyChecked: this.pluginAvailabilityChecked, available: this.pluginAvailable }); // Se já verificou e não está forçando, retorna o status atual if (this.pluginAvailabilityChecked && !force) { console.log('[SeoService] Using cached plugin status:', { version: this.pluginVersion, features: this.pluginFeatures, status: this.pluginAvailable ? 'active' : 'not_installed' }); return { version: this.pluginVersion, features: this.pluginFeatures, status: this.pluginAvailable ? 'active' : 'not_installed', }; } try { console.log('[SeoService] Attempting to contact plugin endpoint:', `${this.pluginEndpoint}/info`); // Tenta acessar o endpoint de informações do plugin const response = await this.client.get(`${this.pluginEndpoint}/info`); // Atualiza as informações do plugin this.pluginAvailable = true; this.pluginVersion = response.version || 'unknown'; this.pluginFeatures = response.features || []; this.pluginAvailabilityChecked = true; console.log('[SeoService] Plugin is available and active:', { version: this.pluginVersion, features: this.pluginFeatures }); return { version: this.pluginVersion, features: this.pluginFeatures, status: 'active', }; } catch (error) { console.error('[SeoService] Plugin availability check failed:', { error: error instanceof Error ? error.message : 'Unknown error', endpoint: `${this.pluginEndpoint}/info` }); // Marca o plugin como indisponível this.pluginAvailable = false; this.pluginAvailabilityChecked = true; this.pluginVersion = 'unknown'; this.pluginFeatures = []; return { version: 'unknown', features: [], status: 'not_installed', }; } } /** * Obtém metadados SEO para um post específico * @param postId ID do post * @param options Opções da consulta * @returns Metadados SEO do post */ async getPostSeoMetadata(postId, options = {}) { const { includeFaq = true, includeCta = true, requirePlugin = false } = options; // Verificar disponibilidade do plugin se necessário if (!this.pluginAvailabilityChecked) { await this.checkPluginAvailability(); } // Se o plugin não está disponível e é requerido, lança erro if (!this.pluginAvailable && requirePlugin) { throw new ErrorUtils_1.WordPressError('AI GROWTH - SEO WP plugin is required but not available on the WordPress site', ErrorUtils_1.WordPressErrorType.NOT_FOUND); } // Se o plugin não está disponível, retorna metadados vazios if (!this.pluginAvailable) { return {}; } try { // Obter metadados SEO do post const response = await this.client.get(`${this.pluginEndpoint}/post/${postId}/metadata`); // Extrair e formatar os dados de resposta const metadata = { meta_title: response.meta_title || '', meta_description: response.meta_description || '', meta_keywords: response.meta_keywords || '', }; // Adicionar FAQ se solicitado e disponível if (includeFaq && response.faq) { metadata.faq = this.formatFaq(response.faq); } // Adicionar CTA se solicitado e disponível if (includeCta && response.cta) { metadata.cta = this.formatCta(response.cta); } return metadata; } catch (error) { // Se o plugin não está disponível mas não é requerido, retorna metadados vazios if (!requirePlugin) { return {}; } // Caso contrário, relança o erro if (error instanceof ErrorUtils_1.WordPressError) { throw error; } throw new ErrorUtils_1.WordPressError(`Failed to fetch SEO metadata for post ${postId}: ${error.message}`, ErrorUtils_1.WordPressErrorType.SERVER, undefined, error); } } /** * Formata os dados de FAQ do plugin * @param faq Dados de FAQ da API * @returns FAQ formatado */ formatFaq(faq) { if (Array.isArray(faq)) { return faq.map(item => ({ question: item.question || '', answer: item.answer || '', })); } if (typeof faq === 'object' && faq !== null) { // Alguns plugins podem retornar um objeto com índices numéricos return Object.values(faq).map(item => ({ question: item.question || '', answer: item.answer || '', })); } return []; } /** * Formata os dados de CTA do plugin * @param cta Dados de CTA da API * @returns CTA formatado */ formatCta(cta) { if (typeof cta === 'object' && cta !== null) { return { text: cta.text || '', url: cta.url || '', }; } return { text: '', url: '', }; } /** * Verifica se uma feature específica do plugin está disponível * @param featureName Nome da feature * @returns Se a feature está disponível */ hasFeature(featureName) { return this.pluginFeatures.includes(featureName); } /** * Enriquece um post com metadados SEO * @param post Post a ser enriquecido * @param options Opções da consulta * @returns Post com metadados SEO */ async enrichPostWithSeo(post, options = {}) { // Se não há post ou não há ID, retorna o post original if (!post || !post.id) { return post; } try { // Obter metadados SEO para o post const seoMetadata = await this.getPostSeoMetadata(post.id, options); // Mesclar os metadados com o post return { ...post, ...seoMetadata, }; } catch (error) { // Se falhar e não é obrigatório, retorna o post original if (!options.requirePlugin) { return post; } // Caso contrário, relança o erro throw error; } } /** * Enriquece múltiplos posts com metadados SEO * @param posts Array de posts a serem enriquecidos * @param options Opções da consulta * @returns Posts com metadados SEO */ async enrichPostsWithSeo(posts, options = {}) { // Se não há posts, retorna array vazio if (!posts || !Array.isArray(posts) || posts.length === 0) { return []; } try { // Enriquecer cada post com metadados SEO return await Promise.all(posts.map(post => this.enrichPostWithSeo(post, options))); } catch (error) { // Se falhar e não é obrigatório, retorna os posts originais if (!options.requirePlugin) { return posts; } // Caso contrário, relança o erro throw error; } } } exports.SeoService = SeoService; //# sourceMappingURL=SeoService.js.map