latex-kit 0.2.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.
Files changed (54) hide show
  1. package/README.md +3 -3
  2. package/boilerplates.d.ts +8 -0
  3. package/boilerplates.js +225 -0
  4. package/build.d.ts +45 -0
  5. package/build.js +226 -0
  6. package/check.d.ts +17 -0
  7. package/check.js +58 -0
  8. package/cli.d.ts +2 -0
  9. package/cli.js +31 -0
  10. package/commands.d.ts +1 -0
  11. package/commands.js +51 -15
  12. package/config.d.ts +28 -0
  13. package/config.js +30 -0
  14. package/diff.d.ts +25 -0
  15. package/diff.js +112 -0
  16. package/esm/boilerplates.d.ts +8 -0
  17. package/esm/boilerplates.js +220 -0
  18. package/esm/build.d.ts +45 -0
  19. package/esm/build.js +220 -0
  20. package/esm/check.d.ts +17 -0
  21. package/esm/check.js +54 -0
  22. package/esm/cli.d.ts +2 -0
  23. package/esm/cli.js +29 -0
  24. package/esm/commands.d.ts +1 -0
  25. package/esm/commands.js +49 -16
  26. package/esm/config.d.ts +28 -0
  27. package/esm/config.js +25 -0
  28. package/esm/diff.d.ts +25 -0
  29. package/esm/diff.js +108 -0
  30. package/esm/import.d.ts +24 -0
  31. package/esm/import.js +113 -0
  32. package/esm/index.d.ts +15 -2
  33. package/esm/index.js +15 -15
  34. package/esm/project-commands.d.ts +16 -0
  35. package/esm/project-commands.js +324 -0
  36. package/esm/project.d.ts +46 -0
  37. package/esm/project.js +139 -0
  38. package/esm/render.js +3 -5
  39. package/esm/scaffold.d.ts +27 -0
  40. package/esm/scaffold.js +108 -0
  41. package/esm/usage.js +53 -6
  42. package/import.d.ts +24 -0
  43. package/import.js +118 -0
  44. package/index.d.ts +15 -2
  45. package/index.js +29 -15
  46. package/package.json +8 -6
  47. package/project-commands.d.ts +16 -0
  48. package/project-commands.js +340 -0
  49. package/project.d.ts +46 -0
  50. package/project.js +143 -0
  51. package/render.js +2 -4
  52. package/scaffold.d.ts +27 -0
  53. package/scaffold.js +115 -0
  54. package/usage.js +53 -6
