-
-
Notifications
You must be signed in to change notification settings - Fork 11.2k
Expand file tree
/
Copy pathgenerate-latex.mjs
More file actions
235 lines (203 loc) · 7.03 KB
/
Copy pathgenerate-latex.mjs
File metadata and controls
235 lines (203 loc) · 7.03 KB
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
#!/usr/bin/env node
/**
* generate-latex.mjs — Validate and compile a generated .tex CV file to PDF
*
* Usage:
* node generate-latex.mjs <input.tex> [output.pdf]
*
* Reads the .tex file, validates structure, compiles to PDF via tectonic or pdflatex.
* If output.pdf is omitted, writes to the same directory as input with .pdf extension.
* The .tex file is generated by the AI agent using templates/cv-template.tex.
*
* Requires: tectonic (preferred, brew install tectonic) or pdflatex (MiKTeX / TeX Live) on PATH.
*/
import { readFile, writeFile, stat, copyFile, rm } from 'fs/promises';
import { resolve, basename, dirname, join } from 'path';
import { execFileSync } from 'child_process';
import { existsSync, mkdirSync } from 'fs';
const REQUIRED_SECTIONS = [
'\\\\section{Education}',
'\\\\section{Experience}',
'\\\\section{Projects}',
'\\\\section{Technical Skills}',
];
const REQUIRED_COMMANDS = [
'\\\\resumeSubheading',
'\\\\resumeItem',
'\\\\resumeProjectHeading',
];
async function main() {
const inputPath = process.argv[2];
const outputPath = process.argv[3]; // optional
if (!inputPath) {
console.error('Usage: node generate-latex.mjs <input.tex> [output.pdf]');
process.exit(1);
}
const absPath = resolve(inputPath);
let content;
try {
content = await readFile(absPath, 'utf-8');
} catch (err) {
console.error(`Error reading ${absPath}: ${err.message}`);
process.exit(1);
}
const issues = [];
// Check required sections
for (const pattern of REQUIRED_SECTIONS) {
if (!new RegExp(pattern).test(content)) {
issues.push(`Missing section matching: ${pattern}`);
}
}
// Check required commands are used
for (const cmd of REQUIRED_COMMANDS) {
if (!new RegExp(cmd).test(content)) {
issues.push(`Missing command: ${cmd}`);
}
}
// Check document structure
if (!content.includes('\\begin{document}')) {
issues.push('Missing \\begin{document}');
}
if (!content.includes('\\end{document}')) {
issues.push('Missing \\end{document}');
}
// Check for unresolved placeholders
const unresolvedMatch = content.match(/\{\{[A-Z_]+\}\}/g);
if (unresolvedMatch) {
issues.push(`Unresolved placeholders: ${[...new Set(unresolvedMatch)].join(', ')}`);
}
// Check for common unescaped special chars in text (heuristic)
const lines = content.split('\n');
let resumeItemCount = 0;
let subheadingCount = 0;
let projectHeadingCount = 0;
for (const line of lines) {
if (/\\resumeItem\{/.test(line)) resumeItemCount++;
if (/\\resumeSubheading[^C]/.test(line)) subheadingCount++;
if (/\\resumeProjectHeading/.test(line)) projectHeadingCount++;
}
// Check pdfgentounicode (accept bare form or wrapped in \ifpdf)
if (!content.includes('\\pdfgentounicode=1')) {
issues.push('Missing \\pdfgentounicode=1 (ATS compatibility — wrap in \\ifpdf...\\fi for tectonic/XeLaTeX compatibility)');
}
const fileInfo = await stat(absPath);
const sizeKB = (fileInfo.size / 1024).toFixed(1);
// Output report as JSON
const report = {
file: basename(absPath),
path: absPath,
sizeKB: parseFloat(sizeKB),
counts: {
resumeItems: resumeItemCount,
subheadings: subheadingCount,
projectHeadings: projectHeadingCount,
},
issues,
valid: issues.length === 0,
};
// If validation fails, report and exit
if (issues.length > 0) {
console.log(JSON.stringify(report, null, 2));
process.exit(1);
}
// --- Compile .tex → .pdf ---
const texDir = dirname(absPath);
const texBase = basename(absPath, '.tex');
const defaultPdf = join(texDir, `${texBase}.pdf`);
const targetPdf = outputPath ? resolve(outputPath) : defaultPdf;
// Ensure output directory exists
const targetDir = dirname(targetPdf);
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
// Detect available engine: prefer tectonic, fall back to pdflatex
let engine = null;
for (const candidate of ['tectonic', 'pdflatex']) {
try {
execFileSync(candidate, ['--version'], { stdio: 'pipe' });
engine = candidate;
break;
} catch { /* not found */ }
}
if (!engine) {
report.compiled = false;
report.compileError = 'No LaTeX engine found. Install tectonic (brew install tectonic) or pdflatex.';
console.log(JSON.stringify(report, null, 2));
process.exit(1);
}
report.engine = engine;
// For tectonic: strip pdflatex-only primitives that cause crashes
let compilePath = absPath;
if (engine === 'tectonic') {
const patched = content
.replace(/\\pdfgentounicode\s*=\s*\d+[^\n]*\n?/g, '')
.replace(/\\input\{glyphtounicode\}[^\n]*\n?/g, '');
compilePath = join(texDir, `${texBase}._tectonic.tex`);
await writeFile(compilePath, patched, 'utf-8');
}
try {
if (engine === 'tectonic') {
// Tectonic handles multi-pass automatically; --outdir sets output location
execFileSync('tectonic', ['--outdir', texDir, compilePath], {
cwd: texDir,
stdio: 'pipe',
timeout: 120_000,
});
} else {
const pdflatexArgs = [
'-no-shell-escape',
'-interaction=nonstopmode',
'-halt-on-error',
`-output-directory=${texDir}`,
absPath,
];
// First pass
execFileSync('pdflatex', pdflatexArgs, { cwd: texDir, stdio: 'pipe', timeout: 120_000 });
// Second pass (resolves references)
execFileSync('pdflatex', pdflatexArgs, { cwd: texDir, stdio: 'pipe', timeout: 120_000 });
}
report.compiled = true;
} catch (err) {
const logPath = join(texDir, `${texBase}.log`);
let latexError = err.message;
try {
const log = await readFile(logPath, 'utf-8');
const errorLines = log.split('\n').filter(l => l.startsWith('!'));
if (errorLines.length > 0) {
latexError = errorLines.join('\n');
}
} catch { /* no log file */ }
report.compiled = false;
report.compileError = latexError;
}
// Post-compile: move PDF and clean up (separate from compile errors)
if (report.compiled) {
// Tectonic outputs PDF named after the patched temp file
const compileBase = basename(compilePath, '.tex');
const compiledPdf = join(texDir, `${compileBase}.pdf`);
try {
await copyFile(compiledPdf, targetPdf);
if (resolve(compiledPdf) !== resolve(targetPdf)) {
await rm(compiledPdf).catch(() => {});
}
const pdfStat = await stat(targetPdf);
report.pdf = {
path: targetPdf,
sizeKB: parseFloat((pdfStat.size / 1024).toFixed(1)),
};
} catch (err) {
report.postCompileError = `Failed to finalize PDF: ${err.message}`;
}
// Clean up auxiliary files and tectonic temp .tex (best-effort)
const auxExts = ['.aux', '.log', '.out', '.fls', '.fdb_latexmk', '.synctex.gz'];
for (const ext of auxExts) {
await rm(join(texDir, `${compileBase}${ext}`)).catch(() => {});
}
if (engine === 'tectonic') {
await rm(compilePath).catch(() => {});
}
}
console.log(JSON.stringify(report, null, 2));
process.exit(report.compiled ? 0 : 1);
}
main();