latex-kit 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,10 +42,10 @@ latex-kit render letter.tex --json # machine-readable summary
42
42
  | Flag | Default | |
43
43
  |---|---|---|
44
44
  | `-o, --out <dir>` | `out` | Output directory, relative to `--root` |
45
- | `-e, --engine <name>` | `lualatex` | `lualatex`, `xelatex`, `pdflatex` |
45
+ | `-e, --engine <name>` | `lualatex` | `lualatex`, `xelatex`, `pdflatex`, `pdfps` (PSTricks) |
46
46
  | `--root <dir>` | current directory | Directory TeX can see |
47
- | `--image <ref>` | pinned `pyramation/latex` | Docker image |
48
- | `--platform <os/arch>` | `linux/amd64` for the default image | Docker `--platform` |
47
+ | `--image <ref>` | pinned `ghcr.io/constructive-io/latex-kit` (TeX Live 2026) | Docker image |
48
+ | `--platform <os/arch>` | native | Docker `--platform` |
49
49
  | `--local` | | Use `latexmk` on `PATH` instead of Docker (not pinned) |
50
50
  | `--source-date-epoch <s>` | `SOURCE_DATE_EPOCH`, else the last git commit | Build timestamp |
51
51
  | `--verify` | | Build twice; exit 1 if the PDFs differ |
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Files written by `latex-kit init` and `latex-kit new`. Every name, address
3
+ * and amount is a placeholder.
4
+ */
5
+ export type FileMap = Record<string, string>;
6
+ export declare function projectFiles(version: string): FileMap;
7
+ export declare function paperFiles(): FileMap;
8
+ export declare function templateFiles(name: string): FileMap;
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ /**
3
+ * Files written by `latex-kit init` and `latex-kit new`. Every name, address
4
+ * and amount is a placeholder.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.projectFiles = projectFiles;
8
+ exports.paperFiles = paperFiles;
9
+ exports.templateFiles = templateFiles;
10
+ function projectFiles(version) {
11
+ return {
12
+ 'package.json': `${JSON.stringify({
13
+ name: 'documents',
14
+ private: true,
15
+ scripts: {
16
+ check: 'latex-kit check',
17
+ draft: 'latex-kit build',
18
+ final: 'latex-kit build --final',
19
+ blank: 'latex-kit build --variant blank',
20
+ typegen: 'latex-kit typegen',
21
+ },
22
+ devDependencies: { 'latex-kit': `^${version}` },
23
+ }, null, 2)}\n`,
24
+ '.gitignore': 'node_modules/\nout/\n',
25
+ 'latex-kit.config.ts': `import { defineConfig } from 'latex-kit';
26
+
27
+ export default defineConfig({
28
+ locale: 'en-US',
29
+ });
30
+ `,
31
+ 'README.md': `# Documents
32
+
33
+ Built with [latex-kit](https://github.com/constructive-io/latex-kit).
34
+
35
+ | Folder | |
36
+ |---|---|
37
+ | \`templates/<name>/template.tex\` | A real \`.tex\` file with \`\\field{…}\`, \`\\when\`, \`\\each\` |
38
+ | \`templates/<name>/schema.ts\` | The data the template needs (zod) |
39
+ | \`snippets/\` | Shared pieces: \`\\snippet{letterhead}\` |
40
+ | \`clauses/\` | Versioned clauses: \`\\clause{id}\`, \`\\clauseref{id}\` |
41
+ | \`data/\` | Shared records, used with \`{ "$ref": "orgs/my-company" }\` |
42
+ | \`documents/\` | One record per document |
43
+ | \`out/\` | Generated .tex, PDFs and manifests (not committed) |
44
+
45
+ \`\`\`bash
46
+ npx latex-kit check # no TeX needed
47
+ npx latex-kit build # drafts
48
+ npx latex-kit build --final # final PDFs; mints document IDs once
49
+ npx latex-kit new document thank-you --template letter
50
+ \`\`\`
51
+ `,
52
+ 'templates/letter/template.tex': `\\documentclass[11pt]{article}
53
+ \\usepackage{fontspec}
54
+ \\usepackage[margin=25mm]{geometry}
55
+ \\usepackage{latex-kit}
56
+ \\pagestyle{empty}
57
+ \\setlength{\\parindent}{0pt}
58
+
59
+ \\begin{document}
60
+ \\snippet{letterhead}
61
+
62
+ \\vspace{2em}
63
+ \\field{date|date:long}
64
+
65
+ \\vspace{1em}
66
+ \\field{to.name}\\\\
67
+ \\when{to.address}{\\field{to.address.line1}\\\\
68
+ \\field{to.address.city}}
69
+
70
+ \\vspace{1em}
71
+ Dear \\field{to.name},
72
+
73
+ \\field{body|paragraphs}
74
+
75
+ \\vspace{2em}
76
+ Sincerely,\\\\[3em]
77
+ \\field{from.signer.name}\\\\
78
+ \\field{from.signer.title|default:""}
79
+
80
+ \\vfill
81
+ {\\small \\docid}
82
+ \\end{document}
83
+ `,
84
+ 'templates/letter/schema.ts': `import { ISODate, Organization, Party, z } from 'latex-kit';
85
+
86
+ export const meta = { docIdPrefix: 'LTR' };
87
+
88
+ export default z.object({
89
+ date: ISODate,
90
+ from: Organization,
91
+ to: Party,
92
+ body: z.string(),
93
+ });
94
+ `,
95
+ 'snippets/letterhead.tex': `% Shared letterhead: reads \`from\` from the document's data.
96
+ \\begin{flushright}
97
+ {\\large\\bfseries \\field{from.name}}\\\\
98
+ \\field{from.address.line1}\\\\
99
+ \\field{from.address.city}
100
+ \\end{flushright}
101
+ `,
102
+ 'clauses/.gitkeep': '',
103
+ 'data/orgs/my-company.yaml': `# Your organization. Documents refer to it as { $ref: orgs/my-company }.
104
+ name: My Company, Inc.
105
+ address:
106
+ line1: 1 Example Street
107
+ city: Springfield
108
+ signer:
109
+ $ref: people/me
110
+ `,
111
+ 'data/people/me.yaml': `name: Your Name
112
+ title: Founder
113
+ `,
114
+ 'documents/welcome-letter.yaml': `template: letter
115
+ data:
116
+ date: "2026-01-15"
117
+ from:
118
+ $ref: orgs/my-company
119
+ to:
120
+ name: Jordan Example
121
+ address:
122
+ line1: 2 Sample Road
123
+ city: Anytown
124
+ body: |
125
+ Welcome aboard! This letter was built by latex-kit from
126
+ documents/welcome-letter.yaml and templates/letter/template.tex.
127
+
128
+ Run latex-kit build --final to mint its document ID.
129
+ `,
130
+ };
131
+ }
132
+ function paperFiles() {
133
+ return {
134
+ '.gitignore': 'out/\n',
135
+ 'paper/main.tex': `\\documentclass[11pt]{article}
136
+ \\usepackage{fontspec}
137
+ \\usepackage[margin=25mm]{geometry}
138
+ \\usepackage{amsmath,natbib,hyperref}
139
+
140
+ \\title{Paper Title}
141
+ \\author{Your Name}
142
+ \\date{\\today}
143
+
144
+ \\begin{document}
145
+ \\maketitle
146
+
147
+ \\begin{abstract}
148
+ One paragraph that says what the paper shows.
149
+ \\end{abstract}
150
+
151
+ \\section{Introduction}
152
+ Cite related work like this~\\citep{knuth1984}.
153
+
154
+ \\section{Results}
155
+ \\begin{equation}
156
+ e^{i\\pi} + 1 = 0
157
+ \\end{equation}
158
+
159
+ \\bibliographystyle{plainnat}
160
+ \\bibliography{refs}
161
+ \\end{document}
162
+ `,
163
+ 'paper/refs.bib': `@book{knuth1984,
164
+ author = {Donald E. Knuth},
165
+ title = {The {\\TeX}book},
166
+ publisher = {Addison-Wesley},
167
+ year = {1984}
168
+ }
169
+ `,
170
+ '.github/workflows/paper.yml': `name: Paper
171
+
172
+ on:
173
+ push:
174
+ branches: [main]
175
+ pull_request:
176
+
177
+ jobs:
178
+ pdf:
179
+ runs-on: ubuntu-latest
180
+ steps:
181
+ - uses: actions/checkout@v4
182
+ with:
183
+ fetch-depth: 0 # the build date comes from the last commit
184
+ - uses: constructive-io/latex-kit/action@v1
185
+ with:
186
+ file: paper/main.tex
187
+ verify: 'true'
188
+ `,
189
+ 'README.md': `# Paper
190
+
191
+ \`\`\`bash
192
+ npx latex-kit render paper/main.tex --verify # → out/main.pdf, byte-identical on every build
193
+ \`\`\`
194
+
195
+ CI builds the PDF on every push and attaches it to the run.
196
+ `,
197
+ };
198
+ }
199
+ function templateFiles(name) {
200
+ return {
201
+ [`templates/${name}/template.tex`]: `\\documentclass[11pt]{article}
202
+ \\usepackage{fontspec}
203
+ \\usepackage[margin=25mm]{geometry}
204
+ \\usepackage{latex-kit}
205
+
206
+ \\begin{document}
207
+ \\section*{\\field{title}}
208
+
209
+ Prepared for \\field{recipient.name} on \\field{date|date:long}.
210
+
211
+ \\docid
212
+ \\end{document}
213
+ `,
214
+ [`templates/${name}/schema.ts`]: `import { ISODate, Party, z } from 'latex-kit';
215
+
216
+ export const meta = { docIdPrefix: '${name.toUpperCase().replace(/[^A-Z0-9]+/g, '-').slice(0, 12)}' };
217
+
218
+ export default z.object({
219
+ title: z.string(),
220
+ date: ISODate,
221
+ recipient: Party,
222
+ });
223
+ `,
224
+ };
225
+ }
package/build.d.ts CHANGED
@@ -13,10 +13,16 @@ export interface BuildOptions {
13
13
  verify?: boolean;
14
14
  /** Stop after writing the .tex (no TeX run). */