package/esm/build.js ADDED
@@ -0,0 +1,220 @@
1
+ import { gitCommitTime, render, RenderError } from '@latex-kit/render';
2
+ import { loadDocument, mintDocId, validate, writeDocId } from '@latex-kit/schema';
3
+ import { diag, evaluateTemplate, hasErrors, LATEX_KIT_STY, wrapDocument, } from '@latex-kit/template';
4
+ import { execFileSync } from 'child_process';
5
+ import { createHash } from 'crypto';
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
7
+ import { basename, extname, join, relative, resolve } from 'path';
8
+ export class BuildError extends Error {
9
+ diagnostics;
10
+ constructor(message, diagnostics) {
11
+ super(message);
12
+ this.diagnostics = diagnostics;
13
+ this.name = 'BuildError';
14
+ }
15
+ }
16
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
17
+ function isCI() {
18
+ return process.env.CI === 'true' || process.env.CI === '1';
19
+ }
20
+ /**
21
+ * The build date: SOURCE_DATE_EPOCH if set, else the newest commit among
22
+ * every input file. Same commit → same date → same PDF bytes.
23
+ */
24
+ function buildEpoch(files) {
25
+ const env = process.env.SOURCE_DATE_EPOCH;
26
+ if (env && /^\d+$/.test(env.trim()))
27
+ return { epoch: Number(env.trim()), reproducible: true };
28
+ let newest = -1;
29
+ let allCommitted = true;
30
+ for (const f of files) {
31
+ const t = gitCommitTime(f);
32
+ if (t && /^\d+$/.test(t))
33
+ newest = Math.max(newest, Number(t));
34
+ else
35
+ allCommitted = false;
36
+ }
37
+ if (newest < 0)
38
+ return { epoch: Math.floor(Date.now() / 1000), reproducible: false };
39
+ return { epoch: newest, reproducible: allCommitted };
40
+ }
41
+ function gitShortHead(cwd) {
42
+ try {
43
+ return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
44
+ }
45
+ catch {
46
+ return 'no-git';
47
+ }
48
+ }
49
+ async function run(job) {
50
+ const { project, template, variant, options } = job;
51
+ const diagnostics = job.diagnostics;
52
+ // 1. fill the template
53
+ const snippets = new Set();
54
+ const loadSnippet = (name, from) => {
55
+ const s = project.loadSnippet(name, from);
56
+ if (s)
57
+ snippets.add(resolve(s.file));
58
+ return s;
59
+ };
60
+ const strict = options.strict ?? isCI();
61
+ const files = [...job.inputs, template.texFile, ...(template.schemaFile ? [template.schemaFile] : [])];
62
+ const { epoch, reproducible } = buildEpoch(files);
63
+ let docId = job.docId;
64
+ let minted = false;
65
+ if (!docId && job.mintInto) {
66
+ docId = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
67
+ minted = true;
68
+ }
69
+ const evaluated = evaluateTemplate(template.compiled, {
70
+ data: job.data,
71
+ variant,
72
+ locale: job.locale,
73
+ docId,
74
+ template: template.name,
75
+ allowMissing: variant === 'draft' ? !strict : undefined,
76
+ loadSnippet,
77
+ loadClause: project.loadClause,
78
+ });
79
+ diagnostics.push(...evaluated.diagnostics);
80
+ if (hasErrors(diagnostics))
81
+ throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
82
+ // snippets count as inputs for the build date too
83
+ const clauseFiles = evaluated.clauses.map((c) => resolve(c.file));
84
+ const extra = [...snippets, ...clauseFiles];
85
+ const finalEpoch = extra.length ? buildEpoch([...files, ...extra]) : { epoch, reproducible };
86
+ // 2. write the .tex next to latex-kit.sty
87
+ const outDir = options.outDir ?? join(project.outDir, job.name);
88
+ mkdirSync(outDir, { recursive: true });
89
+ const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
90
+ const texPath = join(outDir, `${job_}.tex`);
91
+ const stamp = `${new Date(finalEpoch.epoch * 1000).toISOString().slice(0, 10)} ${gitShortHead(project.root)}`;
92
+ const tex = wrapDocument(evaluated.tex, { variant, stamp });
93
+ writeFileSync(texPath, tex);
94
+ writeFileSync(join(outDir, 'latex-kit.sty'), LATEX_KIT_STY);
95
+ const result = {
96
+ name: job.name,
97
+ template: template.name,
98
+ variant,
99
+ tex: texPath,
100
+ pdf: null,
101
+ sha256: null,
102
+ docId: docId ?? null,
103
+ minted: false,
104
+ sourceDateEpoch: finalEpoch.epoch,
105
+ reproducible: finalEpoch.reproducible,
106
+ diagnostics,
107
+ };
108
+ if (options.texOnly)
109
+ return result;
110
+ // 3. render
111
+ const engine = options.engine ?? template.meta.engine ?? project.config.engine ?? 'lualatex';
112
+ const renderOpts = {
113
+ file: texPath,
114
+ root: project.root,
115
+ engine,
116
+ backend: options.backend ?? project.config.backend,
117
+ image: options.image ?? project.config.image,
118
+ platform: options.platform !== undefined ? options.platform : project.config.platform,
119
+ sourceDateEpoch: finalEpoch.epoch,
120
+ texInputs: [relative(project.root, outDir) || '.', relative(project.root, template.dir) || '.'],
121
+ onOutput: options.onOutput,
122
+ };
123
+ let rendered;
124
+ try {
125
+ rendered = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
126
+ }
127
+ catch (e) {
128
+ if (e instanceof RenderError) {
129
+ throw new BuildError(`${job.name}: ${e.message}`, [
130
+ ...diagnostics,
131
+ ...e.diagnostics.map((d) => diag(d.severity, d.message, d.file ? { file: project.rel(join(outDir, basename(d.file))), line: d.line ?? 0, column: 0 } : undefined)),
132
+ ]);
133
+ }
134
+ throw e;
135
+ }
136
+ result.pdf = rendered.pdf;
137
+ result.sha256 = rendered.sha256;
138
+ if (options.verify) {
139
+ // same output path: some tools (Ghostscript) hash the path into the PDF ID
140
+ const again = await render({ ...renderOpts, outDir: relative(project.root, outDir) });
141
+ result.verified = again.sha256 === rendered.sha256;
142
+ }
143
+ // 4. keep the ID: only after a successful final build
144
+ if (minted && job.mintInto) {
145
+ writeDocId(job.mintInto, docId);
146
+ result.minted = true;
147
+ }
148
+ // 5. manifest: what went in, what came out
149
+ const inputFiles = [...new Set([...files, ...extra])].filter(existsSync).sort();
150
+ writeFileSync(join(outDir, `${job_}.manifest.json`), JSON.stringify({
151
+ document: job.name,
152
+ template: template.name,
153
+ variant,
154
+ docId: docId ?? null,
155
+ locale: job.locale,
156
+ engine,
157
+ image: rendered.image,
158
+ sourceDateEpoch: finalEpoch.epoch,
159
+ inputs: inputFiles.map((f) => ({ file: relative(project.root, f), sha256: sha256(readFileSync(f)) })),
160
+ tex: { file: relative(project.root, texPath), sha256: sha256(tex) },
161
+ pdf: { file: relative(project.root, rendered.pdf), sha256: rendered.sha256 },
162
+ clauses: evaluated.clauses.map((c) => ({ id: c.id, version: c.version ?? null, file: relative(project.root, resolve(c.file)) })),
163
+ fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
164
+ }, null, 2) + '\n');
165
+ return result;
166
+ }
167
+ /** Build one document record. */
168
+ export async function buildDocument(project, file, options = {}) {
169
+ const variant = options.variant ?? 'draft';
170
+ const diagnostics = [];
171
+ const doc = await loadDocument(file, { dataDir: project.dataDir });
172
+ const template = await project.template(doc.record.template);
173
+ const at = { file: project.rel(file), line: 1, column: 1 };
174
+ let data = doc.data;
175
+ if (template.schema) {
176
+ const v = validate(template.schema, doc.data);
177
+ if (v.ok) {
178
+ data = v.value;
179
+ }
180
+ else {
181
+ const sev = variant === 'final' || variant === 'signed' ? 'error' : 'warning';
182
+ for (const i of v.issues)
183
+ diagnostics.push(diag(sev, `data.${i.path}: ${i.message}`, at));
184
+ }
185
+ }
186
+ const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId && !options.docIdFallback;
187
+ if (needsId && !['.json', '.yaml', '.yml'].includes(extname(file).toLowerCase())) {
188
+ const suggestion = mintDocId({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
189
+ diagnostics.push(diag('error', `a ${variant} build needs a document ID, and latex-kit does not edit code. Add: docId: '${suggestion}'`, at));
190
+ throw new BuildError(`${doc.record.template}: no document ID`, diagnostics);
191
+ }
192
+ return run({
193
+ project,
194
+ template,
195
+ name: project.documentName(file),
196
+ variant,
197
+ data,
198
+ locale: doc.record.locale ?? template.meta.locale ?? project.config.locale,
199
+ docId: doc.record.docId ?? options.docIdFallback,
200
+ inputs: [file, ...doc.refFiles],
201
+ diagnostics,
202
+ options,
203
+ mintInto: needsId ? file : undefined,
204
+ });
205
+ }
206
+ /** Build a template as a blank form, without a record. */
207
+ export async function buildBlank(project, templateName, options = {}) {
208
+ const template = await project.template(templateName);
209
+ return run({
210
+ project,
211
+ template,
212
+ name: `${templateName}`,
213
+ variant: 'blank',
214
+ data: {},
215
+ locale: template.meta.locale ?? project.config.locale,
216
+ inputs: [],
217
+ diagnostics: [],
218
+ options: { ...options, variant: 'blank' },
219
+ });
220
+ }
package/esm/check.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { Diagnostic, FieldRef } from '@latex-kit/template';
2
+ import { Project } from './project';
3
+ export interface CheckResult {
4
+ diagnostics: Diagnostic[];
5
+ templates: string[];
6
+ documents: string[];
7
+ }
8
+ /**
9
+ * Everything that can be checked without TeX: template syntax, field names
10
+ * against each schema, every document's data, references, and duplicate IDs.
11
+ */
12
+ export declare function checkProject(project: Project): Promise<CheckResult>;
13
+ /** Every field a template reads, including through snippets. */
14
+ export declare function templateFields(project: Project, name: string): Promise<{
15
+ fields: FieldRef[];
16
+ diagnostics: Diagnostic[];
17
+ }>;
package/esm/check.js ADDED
@@ -0,0 +1,54 @@
1
+ import { loadDocument, validate } from '@latex-kit/schema';
2
+ import { analyzeTemplate, diag } from '@latex-kit/template';
3
+ /**
4
+ * Everything that can be checked without TeX: template syntax, field names
5
+ * against each schema, every document's data, references, and duplicate IDs.
6
+ */
7
+ export async function checkProject(project) {
8
+ const diagnostics = [];
9
+ const templates = project.templateNames();
10
+ for (const name of templates) {
11
+ try {
12
+ const t = await project.template(name);
13
+ if (!t.jsonSchema) {
14
+ diagnostics.push(diag('warning', `template ${name} has no schema.ts, so field names are not checked`, { file: t.compiled.file, line: 1, column: 1 }));
15
+ }
16
+ diagnostics.push(...analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause }).diagnostics);
17
+ }
18
+ catch (e) {
19
+ diagnostics.push(diag('error', e.message, { file: project.rel(project.path(project.config.templates, name)), line: 1, column: 1 }));
20
+ }
21
+ }
22
+ const files = project.documentFiles();
23
+ const ids = new Map();
24
+ for (const file of files) {
25
+ const at = { file: project.rel(file), line: 1, column: 1 };
26
+ try {
27
+ const doc = await loadDocument(file, { dataDir: project.dataDir });
28
+ if (doc.record.docId) {
29
+ const prev = ids.get(doc.record.docId);
30
+ if (prev)
31
+ diagnostics.push(diag('error', `document ID ${doc.record.docId} is also used by ${prev}; never reuse an ID`, at));
32
+ else
33
+ ids.set(doc.record.docId, project.rel(file));
34
+ }
35
+ const t = await project.template(doc.record.template);
36
+ if (t.schema) {
37
+ const v = validate(t.schema, doc.data);
38
+ if (!v.ok)
39
+ for (const i of v.issues)
40
+ diagnostics.push(diag('error', `data.${i.path}: ${i.message}`, at));
41
+ }
42
+ }
43
+ catch (e) {
44
+ diagnostics.push(diag('error', e.message.replace(`${file}: `, ''), at));
45
+ }
46
+ }
47
+ return { diagnostics, templates, documents: files.map((f) => project.rel(f)) };
48
+ }
49
+ /** Every field a template reads, including through snippets. */
50
+ export async function templateFields(project, name) {
51
+ const t = await project.template(name);
52
+ const r = analyzeTemplate(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause });
53
+ return { fields: r.fields, diagnostics: r.diagnostics };
54
+ }
package/esm/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/esm/cli.js ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ import { setModuleAliases } from '@latex-kit/schema';
3
+ import { CLI } from 'inquirerer';
4
+ import { dirname } from 'path';
5
+ import { commands, version } from './commands';
6
+ // Project files import 'latex-kit' (and zod through it). Point those names at
7
+ // this CLI's own copies, so a project works without its own node_modules and
8
+ // every file shares one zod.
9
+ const schemaDir = dirname(require.resolve('@latex-kit/schema'));
10
+ setModuleAliases({
11
+ 'latex-kit': __dirname,
12
+ '@latex-kit/schema': schemaDir,
13
+ zod: dirname(require.resolve('zod/package.json', { paths: [schemaDir] })),
14
+ });
15
+ const app = new CLI(commands, {
16
+ noTty: !process.stdin.isTTY,
17
+ // inquirerer answers --version itself; make it report latex-kit
18
+ version: version(),
19
+ minimistOpts: {
20
+ alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
21
+ boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only', 'force', 'schema', 'paper'],
22
+ string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template', 'name', 'against'],
23
+ default: { strict: undefined, schema: true },
24
+ },
25
+ });
26
+ app.run().catch((error) => {
27
+ console.error(error instanceof Error ? error.message : error);
28
+ process.exit(1);
29
+ });
package/esm/commands.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { CLIOptions, Inquirerer } from 'inquirerer';
2
2
  import type { ParsedArgs } from 'minimist';
