Thoth / server /tools.js
mfirat007's picture
Upload 74 files
4a51f94 verified
Raw History Blame Contribute Delete
11.6 kB
// Kaynak üzerinde çalışan yardımcı araçlar: tex-fmt ile biçimlendirme, Pandoc ile Word'e aktarma.
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync, statSync } from 'node:fs';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { Router } from 'express';
import { BUILD_DIR, PANDOC_BIN, ROOT, TEXFMT_BIN } from './config.js';
import { db } from './db.js';
import { withProject } from './store.js';
import { FRONT_FIELDS, PAGE_BREAK, TOC, apaFrontMatter, apaReferenceDoc, applyApa, plainText, withRunningHead } from './word.js';
import { HttpError, cleanPath } from './util.js';
/** Bir aracı çalıştırır; `input` standart girdiye yazılır. */
export function runTool(bin, args, { cwd, input, timeoutMs }) {
return new Promise((resolve) => {
const child = spawn(bin, args, { cwd, windowsHide: true });
const out = [];
let err = '';
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill();
}, timeoutMs);
child.stdout.on('data', (d) => out.push(d));
child.stderr.on('data', (d) => (err += d));
child.on('error', (e) => {
clearTimeout(timer);
resolve({ code: -1, stdout: Buffer.alloc(0), stderr: e.message, timedOut });
});
child.on('close', (code) => {
clearTimeout(timer);
resolve({ code: timedOut ? -1 : code, stdout: Buffer.concat(out), stderr: err, timedOut });
});
child.stdin.on('error', () => {}); // süreç erken kapanırsa yazma hatası yutulur
child.stdin.end(input ?? '');
});
}
export function requireBinary(bin, name) {
if (!existsSync(bin)) throw new HttpError(500, `${name} kurulu değil. Sunucuda "npm run setup" komutunu çalıştırın.`);
}
export const toolsRouter = Router();
// ---- Biçimlendirme (tex-fmt) ----
toolsRouter.post('/projects/:id/format', withProject('editor'), async (req, res) => {
const { content } = req.body;
if (typeof content !== 'string') throw new HttpError(400, 'Biçimlendirilecek içerik gerekli.');
if (content.length > 2_000_000) throw new HttpError(413, 'Dosya biçimlendirmek için çok büyük.');
requireBinary(TEXFMT_BIN, 'Biçimlendirici (tex-fmt)');
// --nowrap: yalnızca girinti ve boşluklar düzenlenir; paragraf satırları yeniden kırılmaz.
const { code, stdout, stderr, timedOut } = await runTool(TEXFMT_BIN, ['--stdin', '--nowrap', '--noconfig'], {
input: content,
timeoutMs: 20_000,
});
if (timedOut) throw new HttpError(504, 'Biçimlendirme süre sınırını aştı.');
if (code !== 0) throw new HttpError(422, `Dosya biçimlendirilemedi: ${stderr.trim() || 'bilinmeyen hata'}`);
// tex-fmt Windows'ta CRLF yazar; editör LF kullanır. Sonda yeni satır yoksa eklenmez.
let formatted = stdout.toString('utf8').replace(/\r\n/g, '\n');
if (!content.endsWith('\n')) formatted = formatted.replace(/\n$/, '');
const warnings = stderr
.split(/\r?\n/)
.map((l) => l.replace(/^(WARN|ERROR):\s*tex-fmt\s*<stdin>:\s*/, '').trim())
.filter(Boolean);
res.json({ content: formatted, warnings });
});
// ---- Word'e aktarma (Pandoc) ----
/**
* \input ve \include komutlarını yalnızca proje dosyalarından çözerek tek bir metinde birleştirir.
* Pandoc'un kendi dosya okumaları kapalı (sandbox) olduğundan, proje dışından dosya alınamaz.
*/
export function flattenIncludes(files, mainPath) {
const resolve = (name) => {
let clean;
try {
clean = cleanPath(name.trim());
} catch {
return null;
}
return [clean, `${clean}.tex`].find((p) => typeof files.get(p) === 'string') ?? null;
};
const expand = (filePath, stack) => {
const text = files.get(filePath);
if (stack.length > 20) return text;
return text
.split('\n')
.map((line) => {
// Yorum kısmındaki komutlara dokunulmaz.
const comment = line.search(/(?<!\\)%/);
const code = comment < 0 ? line : line.slice(0, comment);
const rest = comment < 0 ? '' : line.slice(comment);
const replaced = code.replace(/\\(input|include)\s*\{([^{}]+)\}/g, (whole, _cmd, name) => {
const target = resolve(name);
if (!target || stack.includes(target)) return whole;
return `\n${expand(target, [...stack, target])}\n`;
});
return replaced + rest;
})
.join('\n');
};
return expand(mainPath, [mainPath]);
}
// Pandoc'un LaTeX okuyucusu \clearpage ve \tableofcontents komutlarını atar; Word'de karşılıkları
// oluşturulabilsin diye bunlar, okuyucunun bölüm (Div) olarak koruduğu işaret ortamlarına çevrilir.
const LAYOUT_MARK = { pageBreak: 'thothsayfasonu', toc: 'thothicindekiler' };
export function markLayoutCommands(source) {
const env = (name) => `\n\\begin{${name}}\\end{${name}}\n`;
return source
.replace(/\\(clearpage|cleardoublepage|newpage|pagebreak)(?![a-zA-Z])/g, env(LAYOUT_MARK.pageBreak))
.replace(/\\tableofcontents(?![a-zA-Z])/g, env(LAYOUT_MARK.toc));
}
const IMAGE_EXT = ['.png', '.jpg', '.jpeg', '.gif'];
// LaTeX okuyucusunun ürettiği güvenli üst bilgiler; diğerleri (bibliography, csl vb.) dosya okutabilir.
const SAFE_META = new Set(['title', 'subtitle', 'author', 'date', 'abstract']);
/**
* Pandoc ara biçimindeki (JSON) belgeyi Word'e yazmadan önce temizler: resim yolları yalnızca çalışma
* klasöründeki resim dosyalarına izin verir; diğerleri görünür bir notla değiştirilir.
*/
export function sanitizeAst(ast, workDir) {
const meta = {};
for (const [key, value] of Object.entries(ast.meta ?? {})) if (SAFE_META.has(key)) meta[key] = value;
ast.meta = meta;
const resolveImage = (url) => {
if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('/') || url.startsWith('\\')) return null; // adres ya da mutlak yol
let clean;
try {
clean = cleanPath(decodeURI(url));
} catch {
return null;
}
const ext = path.extname(clean).toLowerCase();
const candidates = ext ? [clean] : IMAGE_EXT.map((e) => clean + e);
for (const c of candidates) {
if (!IMAGE_EXT.includes(path.extname(c).toLowerCase())) continue;
const full = path.join(workDir, ...c.split('/'));
if (existsSync(full) && statSync(full).isFile()) return full;
}
return null;
};
const skipped = [];
const walk = (node) => {
if (Array.isArray(node)) return node.map(walk);
if (!node || typeof node !== 'object') return node;
if (node.t === 'Image') {
const [attr, alt, [url, title]] = node.c;
const local = resolveImage(url);
if (local) return { t: 'Image', c: [attr, walk(alt), [local, title]] };
skipped.push(url);
return { t: 'Emph', c: [{ t: 'Str', c: `[Görsel Word'e aktarılamadı: ${url}]` }] };
}
// Ham LaTeX/XML parçaları Word'e geçirilmez.
if (node.t === 'RawBlock') return { t: 'Div', c: [['', [], []], []] };
if (node.t === 'RawInline') return { t: 'Str', c: '' };
// Sayfa sonu ve içindekiler için markLayoutCommands()'ın bıraktığı işaretler
if (node.t === 'Div' && node.c[0][1].includes(LAYOUT_MARK.pageBreak)) return PAGE_BREAK;
if (node.t === 'Div' && node.c[0][1].includes(LAYOUT_MARK.toc)) return TOC;
const copy = {};
for (const [k, v] of Object.entries(node)) copy[k] = k === 'meta' ? v : walk(v);
return copy;
};
return { ast: walk(ast), skipped };
}
export const PANDOC_LIMITS = ['+RTS', '-M1024m', '-RTS'];
// APA 7 kaynakça stili: Citation Style Language projesi (CC BY-SA 3.0), https://github.com/citation-style-language/styles
export const APA_CSL = path.join(ROOT, 'server', 'csl', 'apa.csl');
toolsRouter.get('/projects/:id/export/docx', withProject(), async (req, res) => {
requireBinary(PANDOC_BIN, 'Word dönüştürücüsü (Pandoc)');
const project = req.project;
const rows = db.prepare('SELECT path, content FROM files WHERE project_id = ?').all(project.id);
const files = new Map(rows.map((r) => [r.path, r.content]));
if (typeof files.get(project.main_file) !== 'string') throw new HttpError(400, 'Ana dosya bulunamadı.');
const work = path.join(BUILD_DIR, project.id, `word-${randomUUID()}`);
try {
for (const r of rows) {
const target = path.join(work, ...r.path.split('/'));
await mkdir(path.dirname(target), { recursive: true });
await writeFile(target, r.content);
}
// 1) LaTeX -> Pandoc ara biçimi; dosya erişimi kapalı.
const today = new Intl.DateTimeFormat('tr-TR', { day: 'numeric', month: 'long', year: 'numeric' }).format(new Date());
const source = markLayoutCommands(flattenIncludes(files, project.main_file).replace(/\\today(?![a-zA-Z])/g, today));
const toAst = async (latex) => {
const parsed = await runTool(PANDOC_BIN, [...PANDOC_LIMITS, '--sandbox', '-f', 'latex', '-t', 'json'], {
cwd: work,
input: latex,
timeoutMs: 60_000,
});
if (parsed.code !== 0) {
throw new HttpError(422, `Belge Word'e çevrilemedi: ${parsed.timedOut ? 'süre sınırı aşıldı' : parsed.stderr.trim().slice(0, 500)}`);
}
return sanitizeAst(JSON.parse(parsed.stdout.toString('utf8')), work).ast;
};
const ast = await toAst(source);
// apa7 belgelerinde başlık sayfası alanları ayrıca çevrilir (sırası korunsun diye madde listesi olarak).
const front = apaFrontMatter(source);
const fieldBlocks = {};
if (front) {
const items = FRONT_FIELDS.map((f) => `\\item ${front.fields[f] ?? ''}`).join('\n');
const list = (await toAst(`\\begin{itemize}\n${items}\n\\end{itemize}`)).blocks.find((b) => b.t === 'BulletList');
FRONT_FIELDS.forEach((f, i) => (fieldBlocks[f] = list?.c[i] ?? []));
}
// 2) Ara biçim -> Word (APA 7). Kaynakça yalnızca projedeki .bib dosyalarından alınır.
const out = path.join(work, 'cikti.docx');
const bibs = rows.filter((r) => r.path.toLowerCase().endsWith('.bib')).map((r) => `--bibliography=${path.join(work, ...r.path.split('/'))}`);
const apaAst = applyApa(ast, { front, fieldBlocks, hasBibliography: bibs.length > 0 });
const baseReference = await apaReferenceDoc((args) => runTool(PANDOC_BIN, [...PANDOC_LIMITS, ...args], { timeoutMs: 30_000 }));
// Profesyonel makalede (man) üst bilgide büyük harfle kısa başlık yer alır.
const runningHead = front && !front.student ? plainText(fieldBlocks.shorttitle).toLocaleUpperCase('tr-TR') : '';
let referenceDoc = baseReference;
if (runningHead) {
referenceDoc = path.join(work, 'sablon.docx');
await writeFile(referenceDoc, withRunningHead(await readFile(baseReference), runningHead));
}
const written = await runTool(
PANDOC_BIN,
[
...PANDOC_LIMITS, '-f', 'json', '-t', 'docx', '-o', out, `--reference-doc=${referenceDoc}`, '-M', 'lang=tr-TR',
'--syntax-highlighting=none',
...(bibs.length ? ['--citeproc', `--csl=${APA_CSL}`, ...bibs] : []),
],
{ cwd: work, input: JSON.stringify(apaAst), timeoutMs: 60_000 },
);
if (written.code !== 0 || !existsSync(out)) {
throw new HttpError(422, `Word dosyası oluşturulamadı: ${written.timedOut ? 'süre sınırı aşıldı' : written.stderr.trim().slice(0, 500)}`);
}
res.attachment(`${project.title}.docx`)
.type('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
.send(await readFile(out));
} finally {
await rm(work, { recursive: true, force: true });
}
});