File size: 11,567 Bytes
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a51f94
f41aded
4a51f94
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// 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 });
  }
});