15
15
  texOnly?: boolean;
16
+ /** Use this ID when the record has none, instead of minting one (for redlines). */
17
+ docIdFallback?: string;
18
+ /** Write output here instead of out/<document>/. */
19
+ outDir?: string;
16
20
  onOutput?: (chunk: string) => void;
17
21
  }
18
22
  export interface BuildResult {
19
23
  name: string;
24
+ /** The template the document uses. */
25
+ template: string;
20
26
  variant: Variant;
21
27
  tex: string;
22
28
  pdf: string | null;
package/build.js CHANGED
@@ -80,14 +80,17 @@ async function run(job) {
80
80
  template: template.name,
81
81
  allowMissing: variant === 'draft' ? !strict : undefined,
82
82
  loadSnippet,
83
+ loadClause: project.loadClause,
83
84
  });
84
85
  diagnostics.push(...evaluated.diagnostics);
85
86
  if ((0, template_1.hasErrors)(diagnostics))
86
87
  throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
87
88
  // snippets count as inputs for the build date too
88
- const finalEpoch = snippets.size ? buildEpoch([...files, ...snippets]) : { epoch, reproducible };
89
+ const clauseFiles = evaluated.clauses.map((c) => (0, path_1.resolve)(c.file));
90
+ const extra = [...snippets, ...clauseFiles];
91
+ const finalEpoch = extra.length ? buildEpoch([...files, ...extra]) : { epoch, reproducible };
89
92
  // 2. write the .tex next to latex-kit.sty