3
+ /** The package version, from package.json next to the built files. */
3
4
  export declare function version(): string;
4
5
  export declare const commands: (argv: Partial<ParsedArgs>, prompter: Inquirerer, _options: CLIOptions) => Promise<Partial<ParsedArgs>>;
package/esm/commands.js CHANGED
@@ -1,10 +1,37 @@
1
- import { readFileSync } from 'fs';
1
+ import { existsSync, readFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import chalk from 'yanse';
4
+ import { UsageError } from './args';
2
5
  import { doctorCommand } from './doctor';
6
+ import { buildCommand, checkCommand, cleanCommand, diffCommand, fieldsCommand, importCommand, initCommand, newCommand, styCommand, typegenCommand, watchCommand } from './project-commands';
3
7
  import { renderCommand } from './render';
4
8
  import { help } from './usage';
9
+ /** The package version, from package.json next to the built files. */
5
10
  export function version() {
6
- return JSON.parse(readFileSync(require.resolve('../package.json'), 'utf8')).version;
11
+ for (const p of [join(__dirname, 'package.json'), join(__dirname, '..', 'package.json')]) {
12
+ if (existsSync(p)) {
13
+ const pkg = JSON.parse(readFileSync(p, 'utf8'));
14
+ if (pkg.name === 'latex-kit')
15
+ return pkg.version;
16
+ }
17
+ }
18
+ return 'unknown';
7
19
  }
20
+ const COMMANDS = {
21
+ init: initCommand,
22
+ new: newCommand,
23
+ build: buildCommand,
24
+ watch: watchCommand,
25
+ clean: cleanCommand,
26
+ check: checkCommand,
27
+ fields: fieldsCommand,
28
+ typegen: typegenCommand,
29
+ import: importCommand,
30
+ diff: diffCommand,
31
+ sty: styCommand,
32
+ render: renderCommand,
33
+ doctor: doctorCommand,
34
+ };
8
35
  export const commands = async (argv, prompter, _options) => {
9
36
  const [command, ...rest] = (argv._ ?? []).map(String);
10
37
  if (argv.version) {
@@ -15,20 +42,26 @@ export const commands = async (argv, prompter, _options) => {
15
42
  help(command === 'help' ? rest[0] : argv.help ? command : undefined);
16
43
  return argv;
17
44
  }
18
- let code;
19
- switch (command) {
20
- case 'render':
21
- code = await renderCommand({ ...argv, _: rest }, prompter);
22
- break;
23
- case 'doctor':
24
- code = await doctorCommand({ ...argv, _: rest });
25
- break;
26
- default:
27
- console.error(`unknown command: ${command}\n`);
28
- help();
29
- code = 2;
45
+ const run = COMMANDS[command];
46
+ if (!run) {
47
+ console.error(`unknown command: ${command}\n`);
48
+ help();
49
+ process.exitCode = 2;
50
+ return argv;
51
+ }
52
+ try {
53
+ const code = await run({ ...argv, _: rest }, prompter);
54
+ if (code !== 0)
55
+ process.exitCode = code;
56
+ }
57
+ catch (e) {
58
+ if (e instanceof UsageError) {
59
+ console.error(chalk.red(e.message));
60
+ process.exitCode = 2;
61
+ }
62
+ else {
63
+ throw e;
64
+ }
30
65
  }
31
- if (code !== 0)
32
- process.exitCode = code;
33
66
  return argv;
34
67
  };
@@ -0,0 +1,28 @@
1
+ import type { Backend, Engine } from '@latex-kit/render';
2
+ /** latex-kit.config.ts (or .js, .mjs, .cjs, .json) at the project root. */
3
+ export interface LatexKitConfig {
4
+ /** One folder per template: `<templates>/<name>/template.tex` and optional `schema.ts`. Default `templates`. */
5
+ templates?: string;
6
+ /** Shared pieces for \snippet{name}. Default `snippets`. */
7
+ snippets?: string;
8
+ /** The clause library for \\clause{id}: `<clauses>/<id>.tex`. Default `clauses`. */
9
+ clauses?: string;
10
+ /** Shared records that references point at: `<data>/<collection>/<id>.json`. Default `data`. */
11
+ data?: string;
12
+ /** Document records: `<documents>/<name>.json|yaml|ts`. Default `documents`. */
13
+ documents?: string;
14
+ /** Generated .tex and PDFs. Default `out`. */
15
+ out?: string;
16
+ /** Default locale for dates, numbers and money. Default `en-US`. */
17
+ locale?: string;
18
+ engine?: Engine;
19
+ backend?: Backend;
20
+ image?: string;
21
+ platform?: string | null;
22
+ }
23
+ export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'clauses' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
24
+ file: string | null;
25
+ };
26
+ export declare function defineConfig(config: LatexKitConfig): LatexKitConfig;
27
+ export declare const CONFIG_FILES: string[];
28
+ export declare function loadConfig(root: string): Promise<ResolvedConfig>;
package/esm/config.js ADDED
@@ -0,0 +1,25 @@
1
+ import { loadModule } from '@latex-kit/schema';
2
+ import { existsSync, readFileSync } from 'fs';
3
+ import { join, resolve } from 'path';
4
+ export function defineConfig(config) {
5
+ return config;
6
+ }
7
+ export const 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'];
8
+ const DEFAULTS = { templates: 'templates', snippets: 'snippets', clauses: 'clauses', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
9
+ export async function loadConfig(root) {
10
+ for (const name of CONFIG_FILES) {
11
+ const file = join(resolve(root), name);
12
+ if (!existsSync(file))
13
+ continue;
14
+ let config;
15
+ if (name.endsWith('.json')) {
16
+ config = JSON.parse(readFileSync(file, 'utf8'));
17
+ }
18
+ else {
19
+ const mod = await loadModule(file);
20
+ config = (mod.default ?? mod);
21
+ }
22
+ return { ...DEFAULTS, ...config, file };
23
+ }
24
+ return { ...DEFAULTS, file: null };
25
+ }
package/esm/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/esm/diff.js ADDED
@@ -0,0 +1,108 @@
1
+ import { render, runLatexdiff } from '@latex-kit/render';
2
+ import { LATEX_KIT_STY } from '@latex-kit/template';
3
+ import { execFileSync } from 'child_process';
4
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
5
+ import { tmpdir } from 'os';
6
+ import { basename, dirname, join, relative } from 'path';
7
+ import { buildDocument, BuildError } from './build';
8
+ import { Project } from './project';
9
+ function git(cwd, args) {
10
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
11
+ }
12
+ /** latexdiff old → new in `dir`, then render the redline. */
13
+ async function redline(project, oldTex, newTex, dir, name, texInputs, options) {
14
+ mkdirSync(dir, { recursive: true });
15
+ writeFileSync(join(dir, 'latex-kit.sty'), LATEX_KIT_STY);
16
+ const tex = join(dir, `${name}.tex`);
17
+ const rel = (p) => relative(project.root, p);
18
+ await runLatexdiff({ root: project.root, old: rel(oldTex), new: rel(newTex), output: rel(tex), backend: options.backend, image: options.image, platform: options.platform });
19
+ const r = await render({
20
+ file: tex,
21
+ root: project.root,
22
+ outDir: rel(dir),
23
+ engine: options.engine ?? project.config.engine ?? 'lualatex',
24
+ backend: options.backend ?? project.config.backend,
25
+ image: options.image ?? project.config.image,
26
+ platform: options.platform !== undefined ? options.platform : project.config.platform,
27
+ texInputs: [rel(dir), ...texInputs.map(rel)],
28
+ });
29
+ return { pdf: r.pdf, tex, old: oldTex, new: newTex };
30
+ }
31
+ /** Redline two .tex files inside the project. */
32
+ export async function diffFiles(project, oldFile, newFile, options = {}) {
33
+ for (const f of [oldFile, newFile])
34
+ if (!existsSync(f))
35
+ throw new Error(`no such file: ${project.rel(f)}`);
36
+ const name = `${basename(newFile, '.tex')}-vs-${basename(oldFile, '.tex')}`;
37
+ const dir = join(project.outDir, 'diff', name);
38
+ mkdirSync(dir, { recursive: true });
39
+ // copies inside out/, so the files are always visible to Docker
40
+ const oldCopy = join(dir, 'old.tex');
41
+ const newCopy = join(dir, 'new.tex');
42
+ copyFileSync(oldFile, oldCopy);
43
+ copyFileSync(newFile, newCopy);
44
+ return redline(project, oldCopy, newCopy, dir, name, [dirname(newFile)], options);
45
+ }
46
+ /**
47
+ * Redline a document against an earlier commit: build it as it was at `ref`
48
+ * (in a temporary git worktree) and as it is now, then latexdiff the two.
49
+ */
50
+ export async function diffDocument(project, file, ref, options = {}) {
51
+ const variant = options.variant ?? 'final';
52
+ let top;
53
+ try {
54
+ top = git(project.root, ['rev-parse', '--show-toplevel']);
55
+ }
56
+ catch {
57
+ throw new Error('diff --against needs the project to be in a git repository');
58
+ }
59
+ const relDoc = relative(top, file);
60
+ const relProject = relative(top, project.root);
61
+ let sha;
62
+ try {
63
+ sha = git(top, ['rev-parse', '--short', `${ref}^{commit}`]);
64
+ }
65
+ catch {
66
+ throw new Error(`unknown git ref: ${ref}`);
67
+ }
68
+ try {
69
+ git(top, ['cat-file', '-e', `${sha}:${relDoc}`]);
70
+ }
71
+ catch {
72
+ throw new Error(`${relDoc} does not exist at ${ref}`);
73
+ }
74
+ const name = project.documentName(file);
75
+ const dir = join(project.outDir, name, 'diff');
76
+ const common = { variant, texOnly: true, strict: false, docIdFallback: 'UNASSIGNED' };
77
+ const current = await buildDocument(project, file, { ...common, outDir: join(dir, 'new') }).catch((e) => {
78
+ if (e instanceof BuildError)
79
+ throw new BuildError(`the current ${name} does not build: ${e.message}`, e.diagnostics);
80
+ throw e;
81
+ });
82
+ const tree = mkdtempSync(join(tmpdir(), 'latex-kit-diff-'));
83
+ try {
84
+ git(top, ['worktree', 'add', '--detach', '--quiet', tree, sha]);
85
+ const oldProject = await Project.open(join(tree, relProject));
86
+ const old = await buildDocument(oldProject, join(tree, relDoc), { ...common, outDir: join(dir, 'old') }).catch((e) => {
87
+ if (e instanceof BuildError)
88
+ throw new BuildError(`${name} at ${ref} (${sha}) does not build: ${e.message}`, e.diagnostics);
89
+ throw e;
90
+ });
91
+ const template = await project.template(current.template);
92
+ return await redline(project, old.tex, current.tex, dir, `${name}-vs-${sha}`, [template.dir], options);
93
+ }
94
+ finally {
95
+ try {
96
+ git(top, ['worktree', 'remove', '--force', tree]);
97
+ }
98
+ catch {
99
+ rmSync(tree, { recursive: true, force: true });
100
+ try {
101
+ git(top, ['worktree', 'prune']);
102
+ }
103
+ catch {
104
+ // nothing left to clean
105
+ }
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,24 @@
1
+ import { Converted } from '@latex-kit/template';
2
+ import { Project } from './project';
3
+ export interface ImportOptions {
4
+ /** Template name. Default: the file name in kebab-case. */
5
+ name?: string;
6
+ /** Replace an existing template. */
7
+ force?: boolean;
8
+ backend?: 'docker' | 'local';
9
+ /** Write a starter schema.ts from the fields found. Default true. */
10
+ schema?: boolean;
11
+ }
12
+ export interface ImportResult {
13
+ name: string;
14
+ template: string;
15
+ schema: string | null;
16
+ media: string | null;
17
+ converted: Converted[];
18
+ skipped: Converted[];
19
+ }
20
+ export declare function templateNameFor(file: string): string;
21
+ /** A zod schema source with every converted field as a string, nested by path. */
22
+ export declare function starterSchema(paths: string[]): string;
23
+ /** Convert a document (Word, Markdown, HTML, …, or an older .tex) into a template. */
24
+ export declare function importDocument(project: Project, file: string, options?: ImportOptions): Promise<ImportResult>;