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.
- package/README.md +3 -3
- package/boilerplates.d.ts +8 -0
- package/boilerplates.js +225 -0
- package/build.d.ts +45 -0
- package/build.js +226 -0
- package/check.d.ts +17 -0
- package/check.js +58 -0
- package/cli.d.ts +2 -0
- package/cli.js +31 -0
- package/commands.d.ts +1 -0
- package/commands.js +51 -15
- package/config.d.ts +28 -0
- package/config.js +30 -0
- package/diff.d.ts +25 -0
- package/diff.js +112 -0
- package/esm/boilerplates.d.ts +8 -0
- package/esm/boilerplates.js +220 -0
- package/esm/build.d.ts +45 -0
- package/esm/build.js +220 -0
- package/esm/check.d.ts +17 -0
- package/esm/check.js +54 -0
- package/esm/cli.d.ts +2 -0
- package/esm/cli.js +29 -0
- package/esm/commands.d.ts +1 -0
- package/esm/commands.js +49 -16
- package/esm/config.d.ts +28 -0
- package/esm/config.js +25 -0
- package/esm/diff.d.ts +25 -0
- package/esm/diff.js +108 -0
- package/esm/import.d.ts +24 -0
- package/esm/import.js +113 -0
- package/esm/index.d.ts +15 -2
- package/esm/index.js +15 -15
- package/esm/project-commands.d.ts +16 -0
- package/esm/project-commands.js +324 -0
- package/esm/project.d.ts +46 -0
- package/esm/project.js +139 -0
- package/esm/render.js +3 -5
- package/esm/scaffold.d.ts +27 -0
- package/esm/scaffold.js +108 -0
- package/esm/usage.js +53 -6
- package/import.d.ts +24 -0
- package/import.js +118 -0
- package/index.d.ts +15 -2
- package/index.js +29 -15
- package/package.json +8 -6
- package/project-commands.d.ts +16 -0
- package/project-commands.js +340 -0
- package/project.d.ts +46 -0
- package/project.js +143 -0
- package/render.js +2 -4
- package/scaffold.d.ts +27 -0
- package/scaffold.js +115 -0
- package/usage.js +53 -6
package/esm/import.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { runPandoc } from '@latex-kit/render';
|
|
2
|
+
import { convertPlaceholders, ensureLatexKitPackage } from '@latex-kit/template';
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
|
4
|
+
import { basename, extname, isAbsolute, join, relative, resolve } from 'path';
|
|
5
|
+
export function templateNameFor(file) {
|
|
6
|
+
return (basename(file, extname(file))
|
|
7
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
8
|
+
.toLowerCase()
|
|
9
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
10
|
+
.replace(/^-|-$/g, '') || 'imported');
|
|
11
|
+
}
|
|
12
|
+
/** A zod schema source with every converted field as a string, nested by path. */
|
|
13
|
+
export function starterSchema(paths) {
|
|
14
|
+
const root = {};
|
|
15
|
+
const conflicts = new Set();
|
|
16
|
+
for (const p of paths) {
|
|
17
|
+
const segs = p.split('.');
|
|
18
|
+
if (segs[0].startsWith('$'))
|
|
19
|
+
continue;
|
|
20
|
+
let node = root;
|
|
21
|
+
segs.forEach((seg, i) => {
|
|
22
|
+
const last = i === segs.length - 1;
|
|
23
|
+
const key = /^\d+$/.test(seg) ? null : seg;
|
|
24
|
+
if (key === null)
|
|
25
|
+
return; // list indexes: leave lists to the author
|
|
26
|
+
if (last) {
|
|
27
|
+
if (node[key] && node[key] !== null)
|
|
28
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
29
|
+
else
|
|
30
|
+
node[key] = null;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
if (node[key] === null)
|
|
34
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
35
|
+
node[key] ??= {};
|
|
36
|
+
node = node[key];
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const render = (t, indent) => Object.keys(t)
|
|
41
|
+
.sort()
|
|
42
|
+
.map((k) => {
|
|
43
|
+
const name = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
|
|
44
|
+
const v = t[k];
|
|
45
|
+
return v === null ? `${indent}${name}: z.string(),` : `${indent}${name}: z.object({\n${render(v, indent + ' ')}\n${indent}}),`;
|
|
46
|
+
})
|
|
47
|
+
.join('\n');
|
|
48
|
+
const note = conflicts.size ? `\n// Used both as a value and as a group, check: ${[...conflicts].join(', ')}` : '';
|
|
49
|
+
return `// Starter schema written by \`latex-kit import\`: every field is a string.
|
|
50
|
+
// Tighten the types (numbers, dates, lists) and add the fields' rules.${note}
|
|
51
|
+
import { z } from 'latex-kit';
|
|
52
|
+
|
|
53
|
+
export default z.object({
|
|
54
|
+
${render(root, ' ')}
|
|
55
|
+
});
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
/** Convert a document (Word, Markdown, HTML, …, or an older .tex) into a template. */
|
|
59
|
+
export async function importDocument(project, file, options = {}) {
|
|
60
|
+
const input = resolve(file);
|
|
61
|
+
if (!existsSync(input))
|
|
62
|
+
throw new Error(`no such file: ${file}`);
|
|
63
|
+
const name = options.name ?? templateNameFor(input);
|
|
64
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
65
|
+
throw new Error(`invalid template name "${name}" (use lowercase letters, digits and -)`);
|
|
66
|
+
const dir = join(project.templatesDir, name);
|
|
67
|
+
const target = join(dir, 'template.tex');
|
|
68
|
+
if (existsSync(target) && !options.force)
|
|
69
|
+
throw new Error(`${project.rel(target)} exists; use --force to replace it`);
|
|
70
|
+
mkdirSync(dir, { recursive: true });
|
|
71
|
+
let tex;
|
|
72
|
+
let media = null;
|
|
73
|
+
if (extname(input).toLowerCase() === '.tex') {
|
|
74
|
+
tex = readFileSync(input, 'utf8');
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
// pandoc runs in Docker with the project mounted, so the input must be inside it
|
|
78
|
+
const rel = relative(project.root, input);
|
|
79
|
+
let staged = null;
|
|
80
|
+
let source = input;
|
|
81
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
82
|
+
const stage = join(project.outDir, '.import');
|
|
83
|
+
mkdirSync(stage, { recursive: true });
|
|
84
|
+
staged = join(stage, basename(input));
|
|
85
|
+
copyFileSync(input, staged);
|
|
86
|
+
source = staged;
|
|
87
|
+
}
|
|
88
|
+
const mediaDir = join(dir, 'media');
|
|
89
|
+
try {
|
|
90
|
+
await runPandoc({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend });
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
if (staged)
|
|
94
|
+
rmSync(staged, { force: true });
|
|
95
|
+
}
|
|
96
|
+
tex = readFileSync(target, 'utf8');
|
|
97
|
+
if (existsSync(mediaDir)) {
|
|
98
|
+
media = mediaDir;
|
|
99
|
+
// pandoc writes media paths relative to the project root; TeX looks in the template folder
|
|
100
|
+
tex = tex.split(relative(project.root, mediaDir) + '/').join('media/');
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const { tex: converted, converted: fields, skipped } = convertPlaceholders(tex);
|
|
104
|
+
writeFileSync(target, ensureLatexKitPackage(converted));
|
|
105
|
+
let schema = null;
|
|
106
|
+
const schemaFile = join(dir, 'schema.ts');
|
|
107
|
+
if (options.schema !== false && fields.length > 0 && !existsSync(schemaFile)) {
|
|
108
|
+
const paths = [...new Set(fields.map((f) => f.to.slice('\\field{'.length, -1)))];
|
|
109
|
+
writeFileSync(schemaFile, starterSchema(paths));
|
|
110
|
+
schema = schemaFile;
|
|
111
|
+
}
|
|
112
|
+
return { name, template: target, schema, media, converted: fields, skipped };
|
|
113
|
+
}
|
package/esm/index.d.ts
CHANGED
|
@@ -1,2 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* latex-kit: typed, reproducible LaTeX documents.
|
|
3
|
+
*
|
|
4
|
+
* The CLI is `latex-kit`. This module is what project files import:
|
|
5
|
+
* `defineConfig` for latex-kit.config.ts, and `z` plus the shared types and
|
|
6
|
+
* `ref()` for templates' schema.ts and TypeScript records.
|
|
7
|
+
*/
|
|
8
|
+
export * from './build';
|
|
9
|
+
export * from './check';
|
|
10
|
+
export * from './config';
|
|
11
|
+
export * from './diff';
|
|
12
|
+
export * from './import';
|
|
13
|
+
export * from './project';
|
|
14
|
+
export * from './scaffold';
|
|
15
|
+
export * from '@latex-kit/schema';
|
package/esm/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
1
|
+
/**
|
|
2
|
+
* latex-kit: typed, reproducible LaTeX documents.
|
|
3
|
+
*
|
|
4
|
+
* The CLI is `latex-kit`. This module is what project files import:
|
|
5
|
+
* `defineConfig` for latex-kit.config.ts, and `z` plus the shared types and
|
|
6
|
+
* `ref()` for templates' schema.ts and TypeScript records.
|
|
7
|
+
*/
|
|
8
|
+
export * from './build';
|
|
9
|
+
export * from './check';
|
|
10
|
+
export * from './config';
|
|
11
|
+
export * from './diff';
|
|
12
|
+
export * from './import';
|
|
13
|
+
export * from './project';
|
|
14
|
+
export * from './scaffold';
|
|
15
|
+
export * from '@latex-kit/schema';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ParsedArgs } from 'minimist';
|
|
2
|
+
export declare function buildCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
3
|
+
export declare function checkCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
4
|
+
export declare function fieldsCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
5
|
+
export declare function typegenCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
6
|
+
export declare function styCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
7
|
+
export declare function importCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
8
|
+
export declare function diffCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
9
|
+
export declare function initCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
10
|
+
export declare function newCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
11
|
+
export declare function cleanCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
14
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
15
|
+
*/
|
|
16
|
+
export declare function watchCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { ENGINES } from '@latex-kit/render';
|
|
2
|
+
import { documentJsonSchema, generateTypes, loadDocument } from '@latex-kit/schema';
|
|
3
|
+
import { formatDiagnostic, LATEX_KIT_STY, VARIANTS } from '@latex-kit/template';
|
|
4
|
+
import { existsSync, mkdirSync, rmSync, watch as fsWatch, writeFileSync } from 'fs';
|
|
5
|
+
import { isAbsolute, join, relative } from 'path';
|
|
6
|
+
import chalk from 'yanse';
|
|
7
|
+
import { UsageError } from './args';
|
|
8
|
+
import { buildBlank, buildDocument, BuildError } from './build';
|
|
9
|
+
import { checkProject, templateFields } from './check';
|
|
10
|
+
import { version } from './commands';
|
|
11
|
+
import { diffDocument, diffFiles } from './diff';
|
|
12
|
+
import { importDocument } from './import';
|
|
13
|
+
import { Project } from './project';
|
|
14
|
+
import { initProject, newDocument, newTemplate } from './scaffold';
|
|
15
|
+
function printDiagnostics(ds, json) {
|
|
16
|
+
if (json)
|
|
17
|
+
return;
|
|
18
|
+
for (const d of ds)
|
|
19
|
+
console.error((d.severity === 'error' ? chalk.red : chalk.yellow)(formatDiagnostic(d)));
|
|
20
|
+
}
|
|
21
|
+
const rel = (p) => (p ? relative(process.cwd(), p) : null);
|
|
22
|
+
export async function buildCommand(argv) {
|
|
23
|
+
const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
|
|
24
|
+
if (!VARIANTS.includes(variant))
|
|
25
|
+
throw new UsageError(`--variant must be one of ${VARIANTS.join(', ')}`);
|
|
26
|
+
if (argv.engine && !ENGINES.includes(argv.engine))
|
|
27
|
+
throw new UsageError(`--engine must be one of ${ENGINES.join(', ')}`);
|
|
28
|
+
const project = await Project.open(argv.root);
|
|
29
|
+
const options = {
|
|
30
|
+
variant,
|
|
31
|
+
strict: argv.strict === undefined ? undefined : Boolean(argv.strict),
|
|
32
|
+
engine: argv.engine,
|
|
33
|
+
backend: argv.local ? 'local' : undefined,
|
|
34
|
+
image: argv.image,
|
|
35
|
+
platform: argv.platform,
|
|
36
|
+
verify: Boolean(argv.verify),
|
|
37
|
+
texOnly: Boolean(argv['tex-only']),
|
|
38
|
+
};
|
|
39
|
+
const json = Boolean(argv.json);
|
|
40
|
+
const log = (s) => !json && console.error(s);
|
|
41
|
+
const targets = [];
|
|
42
|
+
const files = (argv._ ?? []).map(String);
|
|
43
|
+
if (variant === 'blank' && files.length === 0) {
|
|
44
|
+
const names = argv.template ? [String(argv.template)] : project.templateNames();
|
|
45
|
+
for (const n of names)
|
|
46
|
+
targets.push({ label: `template ${n}`, run: () => buildBlank(project, n, options) });
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
let docs = files.length ? files.map((f) => join(process.cwd(), f)) : project.documentFiles();
|
|
50
|
+
for (const f of docs)
|
|
51
|
+
if (!existsSync(f))
|
|
52
|
+
throw new UsageError(`no such document: ${rel(f)}`);
|
|
53
|
+
if (argv.template) {
|
|
54
|
+
const wanted = String(argv.template);
|
|
55
|
+
const keep = [];
|
|
56
|
+
for (const f of docs)
|
|
57
|
+
if ((await loadDocument(f, { dataDir: project.dataDir })).record.template === wanted)
|
|
58
|
+
keep.push(f);
|
|
59
|
+
docs = keep;
|
|
60
|
+
}
|
|
61
|
+
for (const f of docs)
|
|
62
|
+
targets.push({ label: rel(f), run: () => buildDocument(project, f, options) });
|
|
63
|
+
}
|
|
64
|
+
if (targets.length === 0) {
|
|
65
|
+
log(chalk.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
const results = [];
|
|
69
|
+
let failed = 0;
|
|
70
|
+
for (const t of targets) {
|
|
71
|
+
log(chalk.dim(`building ${t.label} (${variant})…`));
|
|
72
|
+
try {
|
|
73
|
+
const r = await t.run();
|
|
74
|
+
printDiagnostics(r.diagnostics, json);
|
|
75
|
+
const bad = r.verified === false;
|
|
76
|
+
if (bad)
|
|
77
|
+
failed++;
|
|
78
|
+
results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
|
|
79
|
+
if (!json) {
|
|
80
|
+
console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${r.docId ? chalk.dim(` ${r.docId}`) : ''}`);
|
|
81
|
+
if (r.minted)
|
|
82
|
+
console.log(chalk.dim(` minted ${r.docId} and saved it in ${t.label}`));
|
|
83
|
+
if (r.verified !== undefined)
|
|
84
|
+
console.log(r.verified ? chalk.dim(' byte-identical on a second build') : chalk.red(' second build differs'));
|
|
85
|
+
if (!r.reproducible)
|
|
86
|
+
console.log(chalk.yellow(' not reproducible: some inputs are not committed, so the build date is "now"'));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
failed++;
|
|
91
|
+
if (e instanceof BuildError) {
|
|
92
|
+
printDiagnostics(e.diagnostics, json);
|
|
93
|
+
if (!json)
|
|
94
|
+
console.error(chalk.red(`✗ ${t.label}: ${e.message}`));
|
|
95
|
+
results.push({ target: t.label, error: e.message, diagnostics: e.diagnostics });
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
if (!json)
|
|
99
|
+
console.error(chalk.red(`✗ ${t.label}: ${e.message}`));
|
|
100
|
+
results.push({ target: t.label, error: e.message });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (json)
|
|
105
|
+
console.log(JSON.stringify(results, null, 2));
|
|
106
|
+
return failed ? 1 : 0;
|
|
107
|
+
}
|
|
108
|
+
export async function checkCommand(argv) {
|
|
109
|
+
const project = await Project.open(argv.root);
|
|
110
|
+
const r = await checkProject(project);
|
|
111
|
+
const errors = r.diagnostics.filter((d) => d.severity === 'error').length;
|
|
112
|
+
const warnings = r.diagnostics.length - errors;
|
|
113
|
+
if (argv.json) {
|
|
114
|
+
console.log(JSON.stringify(r, null, 2));
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
printDiagnostics(r.diagnostics, false);
|
|
118
|
+
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'}`;
|
|
119
|
+
console.log(errors ? chalk.red(`✗ ${summary}`) : `${chalk.green('✓')} ${summary}`);
|
|
120
|
+
}
|
|
121
|
+
return errors ? 1 : 0;
|
|
122
|
+
}
|
|
123
|
+
export async function fieldsCommand(argv) {
|
|
124
|
+
const name = argv._?.[0];
|
|
125
|
+
if (!name)
|
|
126
|
+
throw new UsageError('usage: latex-kit fields <template>');
|
|
127
|
+
const project = await Project.open(argv.root);
|
|
128
|
+
const { fields, diagnostics } = await templateFields(project, String(name));
|
|
129
|
+
if (argv.json) {
|
|
130
|
+
console.log(JSON.stringify(fields, null, 2));
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
printDiagnostics(diagnostics, false);
|
|
134
|
+
const width = Math.max(...fields.map((f) => f.absolute.length), 4);
|
|
135
|
+
for (const f of fields) {
|
|
136
|
+
const filters = f.filters.length ? chalk.cyan(` | ${f.filters.join(' | ')}`) : '';
|
|
137
|
+
console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(5))} ${chalk.dim(`${f.file}:${f.line}`)}${filters}`);
|
|
138
|
+
}
|
|
139
|
+
return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
|
|
140
|
+
}
|
|
141
|
+
export async function typegenCommand(argv) {
|
|
142
|
+
const project = await Project.open(argv.root);
|
|
143
|
+
let n = 0;
|
|
144
|
+
for (const name of project.templateNames()) {
|
|
145
|
+
const t = await project.template(name);
|
|
146
|
+
if (!t.jsonSchema)
|
|
147
|
+
continue;
|
|
148
|
+
const schemaFile = join(t.dir, `${name}.schema.json`);
|
|
149
|
+
const typesFile = join(t.dir, 'types.d.ts');
|
|
150
|
+
writeFileSync(schemaFile, JSON.stringify(documentJsonSchema(name, t.jsonSchema), null, 2) + '\n');
|
|
151
|
+
writeFileSync(typesFile, `// Generated by latex-kit typegen from schema.ts. Do not edit.\n${generateTypes(name, t.jsonSchema)}\n`);
|
|
152
|
+
console.log(`${chalk.green('✓')} ${rel(schemaFile)} ${rel(typesFile)}`);
|
|
153
|
+
n++;
|
|
154
|
+
}
|
|
155
|
+
if (n === 0)
|
|
156
|
+
console.log(chalk.yellow('no templates with a schema.ts'));
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
export async function styCommand(argv) {
|
|
160
|
+
const project = await Project.open(argv.root);
|
|
161
|
+
const dir = argv._?.[0] ? join(process.cwd(), String(argv._[0])) : project.templatesDir;
|
|
162
|
+
mkdirSync(dir, { recursive: true });
|
|
163
|
+
const file = join(dir, 'latex-kit.sty');
|
|
164
|
+
writeFileSync(file, LATEX_KIT_STY);
|
|
165
|
+
console.log(`${chalk.green('✓')} ${rel(file)} (lets editors compile templates as blank previews)`);
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
export async function importCommand(argv) {
|
|
169
|
+
const file = argv._?.[0];
|
|
170
|
+
if (!file)
|
|
171
|
+
throw new UsageError('usage: latex-kit import <file.docx|.md|.html|.tex> [--name <template>] [--force]');
|
|
172
|
+
const project = await Project.open(argv.root);
|
|
173
|
+
const r = await importDocument(project, String(file), {
|
|
174
|
+
name: argv.name,
|
|
175
|
+
force: Boolean(argv.force),
|
|
176
|
+
backend: argv.local ? 'local' : undefined,
|
|
177
|
+
schema: argv.schema !== false,
|
|
178
|
+
});
|
|
179
|
+
console.log(`${chalk.green('✓')} ${rel(r.template)}`);
|
|
180
|
+
if (r.media)
|
|
181
|
+
console.log(chalk.dim(` images in ${rel(r.media)}`));
|
|
182
|
+
console.log(chalk.dim(` ${r.converted.length} placeholder${r.converted.length === 1 ? '' : 's'} became \\field{…}`));
|
|
183
|
+
for (const s of r.skipped)
|
|
184
|
+
console.log(chalk.yellow(` line ${s.line}: left ${s.from} as is (not a valid field path)`));
|
|
185
|
+
if (r.schema)
|
|
186
|
+
console.log(chalk.dim(` starter schema: ${rel(r.schema)} (every field is a string; tighten it)`));
|
|
187
|
+
console.log(chalk.dim(` next: latex-kit fields ${r.name}, then latex-kit build --variant blank --template ${r.name}`));
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
|
190
|
+
export async function diffCommand(argv) {
|
|
191
|
+
const args = (argv._ ?? []).map(String);
|
|
192
|
+
const variant = (argv.variant ?? 'final');
|
|
193
|
+
if (!VARIANTS.includes(variant))
|
|
194
|
+
throw new UsageError(`--variant must be one of ${VARIANTS.join(', ')}`);
|
|
195
|
+
const project = await Project.open(argv.root);
|
|
196
|
+
const options = { variant, engine: argv.engine, backend: argv.local ? 'local' : undefined, image: argv.image, platform: argv.platform };
|
|
197
|
+
const abs = (p) => join(process.cwd(), p);
|
|
198
|
+
let result;
|
|
199
|
+
try {
|
|
200
|
+
if (args.length === 2 && !argv.against) {
|
|
201
|
+
result = await diffFiles(project, abs(args[0]), abs(args[1]), options);
|
|
202
|
+
}
|
|
203
|
+
else if (args.length === 1 && argv.against) {
|
|
204
|
+
result = await diffDocument(project, abs(args[0]), String(argv.against), options);
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
throw new UsageError('usage: latex-kit diff <old.tex> <new.tex>\n latex-kit diff <document> --against <git-ref>');
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
catch (e) {
|
|
211
|
+
if (e instanceof BuildError) {
|
|
212
|
+
printDiagnostics(e.diagnostics, Boolean(argv.json));
|
|
213
|
+
console.error(chalk.red(`✗ ${e.message}`));
|
|
214
|
+
return 1;
|
|
215
|
+
}
|
|
216
|
+
throw e;
|
|
217
|
+
}
|
|
218
|
+
if (argv.json)
|
|
219
|
+
console.log(JSON.stringify({ pdf: rel(result.pdf), tex: rel(result.tex), old: rel(result.old), new: rel(result.new) }, null, 2));
|
|
220
|
+
else
|
|
221
|
+
console.log(`${chalk.green('✓')} ${rel(result.pdf)} ${chalk.dim('(insertions underlined in blue, deletions struck through in red)')}`);
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
export async function initCommand(argv) {
|
|
225
|
+
const dir = join(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
|
|
226
|
+
const r = initProject(dir, { paper: Boolean(argv.paper), force: Boolean(argv.force), version: version() });
|
|
227
|
+
for (const f of r.written)
|
|
228
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
229
|
+
for (const f of r.skipped)
|
|
230
|
+
console.log(chalk.dim(` kept ${rel(f)} (exists)`));
|
|
231
|
+
const cd = rel(dir) === '.' ? '' : `cd ${rel(dir)} && `;
|
|
232
|
+
console.log(argv.paper
|
|
233
|
+
? chalk.dim(`\nnext: ${cd}latex-kit render paper/main.tex --verify`)
|
|
234
|
+
: chalk.dim(`\nnext: ${cd}latex-kit check && latex-kit build`));
|
|
235
|
+
return 0;
|
|
236
|
+
}
|
|
237
|
+
export async function newCommand(argv) {
|
|
238
|
+
const [kind, name] = (argv._ ?? []).map(String);
|
|
239
|
+
const project = await Project.open(argv.root);
|
|
240
|
+
if (kind === 'template' && name) {
|
|
241
|
+
const r = newTemplate(project, name, Boolean(argv.force));
|
|
242
|
+
for (const f of r.written)
|
|
243
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
244
|
+
console.log(chalk.dim(`\nnext: latex-kit new document <name> --template ${name}`));
|
|
245
|
+
return 0;
|
|
246
|
+
}
|
|
247
|
+
if (kind === 'document' && name) {
|
|
248
|
+
if (!argv.template)
|
|
249
|
+
throw new UsageError('usage: latex-kit new document <name> --template <template>');
|
|
250
|
+
const r = await newDocument(project, name, String(argv.template), Boolean(argv.force));
|
|
251
|
+
for (const f of r.written)
|
|
252
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
253
|
+
if (r.schemaFile)
|
|
254
|
+
console.log(chalk.dim(` editors autocomplete it from ${rel(r.schemaFile)}`));
|
|
255
|
+
console.log(chalk.dim(`\nnext: fill in the data, then latex-kit build ${r.written[0] ? rel(r.written[0]) : ''}`));
|
|
256
|
+
return 0;
|
|
257
|
+
}
|
|
258
|
+
throw new UsageError('usage: latex-kit new template <name>\n latex-kit new document <name> --template <template>');
|
|
259
|
+
}
|
|
260
|
+
export async function cleanCommand(argv) {
|
|
261
|
+
const project = await Project.open(argv.root);
|
|
262
|
+
const rel = relative(project.root, project.outDir);
|
|
263
|
+
if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
|
|
264
|
+
throw new UsageError(`refusing to delete ${project.outDir}: the out folder must be inside the project`);
|
|
265
|
+
if (!existsSync(project.outDir)) {
|
|
266
|
+
console.log(chalk.dim(`nothing to clean (${project.rel(project.outDir)}/ does not exist)`));
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
rmSync(project.outDir, { recursive: true, force: true });
|
|
270
|
+
console.log(`${chalk.green('✓')} removed ${project.rel(project.outDir)}/`);
|
|
271
|
+
return 0;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
275
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
276
|
+
*/
|
|
277
|
+
export async function watchCommand(argv) {
|
|
278
|
+
const variant = (argv.variant ?? 'draft');
|
|
279
|
+
if (variant === 'final' || variant === 'signed')
|
|
280
|
+
throw new UsageError('watch builds drafts or blanks; run latex-kit build --final when you are done');
|
|
281
|
+
const project = await Project.open(argv.root);
|
|
282
|
+
const dirs = [project.config.templates, project.config.snippets, project.config.clauses, project.config.data, project.config.documents]
|
|
283
|
+
.map((d) => project.path(d))
|
|
284
|
+
.filter((d) => existsSync(d));
|
|
285
|
+
if (dirs.length === 0)
|
|
286
|
+
throw new UsageError('nothing to watch: no templates/, data/ or documents/ here');
|
|
287
|
+
let running = false;
|
|
288
|
+
let again = false;
|
|
289
|
+
let timer = null;
|
|
290
|
+
const run = async () => {
|
|
291
|
+
if (running) {
|
|
292
|
+
again = true;
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
running = true;
|
|
296
|
+
console.log(chalk.dim(`\n— ${new Date().toLocaleTimeString()} —`));
|
|
297
|
+
try {
|
|
298
|
+
await buildCommand({ ...argv, variant });
|
|
299
|
+
}
|
|
300
|
+
catch (e) {
|
|
301
|
+
console.error(chalk.red(e.message));
|
|
302
|
+
}
|
|
303
|
+
running = false;
|
|
304
|
+
if (again) {
|
|
305
|
+
again = false;
|
|
306
|
+
void run();
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
const schedule = (file) => {
|
|
310
|
+
// generated files and editor swap files are not changes worth a build
|
|
311
|
+
if (file && /(\.schema\.json|types\.d\.ts|~|\.swp)$/.test(file))
|
|
312
|
+
return;
|
|
313
|
+
if (timer)
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
timer = setTimeout(() => void run(), 250);
|
|
316
|
+
};
|
|
317
|
+
for (const d of dirs)
|
|
318
|
+
fsWatch(d, { recursive: true }, (_event, file) => schedule(file ? String(file) : null));
|
|
319
|
+
console.log(chalk.dim(`watching ${dirs.map((d) => project.rel(d)).join(', ')} (Ctrl-C to stop)`));
|
|
320
|
+
await run();
|
|
321
|
+
return new Promise(() => {
|
|
322
|
+
// runs until interrupted
|
|
323
|
+
});
|
|
324
|
+
}
|
package/esm/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
|
+
}
|