60 lines
2.4 KiB
JavaScript
60 lines
2.4 KiB
JavaScript
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const ROOT = path.join(__dirname, '..');
|
|
|
|
function readLogicSource(fileName) {
|
|
const raw = fs.readFileSync(path.join(ROOT, 'logic', fileName), 'utf8');
|
|
// Remove a linha final "module.exports = {...}" -- as funcoes ficam soltas no escopo do node.
|
|
return raw.replace(/module\.exports\s*=\s*\{[\s\S]*?\};?\s*$/m, '').trim();
|
|
}
|
|
|
|
function inlinedLogic(fileNames) {
|
|
return fileNames.map(readLogicSource).join('\n\n');
|
|
}
|
|
|
|
function sqlAsJsTemplateLiteral(sqlRelativePath) {
|
|
const sql = fs.readFileSync(path.join(ROOT, sqlRelativePath), 'utf8');
|
|
const escaped = sql.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
|
|
return `\`${escaped}\``;
|
|
}
|
|
|
|
function buildDriverCode(driverRelativePath) {
|
|
const driverPath = path.join(ROOT, 'n8n', 'nodes', driverRelativePath);
|
|
let driver = fs.readFileSync(driverPath, 'utf8');
|
|
|
|
const requiresMatch = driver.match(/^\/\/ @requires (.+)$/m);
|
|
const requiredLogicFiles = requiresMatch ? requiresMatch[1].trim().split(/\s+/) : [];
|
|
driver = driver.replace(/^\/\/ @requires .+\n/m, '');
|
|
|
|
driver = driver.replace('/* __SQL_CANDIDATOS_V2__ */', sqlAsJsTemplateLiteral('sql/candidatos_v2_glpi.sql'));
|
|
driver = driver.replace('/* __SQL_LEGADO_V1_VERBATIM__ */', sqlAsJsTemplateLiteral('sql/top_10_chamados_abertos_glpi.sql'));
|
|
driver = driver.replace('/* __SQL_CONTEXTO_FOLLOWUPS__ */', sqlAsJsTemplateLiteral('sql/contexto_followups_glpi.sql'));
|
|
driver = driver.replace('/* __SQL_CONTEXTO_TAREFAS__ */', sqlAsJsTemplateLiteral('sql/contexto_tarefas_glpi.sql'));
|
|
|
|
const logicBlock = requiredLogicFiles.length ? `${inlinedLogic(requiredLogicFiles)}\n\n` : '';
|
|
return `${logicBlock}${driver.trim()}`;
|
|
}
|
|
|
|
function buildWorkflow() {
|
|
const templatePath = path.join(ROOT, 'n8n', 'workflow.template.json');
|
|
const template = JSON.parse(fs.readFileSync(templatePath, 'utf8'));
|
|
|
|
for (const node of template.nodes) {
|
|
if (node.type === 'n8n-nodes-base.code' && typeof node.parameters.jsCode === 'string') {
|
|
const marker = node.parameters.jsCode.match(/^__BUILD__:(.+)$/);
|
|
if (marker) {
|
|
node.parameters.jsCode = buildDriverCode(marker[1].trim());
|
|
}
|
|
}
|
|
}
|
|
|
|
return template;
|
|
}
|
|
|
|
if (require.main === module) {
|
|
process.stdout.write(JSON.stringify(buildWorkflow(), null, 2));
|
|
}
|
|
|
|
module.exports = { buildWorkflow, inlinedLogic, readLogicSource, sqlAsJsTemplateLiteral, buildDriverCode };
|