90
- const outDir = (0, path_1.join)(project.outDir, job.name);
93
+ const outDir = options.outDir ?? (0, path_1.join)(project.outDir, job.name);
91
94
  (0, fs_1.mkdirSync)(outDir, { recursive: true });
92
95
  const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
93
96
  const texPath = (0, path_1.join)(outDir, `${job_}.tex`);
@@ -97,6 +100,7 @@ async function run(job) {
97
100
  (0, fs_1.writeFileSync)((0, path_1.join)(outDir, 'latex-kit.sty'), template_1.LATEX_KIT_STY);
98
101
  const result = {
99
102
  name: job.name,
103
+ template: template.name,
100
104
  variant,
101
105
  tex: texPath,
102
106
  pdf: null,
@@ -138,10 +142,9 @@ async function run(job) {
138
142
  result.pdf = rendered.pdf;
139
143
  result.sha256 = rendered.sha256;
140
144
  if (options.verify) {
141
- const verifyDir = `${outDir}.verify`;
142
- const again = await (0, render_1.render)({ ...renderOpts, outDir: (0, path_1.relative)(project.root, verifyDir) });
145
+ // same output path: some tools (Ghostscript) hash the path into the PDF ID
146
+ const again = await (0, render_1.render)({ ...renderOpts, outDir: (0, path_1.relative)(project.root, outDir) });
143
147
  result.verified = again.sha256 === rendered.sha256;
144
- (0, fs_1.rmSync)(verifyDir, { recursive: true, force: true });
145
148
  }
146
149
  // 4. keep the ID: only after a successful final build
147
150
  if (minted && job.mintInto) {
@@ -149,7 +152,7 @@ async function run(job) {
149
152
  result.minted = true;
150
153
  }
151
154
  // 5. manifest: what went in, what came out
152
- const inputFiles = [...new Set([...files, ...snippets])].filter(fs_1.existsSync).sort();
155
+ const inputFiles = [...new Set([...files, ...extra])].filter(fs_1.existsSync).sort();
153
156
  (0, fs_1.writeFileSync)((0, path_1.join)(outDir, `${job_}.manifest.json`), JSON.stringify({
154
157
  document: job.name,
155
158
  template: template.name,
@@ -162,6 +165,7 @@ async function run(job) {
162
165
  inputs: inputFiles.map((f) => ({ file: (0, path_1.relative)(project.root, f), sha256: sha256((0, fs_1.readFileSync)(f)) })),
163
166
  tex: { file: (0, path_1.relative)(project.root, texPath), sha256: sha256(tex) },
164
167
  pdf: { file: (0, path_1.relative)(project.root, rendered.pdf), sha256: rendered.sha256 },
168
+ clauses: evaluated.clauses.map((c) => ({ id: c.id, version: c.version ?? null, file: (0, path_1.relative)(project.root, (0, path_1.resolve)(c.file)) })),
165
169
  fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
166
170
  }, null, 2) + '\n');
167
171
  return result;
@@ -185,7 +189,7 @@ async function buildDocument(project, file, options = {}) {
185
189
  diagnostics.push((0, template_1.diag)(sev, `data.${i.path}: ${i.message}`, at));
186
190
  }
187
191
  }
188
- const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId;
192
+ const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId && !options.docIdFallback;
189
193
  if (needsId && !['.json', '.yaml', '.yml'].includes((0, path_1.extname)(file).toLowerCase())) {
190
194
  const suggestion = (0, schema_1.mintDocId)({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
191
195
  diagnostics.push((0, template_1.diag)('error', `a ${variant} build needs a document ID, and latex-kit does not edit code. Add: docId: '${suggestion}'`, at));
@@ -198,7 +202,7 @@ async function buildDocument(project, file, options = {}) {
198
202
  variant,
199
203
  data,
200
204
  locale: doc.record.locale ?? template.meta.locale ?? project.config.locale,
201
- docId: doc.record.docId,
205
+ docId: doc.record.docId ?? options.docIdFallback,
202
206
  inputs: [file, ...doc.refFiles],
203
207
  diagnostics,
204
208
  options,
package/check.js CHANGED
@@ -17,7 +17,7 @@ async function checkProject(project) {
17
17
  if (!t.jsonSchema) {
18
18
  diagnostics.push((0, template_1.diag)('warning', `template ${name} has no schema.ts, so field names are not checked`, { file: t.compiled.file, line: 1, column: 1 }));
19
19
  }
20
- diagnostics.push(...(0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet }).diagnostics);
20
+ diagnostics.push(...(0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause }).diagnostics);
21
21
  }
22
22
  catch (e) {
23
23
  diagnostics.push((0, template_1.diag)('error', e.message, { file: project.rel(project.path(project.config.templates, name)), line: 1, column: 1 }));
@@ -53,6 +53,6 @@ async function checkProject(project) {
53
53
  /** Every field a template reads, including through snippets. */
54
54
  async function templateFields(project, name) {
55
55
  const t = await project.template(name);
56
- const r = (0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet });
56
+ const r = (0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause });
57
57
  return { fields: r.fields, diagnostics: r.diagnostics };
58
58
  }
package/cli.js CHANGED
@@ -1,17 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
+ const schema_1 = require("@latex-kit/schema");
4
5
  const inquirerer_1 = require("inquirerer");
6
+ const path_1 = require("path");
5
7
  const commands_1 = require("./commands");
8
+ // Project files import 'latex-kit' (and zod through it). Point those names at
9
+ // this CLI's own copies, so a project works without its own node_modules and
10
+ // every file shares one zod.
11
+ const schemaDir = (0, path_1.dirname)(require.resolve('@latex-kit/schema'));
12
+ (0, schema_1.setModuleAliases)({
13
+ 'latex-kit': __dirname,
14
+ '@latex-kit/schema': schemaDir,
15
+ zod: (0, path_1.dirname)(require.resolve('zod/package.json', { paths: [schemaDir] })),
16
+ });
6
17
  const app = new inquirerer_1.CLI(commands_1.commands, {
7
18
  noTty: !process.stdin.isTTY,
8
19
  // inquirerer answers --version itself; make it report latex-kit
9
20
  version: (0, commands_1.version)(),
10
21
  minimistOpts: {
11
22
  alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
12
- boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only'],
13
- string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template'],
14
- default: { strict: undefined },
23
+ boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only', 'force', 'schema', 'paper'],
24
+ string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template', 'name', 'against'],
25
+ default: { strict: undefined, schema: true },
15
26
  },
16
27
  });
17
28
  app.run().catch((error) => {
package/commands.js CHANGED
@@ -25,10 +25,16 @@ function version() {
25
25
  return 'unknown';
26
26
  }
27
27
  const COMMANDS = {
28
+ init: project_commands_1.initCommand,
29
+ new: project_commands_1.newCommand,
28
30
  build: project_commands_1.buildCommand,
31
+ watch: project_commands_1.watchCommand,
32
+ clean: project_commands_1.cleanCommand,
29
33
  check: project_commands_1.checkCommand,
30
34
  fields: project_commands_1.fieldsCommand,
31
35
  typegen: project_commands_1.typegenCommand,
36
+ import: project_commands_1.importCommand,
37
+ diff: project_commands_1.diffCommand,
32
38
  sty: project_commands_1.styCommand,
33
39
  render: render_1.renderCommand,
34
40
  doctor: doctor_1.doctorCommand,
package/config.d.ts CHANGED
@@ -5,6 +5,8 @@ export interface LatexKitConfig {
5
5
  templates?: string;
6
6
  /** Shared pieces for \snippet{name}. Default `snippets`. */
7
7
  snippets?: string;
8
+ /** The clause library for \\clause{id}: `<clauses>/<id>.tex`. Default `clauses`. */
9
+ clauses?: string;
8
10
  /** Shared records that references point at: `<data>/<collection>/<id>.json`. Default `data`. */
9
11
  data?: string;
10
12
  /** Document records: `<documents>/<name>.json|yaml|ts`. Default `documents`. */
@@ -18,7 +20,7 @@ export interface LatexKitConfig {
18
20
  image?: string;
19
21
  platform?: string | null;
20
22
  }
21
- export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
23
+ export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'clauses' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
22
24
  file: string | null;
23
25
  };
24
26
  export declare function defineConfig(config: LatexKitConfig): LatexKitConfig;
package/config.js CHANGED
@@ -10,7 +10,7 @@ function defineConfig(config) {
10
10
  return config;
11
11
  }
12
12
  exports.CONFIG_FILES = ['latex-kit.config.ts', 'latex-kit.config.mts', 'latex-kit.config.js', 'latex-kit.config.mjs', 'latex-kit.config.cjs', 'latex-kit.config.json'];
13
- const DEFAULTS = { templates: 'templates', snippets: 'snippets', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
13
+ const DEFAULTS = { templates: 'templates', snippets: 'snippets', clauses: 'clauses', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
14
14
  async function loadConfig(root) {
15
15
  for (const name of exports.CONFIG_FILES) {
16
16
  const file = (0, path_1.join)((0, path_1.resolve)(root), name);
package/diff.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { Engine } from '@latex-kit/render';
2
+ import { Variant } from '@latex-kit/template';
3
+ import { Project } from './project';
4
+ export interface DiffOptions {
5
+ variant?: Variant;
6
+ engine?: Engine;
7
+ backend?: 'docker' | 'local';
8
+ image?: string;
9
+ platform?: string | null;
10
+ }
11
+ export interface DiffResult {
12
+ /** The redline PDF. */
13
+ pdf: string;
14
+ /** latexdiff's marked-up .tex. */
15
+ tex: string;
16
+ old: string;
17
+ new: string;
18
+ }
19
+ /** Redline two .tex files inside the project. */
20
+ export declare function diffFiles(project: Project, oldFile: string, newFile: string, options?: DiffOptions): Promise<DiffResult>;
21
+ /**
22
+ * Redline a document against an earlier commit: build it as it was at `ref`
23
+ * (in a temporary git worktree) and as it is now, then latexdiff the two.
24
+ */
25
+ export declare function diffDocument(project: Project, file: string, ref: string, options?: DiffOptions): Promise<DiffResult>;
package/diff.js ADDED
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.diffFiles = diffFiles;
4
+ exports.diffDocument = diffDocument;
5
+ const render_1 = require("@latex-kit/render");
6
+ const template_1 = require("@latex-kit/template");
7
+ const child_process_1 = require("child_process");
8
+ const fs_1 = require("fs");
9
+ const os_1 = require("os");
10
+ const path_1 = require("path");
11
+ const build_1 = require("./build");
12
+ const project_1 = require("./project");
13
+ function git(cwd, args) {
14
+ return (0, child_process_1.execFileSync)('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
15
+ }
16
+ /** latexdiff old → new in `dir`, then render the redline. */
17
+ async function redline(project, oldTex, newTex, dir, name, texInputs, options) {
18
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
19
+ (0, fs_1.writeFileSync)((0, path_1.join)(dir, 'latex-kit.sty'), template_1.LATEX_KIT_STY);
20
+ const tex = (0, path_1.join)(dir, `${name}.tex`);
21
+ const rel = (p) => (0, path_1.relative)(project.root, p);
22
+ await (0, render_1.runLatexdiff)({ root: project.root, old: rel(oldTex), new: rel(newTex), output: rel(tex), backend: options.backend, image: options.image, platform: options.platform });
23
+ const r = await (0, render_1.render)({
24
+ file: tex,
25
+ root: project.root,
26
+ outDir: rel(dir),
27
+ engine: options.engine ?? project.config.engine ?? 'lualatex',
28
+ backend: options.backend ?? project.config.backend,
29
+ image: options.image ?? project.config.image,
30
+ platform: options.platform !== undefined ? options.platform : project.config.platform,
31
+ texInputs: [rel(dir), ...texInputs.map(rel)],
32
+ });
33
+ return { pdf: r.pdf, tex, old: oldTex, new: newTex };
34
+ }
35
+ /** Redline two .tex files inside the project. */
36
+ async function diffFiles(project, oldFile, newFile, options = {}) {
37
+ for (const f of [oldFile, newFile])
38
+ if (!(0, fs_1.existsSync)(f))
39
+ throw new Error(`no such file: ${project.rel(f)}`);
40
+ const name = `${(0, path_1.basename)(newFile, '.tex')}-vs-${(0, path_1.basename)(oldFile, '.tex')}`;
41
+ const dir = (0, path_1.join)(project.outDir, 'diff', name);
42
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
43
+ // copies inside out/, so the files are always visible to Docker
44
+ const oldCopy = (0, path_1.join)(dir, 'old.tex');
45
+ const newCopy = (0, path_1.join)(dir, 'new.tex');
46
+ (0, fs_1.copyFileSync)(oldFile, oldCopy);
47
+ (0, fs_1.copyFileSync)(newFile, newCopy);
48
+ return redline(project, oldCopy, newCopy, dir, name, [(0, path_1.dirname)(newFile)], options);
49
+ }
50
+ /**
51
+ * Redline a document against an earlier commit: build it as it was at `ref`
52
+ * (in a temporary git worktree) and as it is now, then latexdiff the two.
53
+ */
54
+ async function diffDocument(project, file, ref, options = {}) {
55
+ const variant = options.variant ?? 'final';
56
+ let top;
57
+ try {
58
+ top = git(project.root, ['rev-parse', '--show-toplevel']);
59
+ }
60
+ catch {
61
+ throw new Error('diff --against needs the project to be in a git repository');
62
+ }
63
+ const relDoc = (0, path_1.relative)(top, file);
64
+ const relProject = (0, path_1.relative)(top, project.root);
65
+ let sha;
66
+ try {
67
+ sha = git(top, ['rev-parse', '--short', `${ref}^{commit}`]);
68
+ }
69
+ catch {
70
+ throw new Error(`unknown git ref: ${ref}`);
71
+ }
72
+ try {
73
+ git(top, ['cat-file', '-e', `${sha}:${relDoc}`]);
74
+ }
75
+ catch {
76
+ throw new Error(`${relDoc} does not exist at ${ref}`);
77
+ }
78
+ const name = project.documentName(file);
79
+ const dir = (0, path_1.join)(project.outDir, name, 'diff');
80
+ const common = { variant, texOnly: true, strict: false, docIdFallback: 'UNASSIGNED' };
81
+ const current = await (0, build_1.buildDocument)(project, file, { ...common, outDir: (0, path_1.join)(dir, 'new') }).catch((e) => {
82
+ if (e instanceof build_1.BuildError)
83
+ throw new build_1.BuildError(`the current ${name} does not build: ${e.message}`, e.diagnostics);
84
+ throw e;
85
+ });
86
+ const tree = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), 'latex-kit-diff-'));
87
+ try {
88
+ git(top, ['worktree', 'add', '--detach', '--quiet', tree, sha]);
89
+ const oldProject = await project_1.Project.open((0, path_1.join)(tree, relProject));
90
+ const old = await (0, build_1.buildDocument)(oldProject, (0, path_1.join)(tree, relDoc), { ...common, outDir: (0, path_1.join)(dir, 'old') }).catch((e) => {
91
+ if (e instanceof build_1.BuildError)
92
+ throw new build_1.BuildError(`${name} at ${ref} (${sha}) does not build: ${e.message}`, e.diagnostics);
93
+ throw e;
94
+ });
95
+ const template = await project.template(current.template);
96
+ return await redline(project, old.tex, current.tex, dir, `${name}-vs-${sha}`, [template.dir], options);
97
+ }
98
+ finally {
99
+ try {
100
+ git(top, ['worktree', 'remove', '--force', tree]);
101
+ }
102
+ catch {
103
+ (0, fs_1.rmSync)(tree, { recursive: true, force: true });
104
+ try {
105
+ git(top, ['worktree', 'prune']);
106
+ }
107
+ catch {
108
+ // nothing left to clean
109
+ }
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Files written by `latex-kit init` and `latex-kit new`. Every name, address
3
+ * and amount is a placeholder.
4
+ */
5
+ export type FileMap = Record<string, string>;
6
+ export declare function projectFiles(version: string): FileMap;
7
+ export declare function paperFiles(): FileMap;
8
+ export declare function templateFiles(name: string): FileMap;