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/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 ADDED
@@ -0,0 +1,45 @@
1
+ import { Engine } from '@latex-kit/render';
2
+ import { Diagnostic, Variant } from '@latex-kit/template';
3
+ import { Project } from './project';
4
+ export interface BuildOptions {
5
+ variant?: Variant;
6
+ /** Fail on missing values even in drafts. Default: on when CI=true. */
7
+ strict?: boolean;
8
+ engine?: Engine;
9
+ backend?: 'docker' | 'local';
10
+ image?: string;
11
+ platform?: string | null;
12
+ /** Build twice and fail unless the PDFs are byte-identical. */
13
+ verify?: boolean;
14
+ /** Stop after writing the .tex (no TeX run). */
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;
20
+ onOutput?: (chunk: string) => void;
21
+ }
22
+ export interface BuildResult {
23
+ name: string;
24
+ /** The template the document uses. */
25
+ template: string;
26
+ variant: Variant;
27
+ tex: string;
28
+ pdf: string | null;
29
+ sha256: string | null;
30
+ docId: string | null;
31
+ /** The ID was minted by this build and written to the record. */
32
+ minted: boolean;
33
+ sourceDateEpoch: number;
34
+ reproducible: boolean;
35
+ verified?: boolean;
36
+ diagnostics: Diagnostic[];
37
+ }
38
+ export declare class BuildError extends Error {
39
+ readonly diagnostics: Diagnostic[];
40
+ constructor(message: string, diagnostics: Diagnostic[]);
41
+ }
42
+ /** Build one document record. */
43
+ export declare function buildDocument(project: Project, file: string, options?: BuildOptions): Promise<BuildResult>;
44
+ /** Build a template as a blank form, without a record. */
45
+ export declare function buildBlank(project: Project, templateName: string, options?: BuildOptions): Promise<BuildResult>;
package/build.js ADDED
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BuildError = void 0;
4
+ exports.buildDocument = buildDocument;
5
+ exports.buildBlank = buildBlank;
6
+ const render_1 = require("@latex-kit/render");
7
+ const schema_1 = require("@latex-kit/schema");
8
+ const template_1 = require("@latex-kit/template");
9
+ const child_process_1 = require("child_process");
10
+ const crypto_1 = require("crypto");
11
+ const fs_1 = require("fs");
12
+ const path_1 = require("path");
13
+ class BuildError extends Error {
14
+ diagnostics;
15
+ constructor(message, diagnostics) {
16
+ super(message);
17
+ this.diagnostics = diagnostics;
18
+ this.name = 'BuildError';
19
+ }
20
+ }
21
+ exports.BuildError = BuildError;
22
+ const sha256 = (data) => (0, crypto_1.createHash)('sha256').update(data).digest('hex');
23
+ function isCI() {
24
+ return process.env.CI === 'true' || process.env.CI === '1';
25
+ }
26
+ /**
27
+ * The build date: SOURCE_DATE_EPOCH if set, else the newest commit among
28
+ * every input file. Same commit → same date → same PDF bytes.
29
+ */
30
+ function buildEpoch(files) {
31
+ const env = process.env.SOURCE_DATE_EPOCH;
32
+ if (env && /^\d+$/.test(env.trim()))
33
+ return { epoch: Number(env.trim()), reproducible: true };
34
+ let newest = -1;
35
+ let allCommitted = true;
36
+ for (const f of files) {
37
+ const t = (0, render_1.gitCommitTime)(f);
38
+ if (t && /^\d+$/.test(t))
39
+ newest = Math.max(newest, Number(t));
40
+ else
41
+ allCommitted = false;
42
+ }
43
+ if (newest < 0)
44
+ return { epoch: Math.floor(Date.now() / 1000), reproducible: false };
45
+ return { epoch: newest, reproducible: allCommitted };
46
+ }
47
+ function gitShortHead(cwd) {
48
+ try {
49
+ return (0, child_process_1.execFileSync)('git', ['rev-parse', '--short', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim();
50
+ }
51
+ catch {
52
+ return 'no-git';
53
+ }
54
+ }
55
+ async function run(job) {
56
+ const { project, template, variant, options } = job;
57
+ const diagnostics = job.diagnostics;
58
+ // 1. fill the template
59
+ const snippets = new Set();
60
+ const loadSnippet = (name, from) => {
61
+ const s = project.loadSnippet(name, from);
62
+ if (s)
63
+ snippets.add((0, path_1.resolve)(s.file));
64
+ return s;
65
+ };
66
+ const strict = options.strict ?? isCI();
67
+ const files = [...job.inputs, template.texFile, ...(template.schemaFile ? [template.schemaFile] : [])];
68
+ const { epoch, reproducible } = buildEpoch(files);
69
+ let docId = job.docId;
70
+ let minted = false;
71
+ if (!docId && job.mintInto) {
72
+ docId = (0, schema_1.mintDocId)({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
73
+ minted = true;
74
+ }
75
+ const evaluated = (0, template_1.evaluateTemplate)(template.compiled, {
76
+ data: job.data,
77
+ variant,
78
+ locale: job.locale,
79
+ docId,
80
+ template: template.name,
81
+ allowMissing: variant === 'draft' ? !strict : undefined,
82
+ loadSnippet,
83
+ loadClause: project.loadClause,
84
+ });
85
+ diagnostics.push(...evaluated.diagnostics);
86
+ if ((0, template_1.hasErrors)(diagnostics))
87
+ throw new BuildError(`${job.name}: cannot build ${variant}`, diagnostics);
88
+ // snippets count as inputs for the build date too
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 };
92
+ // 2. write the .tex next to latex-kit.sty
93
+ const outDir = options.outDir ?? (0, path_1.join)(project.outDir, job.name);
94
+ (0, fs_1.mkdirSync)(outDir, { recursive: true });
95
+ const job_ = variant === 'final' ? job.name : `${job.name}-${variant}`;
96
+ const texPath = (0, path_1.join)(outDir, `${job_}.tex`);
97
+ const stamp = `${new Date(finalEpoch.epoch * 1000).toISOString().slice(0, 10)} ${gitShortHead(project.root)}`;
98
+ const tex = (0, template_1.wrapDocument)(evaluated.tex, { variant, stamp });
99
+ (0, fs_1.writeFileSync)(texPath, tex);
100
+ (0, fs_1.writeFileSync)((0, path_1.join)(outDir, 'latex-kit.sty'), template_1.LATEX_KIT_STY);
101
+ const result = {
102
+ name: job.name,
103
+ template: template.name,
104
+ variant,
105
+ tex: texPath,
106
+ pdf: null,
107
+ sha256: null,
108
+ docId: docId ?? null,
109
+ minted: false,
110
+ sourceDateEpoch: finalEpoch.epoch,
111
+ reproducible: finalEpoch.reproducible,
112
+ diagnostics,
113
+ };
114
+ if (options.texOnly)
115
+ return result;
116
+ // 3. render
117
+ const engine = options.engine ?? template.meta.engine ?? project.config.engine ?? 'lualatex';
118
+ const renderOpts = {
119
+ file: texPath,
120
+ root: project.root,
121
+ engine,
122
+ backend: options.backend ?? project.config.backend,
123
+ image: options.image ?? project.config.image,
124
+ platform: options.platform !== undefined ? options.platform : project.config.platform,
125
+ sourceDateEpoch: finalEpoch.epoch,
126
+ texInputs: [(0, path_1.relative)(project.root, outDir) || '.', (0, path_1.relative)(project.root, template.dir) || '.'],
127
+ onOutput: options.onOutput,
128
+ };
129
+ let rendered;
130
+ try {
131
+ rendered = await (0, render_1.render)({ ...renderOpts, outDir: (0, path_1.relative)(project.root, outDir) });
132
+ }
133
+ catch (e) {
134
+ if (e instanceof render_1.RenderError) {
135
+ throw new BuildError(`${job.name}: ${e.message}`, [
136
+ ...diagnostics,
137
+ ...e.diagnostics.map((d) => (0, template_1.diag)(d.severity, d.message, d.file ? { file: project.rel((0, path_1.join)(outDir, (0, path_1.basename)(d.file))), line: d.line ?? 0, column: 0 } : undefined)),
138
+ ]);
139
+ }
140
+ throw e;
141
+ }
142
+ result.pdf = rendered.pdf;
143
+ result.sha256 = rendered.sha256;
144
+ if (options.verify) {
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) });
147
+ result.verified = again.sha256 === rendered.sha256;
148
+ }
149
+ // 4. keep the ID: only after a successful final build
150
+ if (minted && job.mintInto) {
151
+ (0, schema_1.writeDocId)(job.mintInto, docId);
152
+ result.minted = true;
153
+ }
154
+ // 5. manifest: what went in, what came out
155
+ const inputFiles = [...new Set([...files, ...extra])].filter(fs_1.existsSync).sort();
156
+ (0, fs_1.writeFileSync)((0, path_1.join)(outDir, `${job_}.manifest.json`), JSON.stringify({
157
+ document: job.name,
158
+ template: template.name,
159
+ variant,
160
+ docId: docId ?? null,
161
+ locale: job.locale,
162
+ engine,
163
+ image: rendered.image,
164
+ sourceDateEpoch: finalEpoch.epoch,
165
+ inputs: inputFiles.map((f) => ({ file: (0, path_1.relative)(project.root, f), sha256: sha256((0, fs_1.readFileSync)(f)) })),
166
+ tex: { file: (0, path_1.relative)(project.root, texPath), sha256: sha256(tex) },
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)) })),
169
+ fields: evaluated.fields.map((f) => ({ path: f.path, missing: f.missing })),
170
+ }, null, 2) + '\n');
171
+ return result;
172
+ }
173
+ /** Build one document record. */
174
+ async function buildDocument(project, file, options = {}) {
175
+ const variant = options.variant ?? 'draft';
176
+ const diagnostics = [];
177
+ const doc = await (0, schema_1.loadDocument)(file, { dataDir: project.dataDir });
178
+ const template = await project.template(doc.record.template);
179
+ const at = { file: project.rel(file), line: 1, column: 1 };
180
+ let data = doc.data;
181
+ if (template.schema) {
182
+ const v = (0, schema_1.validate)(template.schema, doc.data);
183
+ if (v.ok) {
184
+ data = v.value;
185
+ }
186
+ else {
187
+ const sev = variant === 'final' || variant === 'signed' ? 'error' : 'warning';
188
+ for (const i of v.issues)
189
+ diagnostics.push((0, template_1.diag)(sev, `data.${i.path}: ${i.message}`, at));
190
+ }
191
+ }
192
+ const needsId = (variant === 'final' || variant === 'signed') && !doc.record.docId && !options.docIdFallback;
193
+ if (needsId && !['.json', '.yaml', '.yml'].includes((0, path_1.extname)(file).toLowerCase())) {
194
+ const suggestion = (0, schema_1.mintDocId)({ prefix: template.meta.docIdPrefix ?? template.name, epoch: Math.floor(Date.now() / 1000) });
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));
196
+ throw new BuildError(`${doc.record.template}: no document ID`, diagnostics);
197
+ }
198
+ return run({
199
+ project,
200
+ template,
201
+ name: project.documentName(file),
202
+ variant,
203
+ data,
204
+ locale: doc.record.locale ?? template.meta.locale ?? project.config.locale,
205
+ docId: doc.record.docId ?? options.docIdFallback,
206
+ inputs: [file, ...doc.refFiles],
207
+ diagnostics,
208
+ options,
209
+ mintInto: needsId ? file : undefined,
210
+ });
211
+ }
212
+ /** Build a template as a blank form, without a record. */
213
+ async function buildBlank(project, templateName, options = {}) {
214
+ const template = await project.template(templateName);
215
+ return run({
216
+ project,
217
+ template,
218
+ name: `${templateName}`,
219
+ variant: 'blank',
220
+ data: {},
221
+ locale: template.meta.locale ?? project.config.locale,
222
+ inputs: [],
223
+ diagnostics: [],
224
+ options: { ...options, variant: 'blank' },
225
+ });
226
+ }
package/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/check.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkProject = checkProject;
4
+ exports.templateFields = templateFields;
5
+ const schema_1 = require("@latex-kit/schema");
6
+ const template_1 = require("@latex-kit/template");
7
+ /**
8
+ * Everything that can be checked without TeX: template syntax, field names
9
+ * against each schema, every document's data, references, and duplicate IDs.
10
+ */
11
+ async function checkProject(project) {
12
+ const diagnostics = [];
13
+ const templates = project.templateNames();
14
+ for (const name of templates) {
15
+ try {
16
+ const t = await project.template(name);
17
+ if (!t.jsonSchema) {
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
+ }
20
+ diagnostics.push(...(0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause }).diagnostics);
21
+ }
22
+ catch (e) {
23
+ diagnostics.push((0, template_1.diag)('error', e.message, { file: project.rel(project.path(project.config.templates, name)), line: 1, column: 1 }));
24
+ }
25
+ }
26
+ const files = project.documentFiles();
27
+ const ids = new Map();
28
+ for (const file of files) {
29
+ const at = { file: project.rel(file), line: 1, column: 1 };
30
+ try {
31
+ const doc = await (0, schema_1.loadDocument)(file, { dataDir: project.dataDir });
32
+ if (doc.record.docId) {
33
+ const prev = ids.get(doc.record.docId);
34
+ if (prev)
35
+ diagnostics.push((0, template_1.diag)('error', `document ID ${doc.record.docId} is also used by ${prev}; never reuse an ID`, at));
36
+ else
37
+ ids.set(doc.record.docId, project.rel(file));
38
+ }
39
+ const t = await project.template(doc.record.template);
40
+ if (t.schema) {
41
+ const v = (0, schema_1.validate)(t.schema, doc.data);
42
+ if (!v.ok)
43
+ for (const i of v.issues)
44
+ diagnostics.push((0, template_1.diag)('error', `data.${i.path}: ${i.message}`, at));
45
+ }
46
+ }
47
+ catch (e) {
48
+ diagnostics.push((0, template_1.diag)('error', e.message.replace(`${file}: `, ''), at));
49
+ }
50
+ }
51
+ return { diagnostics, templates, documents: files.map((f) => project.rel(f)) };
52
+ }
53
+ /** Every field a template reads, including through snippets. */
54
+ async function templateFields(project, name) {
55
+ const t = await project.template(name);
56
+ const r = (0, template_1.analyzeTemplate)(t.compiled, { schema: t.jsonSchema ?? undefined, loadSnippet: project.loadSnippet, loadClause: project.loadClause });
57
+ return { fields: r.fields, diagnostics: r.diagnostics };
58
+ }
package/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/cli.js ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const schema_1 = require("@latex-kit/schema");
5
+ const inquirerer_1 = require("inquirerer");
6
+ const path_1 = require("path");
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
+ });
17
+ const app = new inquirerer_1.CLI(commands_1.commands, {
18
+ noTty: !process.stdin.isTTY,
19
+ // inquirerer answers --version itself; make it report latex-kit
20
+ version: (0, commands_1.version)(),
21
+ minimistOpts: {
22
+ alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
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 },
26
+ },
27
+ });
28
+ app.run().catch((error) => {
29
+ console.error(error instanceof Error ? error.message : error);
30
+ process.exit(1);
31
+ });
package/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>>;