const { logInfo, logWarning } = require('./logger'); const stripHTML = (html) => { if (!html) return ''; let cleaned = html .replace(/</g, '<') // < para < .replace(/>/g, '>') // > para > .replace(/&/g, '&') // & para & .replace(/ /g, ' ') //   para espaço .replace(/</g, '<') // < para < .replace(/>/g, '>') // > para > .replace(/&/g, '&') // & para & .replace(/"/g, '"'); // " para " cleaned = cleaned .replace(//gi, '\n') //
para quebra de linha .replace(/

/gi, '') // Remove

.replace(/<\/p>/gi, '\n\n') //

para duas quebras .replace(//gi, '**') // para ** .replace(/<\/strong>/gi, '**') // para ** .replace(//gi, '*') // para * .replace(/<\/em>/gi, '*') // para * .replace(/
/gi, '> ') //
para citação .replace(/<\/blockquote>/gi, '') //
.replace(/]*>/gi, '') // Remove
com qualquer atributo .replace(/<\/div>/gi, '\n') //
para quebra .replace(/<[^>]*>/g, '') // Remove todas outras tags HTML .replace(/\n\s*\n\s*\n/g, '\n\n') // Remove múltiplas quebras .replace(/^\s+|\s+$/g, '') // Remove espaços no início/fim .trim(); return cleaned; }; const handleImages = (content) => { const imgRegex = /]+src="([^"]+)"[^>]*>/gi; const hasImages = imgRegex.test(content); if (hasImages) { logWarning('📷 Imagem detectada no comentário GLPI'); return content.replace(/]*>.*?]*>.*?<\/a>/gi, '[IMAGEM ANEXA NO GLPI]'); } return content; }; const cleanJSONMetadata = (content) => { if (typeof content === 'string' && content.includes('{id=') && content.includes('content=')) { try { const contentMatch = content.match(/content=([^,]+),/); if (contentMatch && contentMatch[1]) { let extracted = contentMatch[1].trim(); extracted = extracted.replace(/^['"]|['"]$/g, ''); return extracted; } } catch (error) { logWarning('Não foi possível extrair conteúdo do metadado GLPI', { content }); } } return content; }; const sanitizeGLPIComment = (commentObj) => { if (!commentObj || typeof commentObj !== 'object') { logWarning('Comentário inválido recebido', { comment: commentObj }); return ''; } let content = commentObj.content || ''; if (!content) return ''; content = cleanJSONMetadata(content.toString()); content = handleImages(content); content = stripHTML(content); if (content !== commentObj.content) { logInfo('🔧 Comentário sanitizado', { original: commentObj.content.substring(0, 100) + '...', cleaned: content.substring(0, 100) + '...' }); } return content; }; /** * @module commentSanitizer * @description Este módulo utilitário é especializado em limpar e formatar o conteúdo dos comentários (follow-ups) vindos do GLPI. * O GLPI armazena comentários em formato HTML, muitas vezes com metadados e formatações que não são desejáveis no ServiceNow. * O objetivo é converter esse conteúdo em texto puro e legível. * * Funções: * - `sanitizeGLPIComment(commentObj)`: A função principal que orquestra o processo de limpeza. * - `stripHTML(html)`: Remove a maioria das tags HTML, convertendo algumas (como `
`, `

`, ``) em marcações de texto simples (quebras de linha, asteriscos). * - `handleImages(content)`: Detecta a presença de imagens nos comentários do GLPI e as substitui por um texto placeholder, como "[IMAGEM ANEXA NO GLPI]", já que as imagens não podem ser transferidas diretamente. * - `cleanJSONMetadata(content)`: Remove metadados em formato de string JSON que o GLPI às vezes insere no campo de conteúdo, extraindo apenas o texto real do comentário. */ module.exports = { sanitizeGLPIComment, stripHTML, handleImages, cleanJSONMetadata };