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
@@ -0,0 +1,340 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.buildCommand = buildCommand;
7
+ exports.checkCommand = checkCommand;
8
+ exports.fieldsCommand = fieldsCommand;
9
+ exports.typegenCommand = typegenCommand;
10
+ exports.styCommand = styCommand;
11
+ exports.importCommand = importCommand;
12
+ exports.diffCommand = diffCommand;
13
+ exports.initCommand = initCommand;
14
+ exports.newCommand = newCommand;
15
+ exports.cleanCommand = cleanCommand;
16
+ exports.watchCommand = watchCommand;
17
+ const render_1 = require("@latex-kit/render");
18
+ const schema_1 = require("@latex-kit/schema");
19
+ const template_1 = require("@latex-kit/template");
20
+ const fs_1 = require("fs");
21
+ const path_1 = require("path");
22
+ const yanse_1 = __importDefault(require("yanse"));
23
+ const args_1 = require("./args");
24
+ const build_1 = require("./build");
25
+ const check_1 = require("./check");
26
+ const commands_1 = require("./commands");
27
+ const diff_1 = require("./diff");
28
+ const import_1 = require("./import");
29
+ const project_1 = require("./project");
30
+ const scaffold_1 = require("./scaffold");
31
+ function printDiagnostics(ds, json) {
32
+ if (json)
33
+ return;
34
+ for (const d of ds)
35
+ console.error((d.severity === 'error' ? yanse_1.default.red : yanse_1.default.yellow)((0, template_1.formatDiagnostic)(d)));
36
+ }
37
+ const rel = (p) => (p ? (0, path_1.relative)(process.cwd(), p) : null);
38
+ async function buildCommand(argv) {
39
+ const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
40
+ if (!template_1.VARIANTS.includes(variant))
41
+ throw new args_1.UsageError(`--variant must be one of ${template_1.VARIANTS.join(', ')}`);
42
+ if (argv.engine && !render_1.ENGINES.includes(argv.engine))
43
+ throw new args_1.UsageError(`--engine must be one of ${render_1.ENGINES.join(', ')}`);
44
+ const project = await project_1.Project.open(argv.root);
45
+ const options = {
46
+ variant,
47
+ strict: argv.strict === undefined ? undefined : Boolean(argv.strict),
48
+ engine: argv.engine,
49
+ backend: argv.local ? 'local' : undefined,
50
+ image: argv.image,
51
+ platform: argv.platform,
52
+ verify: Boolean(argv.verify),
53
+ texOnly: Boolean(argv['tex-only']),
54
+ };
55
+ const json = Boolean(argv.json);
56
+ const log = (s) => !json && console.error(s);
57
+ const targets = [];
58
+ const files = (argv._ ?? []).map(String);
59
+ if (variant === 'blank' && files.length === 0) {
60
+ const names = argv.template ? [String(argv.template)] : project.templateNames();
61
+ for (const n of names)
62
+ targets.push({ label: `template ${n}`, run: () => (0, build_1.buildBlank)(project, n, options) });
63
+ }
64
+ else {
65
+ let docs = files.length ? files.map((f) => (0, path_1.join)(process.cwd(), f)) : project.documentFiles();
66
+ for (const f of docs)
67
+ if (!(0, fs_1.existsSync)(f))
68
+ throw new args_1.UsageError(`no such document: ${rel(f)}`);
69
+ if (argv.template) {
70
+ const wanted = String(argv.template);
71
+ const keep = [];
72
+ for (const f of docs)
73
+ if ((await (0, schema_1.loadDocument)(f, { dataDir: project.dataDir })).record.template === wanted)
74
+ keep.push(f);
75
+ docs = keep;
76
+ }
77
+ for (const f of docs)
78
+ targets.push({ label: rel(f), run: () => (0, build_1.buildDocument)(project, f, options) });
79
+ }
80
+ if (targets.length === 0) {
81
+ log(yanse_1.default.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
82
+ return 0;
83
+ }
84
+ const results = [];
85
+ let failed = 0;
86
+ for (const t of targets) {
87
+ log(yanse_1.default.dim(`building ${t.label} (${variant})…`));
88
+ try {
89
+ const r = await t.run();
90
+ printDiagnostics(r.diagnostics, json);
91
+ const bad = r.verified === false;
92
+ if (bad)
93
+ failed++;
94
+ results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
95
+ if (!json) {
96
+ console.log(`${bad ? yanse_1.default.red('✗') : yanse_1.default.green('✓')} ${rel(r.pdf ?? r.tex)}${r.docId ? yanse_1.default.dim(` ${r.docId}`) : ''}`);
97
+ if (r.minted)
98
+ console.log(yanse_1.default.dim(` minted ${r.docId} and saved it in ${t.label}`));
99
+ if (r.verified !== undefined)
100
+ console.log(r.verified ? yanse_1.default.dim(' byte-identical on a second build') : yanse_1.default.red(' second build differs'));
101
+ if (!r.reproducible)
102
+ console.log(yanse_1.default.yellow(' not reproducible: some inputs are not committed, so the build date is "now"'));
103
+ }
104
+ }
105
+ catch (e) {
106
+ failed++;
107
+ if (e instanceof build_1.BuildError) {
108
+ printDiagnostics(e.diagnostics, json);
109
+ if (!json)
110
+ console.error(yanse_1.default.red(`✗ ${t.label}: ${e.message}`));
111
+ results.push({ target: t.label, error: e.message, diagnostics: e.diagnostics });
112
+ }
113
+ else {
114
+ if (!json)
115
+ console.error(yanse_1.default.red(`✗ ${t.label}: ${e.message}`));
116
+ results.push({ target: t.label, error: e.message });
117
+ }
118
+ }
119
+ }
120
+ if (json)
121
+ console.log(JSON.stringify(results, null, 2));
122
+ return failed ? 1 : 0;
123
+ }
124
+ async function checkCommand(argv) {
125
+ const project = await project_1.Project.open(argv.root);
126
+ const r = await (0, check_1.checkProject)(project);
127
+ const errors = r.diagnostics.filter((d) => d.severity === 'error').length;
128
+ const warnings = r.diagnostics.length - errors;
129
+ if (argv.json) {
130
+ console.log(JSON.stringify(r, null, 2));
131
+ }
132
+ else {
133
+ printDiagnostics(r.diagnostics, false);
134
+ const summary = `${r.templates.length} template${r.templates.length === 1 ? '' : 's'}, ${r.documents.length} document${r.documents.length === 1 ? '' : 's'}: ${errors} error${errors === 1 ? '' : 's'}, ${warnings} warning${warnings === 1 ? '' : 's'}`;
135
+ console.log(errors ? yanse_1.default.red(`✗ ${summary}`) : `${yanse_1.default.green('✓')} ${summary}`);
136
+ }
137
+ return errors ? 1 : 0;
138
+ }
139
+ async function fieldsCommand(argv) {
140
+ const name = argv._?.[0];
141
+ if (!name)
142
+ throw new args_1.UsageError('usage: latex-kit fields <template>');
143
+ const project = await project_1.Project.open(argv.root);
144
+ const { fields, diagnostics } = await (0, check_1.templateFields)(project, String(name));
145
+ if (argv.json) {
146
+ console.log(JSON.stringify(fields, null, 2));
147
+ return 0;
148
+ }
149
+ printDiagnostics(diagnostics, false);
150
+ const width = Math.max(...fields.map((f) => f.absolute.length), 4);
151
+ for (const f of fields) {
152
+ const filters = f.filters.length ? yanse_1.default.cyan(` | ${f.filters.join(' | ')}`) : '';
153
+ console.log(`${f.absolute.padEnd(width)} ${yanse_1.default.dim(f.kind.padEnd(5))} ${yanse_1.default.dim(`${f.file}:${f.line}`)}${filters}`);
154
+ }
155
+ return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
156
+ }
157
+ async function typegenCommand(argv) {
158
+ const project = await project_1.Project.open(argv.root);
159
+ let n = 0;
160
+ for (const name of project.templateNames()) {
161
+ const t = await project.template(name);
162
+ if (!t.jsonSchema)
163
+ continue;
164
+ const schemaFile = (0, path_1.join)(t.dir, `${name}.schema.json`);
165
+ const typesFile = (0, path_1.join)(t.dir, 'types.d.ts');
166
+ (0, fs_1.writeFileSync)(schemaFile, JSON.stringify((0, schema_1.documentJsonSchema)(name, t.jsonSchema), null, 2) + '\n');
167
+ (0, fs_1.writeFileSync)(typesFile, `// Generated by latex-kit typegen from schema.ts. Do not edit.\n${(0, schema_1.generateTypes)(name, t.jsonSchema)}\n`);
168
+ console.log(`${yanse_1.default.green('✓')} ${rel(schemaFile)} ${rel(typesFile)}`);
169
+ n++;
170
+ }
171
+ if (n === 0)
172
+ console.log(yanse_1.default.yellow('no templates with a schema.ts'));
173
+ return 0;
174
+ }
175
+ async function styCommand(argv) {
176
+ const project = await project_1.Project.open(argv.root);
177
+ const dir = argv._?.[0] ? (0, path_1.join)(process.cwd(), String(argv._[0])) : project.templatesDir;
178
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
179
+ const file = (0, path_1.join)(dir, 'latex-kit.sty');
180
+ (0, fs_1.writeFileSync)(file, template_1.LATEX_KIT_STY);
181
+ console.log(`${yanse_1.default.green('✓')} ${rel(file)} (lets editors compile templates as blank previews)`);
182
+ return 0;
183
+ }
184
+ async function importCommand(argv) {
185
+ const file = argv._?.[0];
186
+ if (!file)
187
+ throw new args_1.UsageError('usage: latex-kit import <file.docx|.md|.html|.tex> [--name <template>] [--force]');
188
+ const project = await project_1.Project.open(argv.root);
189
+ const r = await (0, import_1.importDocument)(project, String(file), {
190
+ name: argv.name,
191
+ force: Boolean(argv.force),
192
+ backend: argv.local ? 'local' : undefined,
193
+ schema: argv.schema !== false,
194
+ });
195
+ console.log(`${yanse_1.default.green('✓')} ${rel(r.template)}`);
196
+ if (r.media)
197
+ console.log(yanse_1.default.dim(` images in ${rel(r.media)}`));
198
+ console.log(yanse_1.default.dim(` ${r.converted.length} placeholder${r.converted.length === 1 ? '' : 's'} became \\field{…}`));
199
+ for (const s of r.skipped)
200
+ console.log(yanse_1.default.yellow(` line ${s.line}: left ${s.from} as is (not a valid field path)`));
201
+ if (r.schema)
202
+ console.log(yanse_1.default.dim(` starter schema: ${rel(r.schema)} (every field is a string; tighten it)`));
203
+ console.log(yanse_1.default.dim(` next: latex-kit fields ${r.name}, then latex-kit build --variant blank --template ${r.name}`));
204
+ return 0;
205
+ }
206
+ async function diffCommand(argv) {
207
+ const args = (argv._ ?? []).map(String);
208
+ const variant = (argv.variant ?? 'final');
209
+ if (!template_1.VARIANTS.includes(variant))
210
+ throw new args_1.UsageError(`--variant must be one of ${template_1.VARIANTS.join(', ')}`);
211
+ const project = await project_1.Project.open(argv.root);
212
+ const options = { variant, engine: argv.engine, backend: argv.local ? 'local' : undefined, image: argv.image, platform: argv.platform };
213
+ const abs = (p) => (0, path_1.join)(process.cwd(), p);
214
+ let result;
215
+ try {
216
+ if (args.length === 2 && !argv.against) {
217
+ result = await (0, diff_1.diffFiles)(project, abs(args[0]), abs(args[1]), options);
218
+ }
219
+ else if (args.length === 1 && argv.against) {
220
+ result = await (0, diff_1.diffDocument)(project, abs(args[0]), String(argv.against), options);
221
+ }
222
+ else {
223
+ throw new args_1.UsageError('usage: latex-kit diff <old.tex> <new.tex>\n latex-kit diff <document> --against <git-ref>');
224
+ }
225
+ }
226
+ catch (e) {
227
+ if (e instanceof build_1.BuildError) {
228
+ printDiagnostics(e.diagnostics, Boolean(argv.json));
229
+ console.error(yanse_1.default.red(`✗ ${e.message}`));
230
+ return 1;
231
+ }
232
+ throw e;
233
+ }
234
+ if (argv.json)
235
+ console.log(JSON.stringify({ pdf: rel(result.pdf), tex: rel(result.tex), old: rel(result.old), new: rel(result.new) }, null, 2));
236
+ else
237
+ console.log(`${yanse_1.default.green('✓')} ${rel(result.pdf)} ${yanse_1.default.dim('(insertions underlined in blue, deletions struck through in red)')}`);
238
+ return 0;
239
+ }
240
+ async function initCommand(argv) {
241
+ const dir = (0, path_1.join)(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
242
+ const r = (0, scaffold_1.initProject)(dir, { paper: Boolean(argv.paper), force: Boolean(argv.force), version: (0, commands_1.version)() });
243
+ for (const f of r.written)
244
+ console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
245
+ for (const f of r.skipped)
246
+ console.log(yanse_1.default.dim(` kept ${rel(f)} (exists)`));
247
+ const cd = rel(dir) === '.' ? '' : `cd ${rel(dir)} && `;
248
+ console.log(argv.paper
249
+ ? yanse_1.default.dim(`\nnext: ${cd}latex-kit render paper/main.tex --verify`)
250
+ : yanse_1.default.dim(`\nnext: ${cd}latex-kit check && latex-kit build`));
251
+ return 0;
252
+ }
253
+ async function newCommand(argv) {
254
+ const [kind, name] = (argv._ ?? []).map(String);
255
+ const project = await project_1.Project.open(argv.root);
256
+ if (kind === 'template' && name) {
257
+ const r = (0, scaffold_1.newTemplate)(project, name, Boolean(argv.force));
258
+ for (const f of r.written)
259
+ console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
260
+ console.log(yanse_1.default.dim(`\nnext: latex-kit new document <name> --template ${name}`));
261
+ return 0;
262
+ }
263
+ if (kind === 'document' && name) {
264
+ if (!argv.template)
265
+ throw new args_1.UsageError('usage: latex-kit new document <name> --template <template>');
266
+ const r = await (0, scaffold_1.newDocument)(project, name, String(argv.template), Boolean(argv.force));
267
+ for (const f of r.written)
268
+ console.log(`${yanse_1.default.green('+')} ${rel(f)}`);
269
+ if (r.schemaFile)
270
+ console.log(yanse_1.default.dim(` editors autocomplete it from ${rel(r.schemaFile)}`));
271
+ console.log(yanse_1.default.dim(`\nnext: fill in the data, then latex-kit build ${r.written[0] ? rel(r.written[0]) : ''}`));
272
+ return 0;
273
+ }
274
+ throw new args_1.UsageError('usage: latex-kit new template <name>\n latex-kit new document <name> --template <template>');
275
+ }
276
+ async function cleanCommand(argv) {
277
+ const project = await project_1.Project.open(argv.root);
278
+ const rel = (0, path_1.relative)(project.root, project.outDir);
279
+ if (rel === '' || rel.startsWith('..') || (0, path_1.isAbsolute)(rel))
280
+ throw new args_1.UsageError(`refusing to delete ${project.outDir}: the out folder must be inside the project`);
281
+ if (!(0, fs_1.existsSync)(project.outDir)) {
282
+ console.log(yanse_1.default.dim(`nothing to clean (${project.rel(project.outDir)}/ does not exist)`));
283
+ return 0;
284
+ }
285
+ (0, fs_1.rmSync)(project.outDir, { recursive: true, force: true });
286
+ console.log(`${yanse_1.default.green('✓')} removed ${project.rel(project.outDir)}/`);
287
+ return 0;
288
+ }
289
+ /**
290
+ * Rebuild when templates, snippets, clauses, data or records change. Builds
291
+ * drafts unless --variant says otherwise; never mints IDs (use build --final).
292
+ */
293
+ async function watchCommand(argv) {
294
+ const variant = (argv.variant ?? 'draft');
295
+ if (variant === 'final' || variant === 'signed')
296
+ throw new args_1.UsageError('watch builds drafts or blanks; run latex-kit build --final when you are done');
297
+ const project = await project_1.Project.open(argv.root);
298
+ const dirs = [project.config.templates, project.config.snippets, project.config.clauses, project.config.data, project.config.documents]
299
+ .map((d) => project.path(d))
300
+ .filter((d) => (0, fs_1.existsSync)(d));
301
+ if (dirs.length === 0)
302
+ throw new args_1.UsageError('nothing to watch: no templates/, data/ or documents/ here');
303
+ let running = false;
304
+ let again = false;
305
+ let timer = null;
306
+ const run = async () => {
307
+ if (running) {
308
+ again = true;
309
+ return;
310
+ }
311
+ running = true;
312
+ console.log(yanse_1.default.dim(`\n— ${new Date().toLocaleTimeString()} —`));
313
+ try {
314
+ await buildCommand({ ...argv, variant });
315
+ }
316
+ catch (e) {
317
+ console.error(yanse_1.default.red(e.message));
318
+ }
319
+ running = false;
320
+ if (again) {
321
+ again = false;
322
+ void run();
323
+ }
324
+ };
325
+ const schedule = (file) => {
326
+ // generated files and editor swap files are not changes worth a build
327
+ if (file && /(\.schema\.json|types\.d\.ts|~|\.swp)$/.test(file))
328
+ return;
329
+ if (timer)
330
+ clearTimeout(timer);
331
+ timer = setTimeout(() => void run(), 250);
332
+ };
333
+ for (const d of dirs)
334
+ (0, fs_1.watch)(d, { recursive: true }, (_event, file) => schedule(file ? String(file) : null));
335
+ console.log(yanse_1.default.dim(`watching ${dirs.map((d) => project.rel(d)).join(', ')} (Ctrl-C to stop)`));
336
+ await run();
337
+ return new Promise(() => {
338
+ // runs until interrupted
339
+ });
340
+ }
package/project.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { JsonSchema, TemplateMeta, z } from '@latex-kit/schema';
2
+ import { CompiledTemplate, LoadedClause } from '@latex-kit/template';
3
+ import { ResolvedConfig } from './config';
4
+ export interface Template {
5
+ name: string;
6
+ dir: string;
7
+ texFile: string;
8
+ compiled: CompiledTemplate;
9
+ schemaFile: string | null;
10
+ schema: z.ZodType | null;
11
+ jsonSchema: JsonSchema | null;
12
+ meta: TemplateMeta;
13
+ }
14
+ /** A latex-kit project: a folder with templates, data and documents. */
15
+ export declare class Project {
16
+ readonly root: string;
17
+ readonly config: ResolvedConfig;
18
+ private templates;
19
+ private snippets;
20
+ private clauses;
21
+ private constructor();
22
+ static open(root?: string): Promise<Project>;
23
+ path(...parts: string[]): string;
24
+ rel(file: string): string;
25
+ get templatesDir(): string;
26
+ get dataDir(): string;
27
+ get documentsDir(): string;
28
+ get outDir(): string;
29
+ /** Template names: folders under templates/ that contain template.tex. */
30
+ templateNames(): string[];
31
+ /** Document record files under documents/ (any depth). */
32
+ documentFiles(): string[];
33
+ /** A document's name: its path under documents/ without extension, `/` → `-`. */
34
+ documentName(file: string): string;
35
+ template(name: string): Promise<Template>;
36
+ private loadTemplate;
37
+ /**
38
+ * \snippet{name}: first next to the file that uses it, then in snippets/.
39
+ * `.tex` is added when the name has no extension. Never outside the project.
40
+ */
41
+ loadSnippet: (name: string, from: string) => CompiledTemplate | null;
42
+ /** \\clause{id}: `clauses/<id>.tex` from the clause library. */
43
+ loadClause: (id: string) => LoadedClause | null;
44
+ /** Absolute paths of every snippet loaded so far. */
45
+ snippetFiles(): string[];
46
+ }
package/project.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Project = void 0;
4
+ const schema_1 = require("@latex-kit/schema");
5
+ const template_1 = require("@latex-kit/template");
6
+ const fs_1 = require("fs");
7
+ const path_1 = require("path");
8
+ const config_1 = require("./config");
9
+ const SCHEMA_FILES = ['schema.ts', 'schema.mts', 'schema.js', 'schema.mjs', 'schema.cjs'];
10
+ /** A latex-kit project: a folder with templates, data and documents. */
11
+ class Project {
12
+ root;
13
+ config;
14
+ templates = new Map();
15
+ snippets = new Map();
16
+ clauses = new Map();
17
+ constructor(root, config) {
18
+ this.root = root;
19
+ this.config = config;
20
+ }
21
+ static async open(root = process.cwd()) {
22
+ const abs = (0, path_1.resolve)(root);
23
+ return new Project(abs, await (0, config_1.loadConfig)(abs));
24
+ }
25
+ path(...parts) {
26
+ return (0, path_1.join)(this.root, ...parts);
27
+ }
28
+ rel(file) {
29
+ return (0, path_1.relative)(process.cwd(), file) || '.';
30
+ }
31
+ get templatesDir() {
32
+ return this.path(this.config.templates);
33
+ }
34
+ get dataDir() {
35
+ return this.path(this.config.data);
36
+ }
37
+ get documentsDir() {
38
+ return this.path(this.config.documents);
39
+ }
40
+ get outDir() {
41
+ return this.path(this.config.out);
42
+ }
43
+ /** Template names: folders under templates/ that contain template.tex. */
44
+ templateNames() {
45
+ if (!(0, fs_1.existsSync)(this.templatesDir))
46
+ return [];
47
+ return (0, fs_1.readdirSync)(this.templatesDir)
48
+ .filter((n) => !n.startsWith('.') && !n.startsWith('_'))
49
+ .filter((n) => (0, fs_1.existsSync)((0, path_1.join)(this.templatesDir, n, 'template.tex')))
50
+ .sort();
51
+ }
52
+ /** Document record files under documents/ (any depth). */
53
+ documentFiles() {
54
+ const out = [];
55
+ const walk = (dir) => {
56
+ if (!(0, fs_1.existsSync)(dir))
57
+ return;
58
+ for (const name of (0, fs_1.readdirSync)(dir).sort()) {
59
+ if (name.startsWith('.') || name.startsWith('_'))
60
+ continue;
61
+ const p = (0, path_1.join)(dir, name);
62
+ if ((0, fs_1.statSync)(p).isDirectory())
63
+ walk(p);
64
+ else if (schema_1.DATA_EXTENSIONS.includes((0, path_1.extname)(name).toLowerCase()) && !name.endsWith('.d.ts'))
65
+ out.push(p);
66
+ }
67
+ };
68
+ walk(this.documentsDir);
69
+ return out;
70
+ }
71
+ /** A document's name: its path under documents/ without extension, `/` → `-`. */
72
+ documentName(file) {
73
+ const rel = (0, path_1.relative)(this.documentsDir, file);
74
+ const base = rel.startsWith('..') || (0, path_1.isAbsolute)(rel) ? (0, path_1.basename)(file) : rel;
75
+ return base.slice(0, -(0, path_1.extname)(base).length).split(/[\\/]/).join('-');
76
+ }
77
+ template(name) {
78
+ let t = this.templates.get(name);
79
+ if (!t) {
80
+ t = this.loadTemplate(name);
81
+ this.templates.set(name, t);
82
+ }
83
+ return t;
84
+ }
85
+ async loadTemplate(name) {
86
+ if (!/^[A-Za-z0-9_-]+$/.test(name))
87
+ throw new Error(`invalid template name "${name}"`);
88
+ const dir = (0, path_1.join)(this.templatesDir, name);
89
+ const texFile = (0, path_1.join)(dir, 'template.tex');
90
+ if (!(0, fs_1.existsSync)(texFile)) {
91
+ const known = this.templateNames();
92
+ throw new Error(`no template "${name}" (expected ${this.rel(texFile)}${known.length ? `; templates: ${known.join(', ')}` : ''})`);
93
+ }
94
+ const compiled = (0, template_1.compileTemplate)((0, fs_1.readFileSync)(texFile, 'utf8'), this.rel(texFile));
95
+ const schemaFile = SCHEMA_FILES.map((f) => (0, path_1.join)(dir, f)).find((f) => (0, fs_1.existsSync)(f)) ?? null;
96
+ let schema = null;
97
+ let meta = {};
98
+ let jsonSchema = null;
99
+ if (schemaFile) {
100
+ ({ schema, meta } = await (0, schema_1.loadTemplateSchema)(schemaFile));
101
+ jsonSchema = (0, schema_1.toJsonSchema)(schema);
102
+ }
103
+ return { name, dir, texFile, compiled, schemaFile, schema, jsonSchema, meta };
104
+ }
105
+ /**
106
+ * \snippet{name}: first next to the file that uses it, then in snippets/.
107
+ * `.tex` is added when the name has no extension. Never outside the project.
108
+ */
109
+ loadSnippet = (name, from) => {
110
+ const file = name.endsWith('.tex') ? name : `${name}.tex`;
111
+ const candidates = [(0, path_1.resolve)((0, path_1.dirname)((0, path_1.resolve)(from)), file), (0, path_1.join)(this.path(this.config.snippets), file)];
112
+ for (const c of candidates) {
113
+ const rel = (0, path_1.relative)(this.root, c);
114
+ if (rel.startsWith('..') || (0, path_1.isAbsolute)(rel) || !(0, fs_1.existsSync)(c))
115
+ continue;
116
+ let compiled = this.snippets.get(c);
117
+ if (!compiled) {
118
+ compiled = (0, template_1.compileTemplate)((0, fs_1.readFileSync)(c, 'utf8'), this.rel(c));
119
+ this.snippets.set(c, compiled);
120
+ }
121
+ return compiled;
122
+ }
123
+ return null;
124
+ };
125
+ /** \\clause{id}: `clauses/<id>.tex` from the clause library. */
126
+ loadClause = (id) => {
127
+ if (this.clauses.has(id))
128
+ return this.clauses.get(id);
129
+ let loaded = null;
130
+ const file = (0, path_1.join)(this.path(this.config.clauses), `${id}.tex`);
131
+ if ((0, template_1.isRelativeName)(id) && (0, fs_1.existsSync)(file)) {
132
+ const text = (0, fs_1.readFileSync)(file, 'utf8');
133
+ loaded = { id, template: (0, template_1.compileTemplate)(text, this.rel(file)), ...(0, template_1.parseClauseHeader)(text) };
134
+ }
135
+ this.clauses.set(id, loaded);
136
+ return loaded;
137
+ };
138
+ /** Absolute paths of every snippet loaded so far. */
139
+ snippetFiles() {
140
+ return [...this.snippets.keys()];
141
+ }
142
+ }
143
+ exports.Project = Project;
package/render.js CHANGED
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.renderCommand = renderCommand;
7
7
  const render_1 = require("@latex-kit/render");
8
- const fs_1 = require("fs");
9
8
  const path_1 = require("path");
10
9
  const yanse_1 = __importDefault(require("yanse"));
11
10
  const args_1 = require("./args");
@@ -54,11 +53,10 @@ async function renderCommand(argv, prompter) {
54
53
  }
55
54
  let verified;
56
55
  if (argv.verify) {
57
- const verifyDir = `${opts.outDir}.verify`;
56
+ // same output path: some tools (Ghostscript) hash the path into the PDF ID
58
57
  log(yanse_1.default.dim('rendering again to check the output is byte-identical…'));
59
- const second = await (0, render_1.render)({ ...opts, file: opts.file, outDir: verifyDir, sourceDateEpoch: first.sourceDateEpoch });
58
+ const second = await (0, render_1.render)({ ...opts, file: opts.file, sourceDateEpoch: first.sourceDateEpoch });
60
59
  verified = second.sha256 === first.sha256;
61
- (0, fs_1.rmSync)((0, path_1.dirname)(second.pdf), { recursive: true, force: true });
62
60
  }
63
61
  if (argv.json) {
64
62
  console.log(JSON.stringify({ ...summary(first), verified }, null, 2));
package/scaffold.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { FileMap } from './boilerplates';
2
+ import { Project } from './project';
3
+ export interface WriteResult {
4
+ written: string[];
5
+ skipped: string[];
6
+ }
7
+ /** Write files under `dir`. Existing files are kept unless `force`. */
8
+ export declare function writeFiles(dir: string, files: FileMap, force?: boolean): WriteResult;
9
+ /** Scaffold a latex-kit project (or a paper) in `dir`. */
10
+ export declare function initProject(dir: string, options: {
11
+ paper?: boolean;
12
+ force?: boolean;
13
+ version: string;
14
+ }): WriteResult;
15
+ export declare function newTemplate(project: Project, name: string, force?: boolean): WriteResult;
16
+ type Schema = Record<string, unknown>;
17
+ /** A placeholder value for a JSON Schema: required fields only, typed. */
18
+ export declare function skeleton(schema: Schema | undefined, root: Schema, depth?: number): unknown;
19
+ /**
20
+ * documents/<name>.json for a template: every required field with a
21
+ * placeholder, and `$schema` pointing at the generated JSON Schema so editors
22
+ * autocomplete and validate it.
23
+ */
24
+ export declare function newDocument(project: Project, name: string, templateName: string, force?: boolean): Promise<WriteResult & {
25
+ schemaFile: string | null;
26
+ }>;
27
+ export {};