latex-kit 0.3.0 → 0.5.0
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 +22 -3
- package/args.js +3 -3
- package/boilerplates.d.ts +8 -0
- package/boilerplates.js +225 -0
- package/build.d.ts +28 -2
- package/build.js +233 -94
- package/check.js +4 -3
- package/cli.js +14 -3
- package/commands.js +7 -0
- package/config.d.ts +14 -3
- package/config.js +1 -1
- package/diff.d.ts +25 -0
- package/diff.js +112 -0
- package/esm/args.js +3 -3
- package/esm/boilerplates.d.ts +8 -0
- package/esm/boilerplates.js +220 -0
- package/esm/build.d.ts +28 -2
- package/esm/build.js +234 -97
- package/esm/check.js +4 -3
- package/esm/cli.js +14 -3
- package/esm/commands.js +8 -1
- package/esm/config.d.ts +14 -3
- package/esm/config.js +1 -1
- 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 +9 -2
- package/esm/index.js +8 -2
- package/esm/lock.d.ts +24 -0
- package/esm/lock.js +50 -0
- package/esm/project-commands.d.ts +14 -0
- package/esm/project-commands.js +232 -7
- package/esm/project.d.ts +20 -1
- package/esm/project.js +105 -4
- package/esm/render.js +6 -6
- package/esm/scaffold.d.ts +27 -0
- package/esm/scaffold.js +108 -0
- package/esm/usage.js +40 -7
- package/import.d.ts +24 -0
- package/import.js +118 -0
- package/index.d.ts +9 -2
- package/index.js +27 -2
- package/lock.d.ts +24 -0
- package/lock.js +57 -0
- package/package.json +6 -5
- package/project-commands.d.ts +14 -0
- package/project-commands.js +238 -5
- package/project.d.ts +20 -1
- package/project.js +103 -2
- package/render.js +5 -5
- package/scaffold.d.ts +27 -0
- package/scaffold.js +115 -0
- package/usage.js +40 -7
package/esm/project.js
CHANGED
|
@@ -1,22 +1,107 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { BUILTIN_COMPONENTS } from '@latex-kit/components';
|
|
2
|
+
import { DATA_EXTENSIONS, loadModule, loadTemplateSchema, toJsonSchema } from '@latex-kit/schema';
|
|
3
|
+
import { compileTemplate, diag, isRelativeName, parseClauseHeader } from '@latex-kit/template';
|
|
3
4
|
import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
|
|
4
5
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'path';
|
|
5
6
|
import { loadConfig } from './config';
|
|
7
|
+
import { readLock } from './lock';
|
|
8
|
+
const CODE_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'];
|
|
9
|
+
/** Every code file under `dir`, as [name without extension, absolute path]. */
|
|
10
|
+
function codeFiles(dir) {
|
|
11
|
+
const out = [];
|
|
12
|
+
const walk = (d, prefix) => {
|
|
13
|
+
if (!existsSync(d))
|
|
14
|
+
return;
|
|
15
|
+
for (const name of readdirSync(d).sort()) {
|
|
16
|
+
if (name.startsWith('.') || name.startsWith('_'))
|
|
17
|
+
continue;
|
|
18
|
+
const p = join(d, name);
|
|
19
|
+
if (statSync(p).isDirectory())
|
|
20
|
+
walk(p, `${prefix}${name}/`);
|
|
21
|
+
else if (CODE_EXTENSIONS.includes(extname(name)) && !name.endsWith('.d.ts'))
|
|
22
|
+
out.push([`${prefix}${name.slice(0, -extname(name).length)}`, p]);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
walk(dir, '');
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
6
28
|
const SCHEMA_FILES = ['schema.ts', 'schema.mts', 'schema.js', 'schema.mjs', 'schema.cjs'];
|
|
7
29
|
/** A latex-kit project: a folder with templates, data and documents. */
|
|
8
30
|
export class Project {
|
|
9
31
|
root;
|
|
10
32
|
config;
|
|
33
|
+
lock;
|
|
11
34
|
templates = new Map();
|
|
12
35
|
snippets = new Map();
|
|
13
|
-
|
|
36
|
+
clauses = new Map();
|
|
37
|
+
/** Clauses written in TypeScript, loaded when the project opens. */
|
|
38
|
+
codeClauses = new Map();
|
|
39
|
+
/** Built-in components, then the project's own (which win). */
|
|
40
|
+
components = { ...BUILTIN_COMPONENTS };
|
|
41
|
+
/** Source files of the project's components, by name. */
|
|
42
|
+
componentFiles = {};
|
|
43
|
+
/** Problems loading components/ and TypeScript clauses. */
|
|
44
|
+
codeDiagnostics = [];
|
|
45
|
+
constructor(root, config,
|
|
46
|
+
/** latex-kit.lock, when the project has one. */
|
|
47
|
+
lock) {
|
|
14
48
|
this.root = root;
|
|
15
49
|
this.config = config;
|
|
50
|
+
this.lock = lock;
|
|
16
51
|
}
|
|
17
52
|
static async open(root = process.cwd()) {
|
|
18
53
|
const abs = resolve(root);
|
|
19
|
-
|
|
54
|
+
const project = new Project(abs, await loadConfig(abs), readLock(abs));
|
|
55
|
+
await project.loadCode();
|
|
56
|
+
return project;
|
|
57
|
+
}
|
|
58
|
+
/** The Docker image to build with: --image, then config, then latex-kit.lock. */
|
|
59
|
+
image(override) {
|
|
60
|
+
return override ?? this.config.image ?? this.lock?.image;
|
|
61
|
+
}
|
|
62
|
+
async loadCode() {
|
|
63
|
+
for (const [name, file] of codeFiles(this.path(this.config.components))) {
|
|
64
|
+
const at = { file: this.rel(file), line: 1, column: 1 };
|
|
65
|
+
this.componentFiles[name] = file;
|
|
66
|
+
try {
|
|
67
|
+
const mod = await loadModule(file);
|
|
68
|
+
const fn = mod.default;
|
|
69
|
+
if (typeof fn !== 'function')
|
|
70
|
+
throw new Error('the default export must be a component function (use defineComponent)');
|
|
71
|
+
this.components[name] = fn;
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
this.codeDiagnostics.push(diag('error', `component ${name}: ${e.message}`, at));
|
|
75
|
+
const message = e.message;
|
|
76
|
+
this.components[name] = () => {
|
|
77
|
+
throw new Error(`failed to load: ${message}`);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
for (const [id, file] of codeFiles(this.path(this.config.clauses))) {
|
|
82
|
+
const at = { file: this.rel(file), line: 1, column: 1 };
|
|
83
|
+
try {
|
|
84
|
+
const mod = await loadModule(file);
|
|
85
|
+
const def = mod.default;
|
|
86
|
+
if (!def || typeof def !== 'object' || (typeof def.body !== 'string' && typeof def.render !== 'function')) {
|
|
87
|
+
throw new Error('the default export must be defineClause({ title, version, body | render })');
|
|
88
|
+
}
|
|
89
|
+
this.codeClauses.set(id, {
|
|
90
|
+
id,
|
|
91
|
+
title: def.title,
|
|
92
|
+
version: def.version === undefined ? undefined : String(def.version),
|
|
93
|
+
template: compileTemplate(def.body ?? '', this.rel(file)),
|
|
94
|
+
render: def.render,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
this.codeDiagnostics.push(diag('error', `clause ${id}: ${e.message}`, at));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Names \\component can use. */
|
|
103
|
+
componentNames() {
|
|
104
|
+
return Object.keys(this.components).sort();
|
|
20
105
|
}
|
|
21
106
|
path(...parts) {
|
|
22
107
|
return join(this.root, ...parts);
|
|
@@ -118,6 +203,22 @@ export class Project {
|
|
|
118
203
|
}
|
|
119
204
|
return null;
|
|
120
205
|
};
|
|
206
|
+
/** \\clause{id}: `clauses/<id>.tex` (or `.ts`) from the clause library. */
|
|
207
|
+
loadClause = (id) => {
|
|
208
|
+
if (this.clauses.has(id))
|
|
209
|
+
return this.clauses.get(id);
|
|
210
|
+
let loaded = null;
|
|
211
|
+
const file = join(this.path(this.config.clauses), `${id}.tex`);
|
|
212
|
+
if (isRelativeName(id) && existsSync(file)) {
|
|
213
|
+
const text = readFileSync(file, 'utf8');
|
|
214
|
+
loaded = { id, template: compileTemplate(text, this.rel(file)), ...parseClauseHeader(text) };
|
|
215
|
+
}
|
|
216
|
+
else if (this.codeClauses.has(id)) {
|
|
217
|
+
loaded = this.codeClauses.get(id);
|
|
218
|
+
}
|
|
219
|
+
this.clauses.set(id, loaded);
|
|
220
|
+
return loaded;
|
|
221
|
+
};
|
|
121
222
|
/** Absolute paths of every snippet loaded so far. */
|
|
122
223
|
snippetFiles() {
|
|
123
224
|
return [...this.snippets.keys()];
|
package/esm/render.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { formatDiagnostic, render, RenderError } from '@latex-kit/render';
|
|
2
|
-
import {
|
|
3
|
-
import { dirname, relative } from 'path';
|
|
2
|
+
import { relative } from 'path';
|
|
4
3
|
import chalk from 'yanse';
|
|
5
4
|
import { renderOptionsFromArgv, UsageError } from './args';
|
|
6
5
|
function summary(r) {
|
|
@@ -8,6 +7,7 @@ function summary(r) {
|
|
|
8
7
|
pdf: relative(process.cwd(), r.pdf),
|
|
9
8
|
sha256: r.sha256,
|
|
10
9
|
engine: r.engine,
|
|
10
|
+
engineReason: r.engineReason,
|
|
11
11
|
backend: r.backend,
|
|
12
12
|
image: r.image,
|
|
13
13
|
sourceDateEpoch: r.sourceDateEpoch,
|
|
@@ -39,8 +39,9 @@ export async function renderCommand(argv, prompter) {
|
|
|
39
39
|
console.error(s);
|
|
40
40
|
};
|
|
41
41
|
try {
|
|
42
|
-
log(chalk.dim(`rendering ${opts.file}
|
|
42
|
+
log(chalk.dim(`rendering ${opts.file} (${opts.backend})…`));
|
|
43
43
|
const first = await render({ ...opts, file: opts.file });
|
|
44
|
+
log(chalk.dim(` engine ${first.engine}${first.engineReason === 'chosen' ? '' : ` (${first.engineReason})`}`));
|
|
44
45
|
for (const d of first.diagnostics)
|
|
45
46
|
log(chalk.yellow(formatDiagnostic(d)));
|
|
46
47
|
if (!first.reproducible) {
|
|
@@ -48,11 +49,10 @@ export async function renderCommand(argv, prompter) {
|
|
|
48
49
|
}
|
|
49
50
|
let verified;
|
|
50
51
|
if (argv.verify) {
|
|
51
|
-
|
|
52
|
+
// same output path: some tools (Ghostscript) hash the path into the PDF ID
|
|
52
53
|
log(chalk.dim('rendering again to check the output is byte-identical…'));
|
|
53
|
-
const second = await render({ ...opts, file: opts.file,
|
|
54
|
+
const second = await render({ ...opts, file: opts.file, engine: first.engine, sourceDateEpoch: first.sourceDateEpoch });
|
|
54
55
|
verified = second.sha256 === first.sha256;
|
|
55
|
-
rmSync(dirname(second.pdf), { recursive: true, force: true });
|
|
56
56
|
}
|
|
57
57
|
if (argv.json) {
|
|
58
58
|
console.log(JSON.stringify({ ...summary(first), verified }, null, 2));
|
|
@@ -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 {};
|
package/esm/scaffold.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { documentJsonSchema } from '@latex-kit/schema';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'fs';
|
|
3
|
+
import { dirname, join, relative } from 'path';
|
|
4
|
+
import { paperFiles, projectFiles, templateFiles } from './boilerplates';
|
|
5
|
+
import { CONFIG_FILES } from './config';
|
|
6
|
+
/** Write files under `dir`. Existing files are kept unless `force`. */
|
|
7
|
+
export function writeFiles(dir, files, force = false) {
|
|
8
|
+
const written = [];
|
|
9
|
+
const skipped = [];
|
|
10
|
+
for (const [rel, content] of Object.entries(files)) {
|
|
11
|
+
const file = join(dir, rel);
|
|
12
|
+
if (existsSync(file) && !force) {
|
|
13
|
+
skipped.push(file);
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
17
|
+
writeFileSync(file, content);
|
|
18
|
+
written.push(file);
|
|
19
|
+
}
|
|
20
|
+
return { written, skipped };
|
|
21
|
+
}
|
|
22
|
+
/** Scaffold a latex-kit project (or a paper) in `dir`. */
|
|
23
|
+
export function initProject(dir, options) {
|
|
24
|
+
mkdirSync(dir, { recursive: true });
|
|
25
|
+
if (!options.paper && !options.force) {
|
|
26
|
+
const existing = CONFIG_FILES.find((f) => existsSync(join(dir, f)));
|
|
27
|
+
if (existing)
|
|
28
|
+
throw new Error(`${join(dir, existing)} already exists; use --force to add the starter files anyway`);
|
|
29
|
+
}
|
|
30
|
+
return writeFiles(dir, options.paper ? paperFiles() : projectFiles(options.version), options.force);
|
|
31
|
+
}
|
|
32
|
+
export function newTemplate(project, name, force = false) {
|
|
33
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
34
|
+
throw new Error(`invalid template name "${name}" (use lowercase letters, digits and -)`);
|
|
35
|
+
if (existsSync(join(project.templatesDir, name)) && !force)
|
|
36
|
+
throw new Error(`template ${name} already exists`);
|
|
37
|
+
const files = templateFiles(name);
|
|
38
|
+
const mapped = {};
|
|
39
|
+
for (const [rel, content] of Object.entries(files))
|
|
40
|
+
mapped[join(project.config.templates, rel.replace(/^templates\//, ''))] = content;
|
|
41
|
+
return writeFiles(project.root, mapped, force);
|
|
42
|
+
}
|
|
43
|
+
/** A placeholder value for a JSON Schema: required fields only, typed. */
|
|
44
|
+
export function skeleton(schema, root, depth = 0) {
|
|
45
|
+
if (!schema || depth > 12)
|
|
46
|
+
return '';
|
|
47
|
+
if (typeof schema.$ref === 'string') {
|
|
48
|
+
const m = /^#\/(\$defs|definitions)\/(.+)$/.exec(schema.$ref);
|
|
49
|
+
const target = m ? root[m[1]]?.[m[2]] : undefined;
|
|
50
|
+
return skeleton(target, root, depth + 1);
|
|
51
|
+
}
|
|
52
|
+
if ('default' in schema)
|
|
53
|
+
return schema.default;
|
|
54
|
+
if ('const' in schema)
|
|
55
|
+
return schema.const;
|
|
56
|
+
if (Array.isArray(schema.enum))
|
|
57
|
+
return schema.enum[0];
|
|
58
|
+
const alt = (schema.anyOf ?? schema.oneOf);
|
|
59
|
+
if (alt?.length)
|
|
60
|
+
return skeleton(alt.find((a) => a.type !== 'null') ?? alt[0], root, depth + 1);
|
|
61
|
+
const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
|
|
62
|
+
switch (type) {
|
|
63
|
+
case 'object': {
|
|
64
|
+
const props = (schema.properties ?? {});
|
|
65
|
+
const required = (schema.required ?? []);
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const key of required)
|
|
68
|
+
out[key] = skeleton(props[key], root, depth + 1);
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
case 'array':
|
|
72
|
+
return [];
|
|
73
|
+
case 'number':
|
|
74
|
+
case 'integer':
|
|
75
|
+
return 0;
|
|
76
|
+
case 'boolean':
|
|
77
|
+
return false;
|
|
78
|
+
case 'string':
|
|
79
|
+
return typeof schema.pattern === 'string' && schema.pattern.includes('\\d{4}-\\d{2}-\\d{2}') ? '2026-01-01' : '';
|
|
80
|
+
default:
|
|
81
|
+
return '';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* documents/<name>.json for a template: every required field with a
|
|
86
|
+
* placeholder, and `$schema` pointing at the generated JSON Schema so editors
|
|
87
|
+
* autocomplete and validate it.
|
|
88
|
+
*/
|
|
89
|
+
export async function newDocument(project, name, templateName, force = false) {
|
|
90
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
91
|
+
throw new Error(`invalid document name "${name}" (use lowercase letters, digits and -)`);
|
|
92
|
+
const existing = existsSync(project.documentsDir) ? readdirSync(project.documentsDir).find((f) => f.replace(/\.[^.]+$/, '') === name) : undefined;
|
|
93
|
+
if (existing && !force)
|
|
94
|
+
throw new Error(`documents/${existing} already exists`);
|
|
95
|
+
const template = await project.template(templateName);
|
|
96
|
+
const file = join(project.documentsDir, `${name}.json`);
|
|
97
|
+
let schemaFile = null;
|
|
98
|
+
const record = {};
|
|
99
|
+
if (template.jsonSchema) {
|
|
100
|
+
schemaFile = join(template.dir, `${templateName}.schema.json`);
|
|
101
|
+
writeFileSync(schemaFile, JSON.stringify(documentJsonSchema(templateName, template.jsonSchema), null, 2) + '\n');
|
|
102
|
+
record.$schema = relative(project.documentsDir, schemaFile).split('\\').join('/');
|
|
103
|
+
}
|
|
104
|
+
record.template = templateName;
|
|
105
|
+
record.data = template.jsonSchema ? skeleton(template.jsonSchema, template.jsonSchema) : {};
|
|
106
|
+
const r = writeFiles(dirname(file), { [`${name}.json`]: JSON.stringify(record, null, 2) + '\n' }, force);
|
|
107
|
+
return { ...r, schemaFile };
|
|
108
|
+
}
|
package/esm/usage.js
CHANGED
|
@@ -3,12 +3,28 @@ const MAIN = `latex-kit — build typed, reproducible LaTeX documents
|
|
|
3
3
|
Usage
|
|
4
4
|
latex-kit <command> [options]
|
|
5
5
|
|
|
6
|
+
Start
|
|
7
|
+
init [dir] A new project: a letter template, data and a record
|
|
8
|
+
init [dir] --paper A paper: main.tex, refs.bib and a GitHub Actions workflow
|
|
9
|
+
new template <name> A template folder with template.tex and schema.ts
|
|
10
|
+
new document <name> --template <t>
|
|
11
|
+
A record with every required field, linked to its schema
|
|
12
|
+
|
|
6
13
|
Project commands (run in a folder with templates/, data/, documents/)
|
|
7
14
|
build [documents…] Fill templates with records and build PDFs
|
|
15
|
+
watch [documents…] Rebuild drafts whenever a template, clause or record changes
|
|
16
|
+
clean Delete the out/ folder
|
|
8
17
|
check Check templates, schemas, records and IDs without TeX
|
|
9
18
|
fields <template> List every field a template reads
|
|
10
19
|
typegen Write JSON Schema and .d.ts for each template's data
|
|
11
20
|
sty [dir] Write latex-kit.sty so editors can preview templates
|
|
21
|
+
lock [--check] Pin the TeX and pandoc images in latex-kit.lock
|
|
22
|
+
import <file> Turn a Word/Markdown/HTML document (or an older .tex)
|
|
23
|
+
into a template; {{x}} and @GROUP@FIELD@ become \\field
|
|
24
|
+
diff <document> --against <ref>
|
|
25
|
+
Redline PDF of a document against an earlier commit
|
|
26
|
+
diff <old.tex> <new.tex>
|
|
27
|
+
Redline PDF of any two .tex files
|
|
12
28
|
|
|
13
29
|
Other commands
|
|
14
30
|
render <file.tex> Build a plain .tex file with latexmk in a pinned image
|
|
@@ -26,16 +42,19 @@ always produces the same PDF bytes.
|
|
|
26
42
|
|
|
27
43
|
Options
|
|
28
44
|
-o, --out <dir> Output directory, relative to --root (default: out)
|
|
29
|
-
-e, --engine <name>
|
|
45
|
+
-e, --engine <name> auto (default), lualatex, xelatex, pdflatex or pdfps
|
|
30
46
|
--root <dir> Directory TeX can see (default: current directory)
|
|
31
|
-
--image <ref> Docker image (default: pinned
|
|
32
|
-
--platform <os/arch> Docker --platform (default:
|
|
47
|
+
--image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
|
|
48
|
+
--platform <os/arch> Docker --platform (default: native)
|
|
33
49
|
--local Use latexmk on PATH instead of Docker (not pinned)
|
|
34
50
|
--source-date-epoch <s> Build timestamp in seconds since 1970
|
|
35
51
|
--verify Build twice and fail if the PDFs differ
|
|
36
52
|
--json Print a JSON summary on stdout
|
|
37
53
|
|
|
38
|
-
|
|
54
|
+
auto reads the file: a "% !TEX program =" line wins; PSTricks packages
|
|
55
|
+
pick pdfps, xeCJK or ctex pick xelatex, CJK/CJKutf8 pick pdflatex, and
|
|
56
|
+
everything else uses lualatex, the only engine that is byte-reproducible in
|
|
57
|
+
the default image.
|
|
39
58
|
`;
|
|
40
59
|
const BUILD = `latex-kit build [documents…] [options]
|
|
41
60
|
|
|
@@ -47,20 +66,34 @@ Variants
|
|
|
47
66
|
as red markers (they fail instead when CI=true or --strict)
|
|
48
67
|
--variant final No marks. Missing values fail. Mints a document ID on the
|
|
49
68
|
--final first build and saves it in the record (JSON/YAML)
|
|
50
|
-
--variant signed Like final
|
|
69
|
+
--variant signed Like final, and \\signature blocks are signed: each signer's
|
|
70
|
+
image from --signatures (a folder outside the repo,
|
|
71
|
+
<name>.png|pdf|jpg or the signer's "signature" file),
|
|
72
|
+
else "/s/ Name"; dates come from the record:
|
|
73
|
+
signed: { discloser: { date: 2026-11-25 } }
|
|
51
74
|
--variant blank Every field is a labelled line. With no documents, builds
|
|
52
75
|
each template (or --template <name>) as an empty form
|
|
53
76
|
|
|
54
77
|
Options
|
|
55
78
|
--template <name> Only documents that use this template
|
|
79
|
+
--only <names> Only these documents (or templates, for blanks);
|
|
80
|
+
comma-separated, * matches anything: --only 'nda-*'
|
|
81
|
+
--locale <tag> Build in another locale (dates, numbers, bilingual
|
|
82
|
+
order); writes <document>-<tag>.pdf
|
|
83
|
+
--signatures <dir> Signature images for --variant signed
|
|
56
84
|
--strict Fail on missing values in drafts too
|
|
57
|
-
|
|
85
|
+
--force Rebuild even if the PDF is up to date
|
|
86
|
+
-e, --engine <name> auto (default), lualatex, xelatex, pdflatex or pdfps
|
|
58
87
|
--local Use latexmk on PATH instead of Docker
|
|
59
|
-
--image <ref> Docker image (default: pinned
|
|
88
|
+
--image <ref> Docker image (default: latex-kit.lock, else the pinned
|
|
89
|
+
ghcr.io/constructive-io/latex-kit)
|
|
60
90
|
--verify Build twice and fail unless the PDFs are identical
|
|
61
91
|
--tex-only Write the .tex without running TeX
|
|
62
92
|
--json JSON results on stdout
|
|
63
93
|
--root <dir> Project folder (default: current directory)
|
|
94
|
+
|
|
95
|
+
A build is skipped ("unchanged") when the last PDF came from exactly the
|
|
96
|
+
same .tex, template folder, engine, image and build date.
|
|
64
97
|
`;
|
|
65
98
|
const DOCTOR = `latex-kit doctor [--image <ref>] [--json]
|
|
66
99
|
|
package/import.d.ts
ADDED
|
@@ -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>;
|
package/import.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.templateNameFor = templateNameFor;
|
|
4
|
+
exports.starterSchema = starterSchema;
|
|
5
|
+
exports.importDocument = importDocument;
|
|
6
|
+
const render_1 = require("@latex-kit/render");
|
|
7
|
+
const template_1 = require("@latex-kit/template");
|
|
8
|
+
const fs_1 = require("fs");
|
|
9
|
+
const path_1 = require("path");
|
|
10
|
+
function templateNameFor(file) {
|
|
11
|
+
return ((0, path_1.basename)(file, (0, path_1.extname)(file))
|
|
12
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
13
|
+
.toLowerCase()
|
|
14
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
15
|
+
.replace(/^-|-$/g, '') || 'imported');
|
|
16
|
+
}
|
|
17
|
+
/** A zod schema source with every converted field as a string, nested by path. */
|
|
18
|
+
function starterSchema(paths) {
|
|
19
|
+
const root = {};
|
|
20
|
+
const conflicts = new Set();
|
|
21
|
+
for (const p of paths) {
|
|
22
|
+
const segs = p.split('.');
|
|
23
|
+
if (segs[0].startsWith('$'))
|
|
24
|
+
continue;
|
|
25
|
+
let node = root;
|
|
26
|
+
segs.forEach((seg, i) => {
|
|
27
|
+
const last = i === segs.length - 1;
|
|
28
|
+
const key = /^\d+$/.test(seg) ? null : seg;
|
|
29
|
+
if (key === null)
|
|
30
|
+
return; // list indexes: leave lists to the author
|
|
31
|
+
if (last) {
|
|
32
|
+
if (node[key] && node[key] !== null)
|
|
33
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
34
|
+
else
|
|
35
|
+
node[key] = null;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
if (node[key] === null)
|
|
39
|
+
conflicts.add(segs.slice(0, i + 1).join('.'));
|
|
40
|
+
node[key] ??= {};
|
|
41
|
+
node = node[key];
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const render = (t, indent) => Object.keys(t)
|
|
46
|
+
.sort()
|
|
47
|
+
.map((k) => {
|
|
48
|
+
const name = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
|
|
49
|
+
const v = t[k];
|
|
50
|
+
return v === null ? `${indent}${name}: z.string(),` : `${indent}${name}: z.object({\n${render(v, indent + ' ')}\n${indent}}),`;
|
|
51
|
+
})
|
|
52
|
+
.join('\n');
|
|
53
|
+
const note = conflicts.size ? `\n// Used both as a value and as a group, check: ${[...conflicts].join(', ')}` : '';
|
|
54
|
+
return `// Starter schema written by \`latex-kit import\`: every field is a string.
|
|
55
|
+
// Tighten the types (numbers, dates, lists) and add the fields' rules.${note}
|
|
56
|
+
import { z } from 'latex-kit';
|
|
57
|
+
|
|
58
|
+
export default z.object({
|
|
59
|
+
${render(root, ' ')}
|
|
60
|
+
});
|
|
61
|
+
`;
|
|
62
|
+
}
|
|
63
|
+
/** Convert a document (Word, Markdown, HTML, …, or an older .tex) into a template. */
|
|
64
|
+
async function importDocument(project, file, options = {}) {
|
|
65
|
+
const input = (0, path_1.resolve)(file);
|
|
66
|
+
if (!(0, fs_1.existsSync)(input))
|
|
67
|
+
throw new Error(`no such file: ${file}`);
|
|
68
|
+
const name = options.name ?? templateNameFor(input);
|
|
69
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(name))
|
|
70
|
+
throw new Error(`invalid template name "${name}" (use lowercase letters, digits and -)`);
|
|
71
|
+
const dir = (0, path_1.join)(project.templatesDir, name);
|
|
72
|
+
const target = (0, path_1.join)(dir, 'template.tex');
|
|
73
|
+
if ((0, fs_1.existsSync)(target) && !options.force)
|
|
74
|
+
throw new Error(`${project.rel(target)} exists; use --force to replace it`);
|
|
75
|
+
(0, fs_1.mkdirSync)(dir, { recursive: true });
|
|
76
|
+
let tex;
|
|
77
|
+
let media = null;
|
|
78
|
+
if ((0, path_1.extname)(input).toLowerCase() === '.tex') {
|
|
79
|
+
tex = (0, fs_1.readFileSync)(input, 'utf8');
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
// pandoc runs in Docker with the project mounted, so the input must be inside it
|
|
83
|
+
const rel = (0, path_1.relative)(project.root, input);
|
|
84
|
+
let staged = null;
|
|
85
|
+
let source = input;
|
|
86
|
+
if (rel.startsWith('..') || (0, path_1.isAbsolute)(rel)) {
|
|
87
|
+
const stage = (0, path_1.join)(project.outDir, '.import');
|
|
88
|
+
(0, fs_1.mkdirSync)(stage, { recursive: true });
|
|
89
|
+
staged = (0, path_1.join)(stage, (0, path_1.basename)(input));
|
|
90
|
+
(0, fs_1.copyFileSync)(input, staged);
|
|
91
|
+
source = staged;
|
|
92
|
+
}
|
|
93
|
+
const mediaDir = (0, path_1.join)(dir, 'media');
|
|
94
|
+
try {
|
|
95
|
+
await (0, render_1.runPandoc)({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend, image: project.lock?.pandocImage });
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
if (staged)
|
|
99
|
+
(0, fs_1.rmSync)(staged, { force: true });
|
|
100
|
+
}
|
|
101
|
+
tex = (0, fs_1.readFileSync)(target, 'utf8');
|
|
102
|
+
if ((0, fs_1.existsSync)(mediaDir)) {
|
|
103
|
+
media = mediaDir;
|
|
104
|
+
// pandoc writes media paths relative to the project root; TeX looks in the template folder
|
|
105
|
+
tex = tex.split((0, path_1.relative)(project.root, mediaDir) + '/').join('media/');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const { tex: converted, converted: fields, skipped } = (0, template_1.convertPlaceholders)(tex);
|
|
109
|
+
(0, fs_1.writeFileSync)(target, (0, template_1.ensureLatexKitPackage)(converted));
|
|
110
|
+
let schema = null;
|
|
111
|
+
const schemaFile = (0, path_1.join)(dir, 'schema.ts');
|
|
112
|
+
if (options.schema !== false && fields.length > 0 && !(0, fs_1.existsSync)(schemaFile)) {
|
|
113
|
+
const paths = [...new Set(fields.map((f) => f.to.slice('\\field{'.length, -1)))];
|
|
114
|
+
(0, fs_1.writeFileSync)(schemaFile, starterSchema(paths));
|
|
115
|
+
schema = schemaFile;
|
|
116
|
+
}
|
|
117
|
+
return { name, template: target, schema, media, converted: fields, skipped };
|
|
118
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -2,11 +2,18 @@
|
|
|
2
2
|
* latex-kit: typed, reproducible LaTeX documents.
|
|
3
3
|
*
|
|
4
4
|
* The CLI is `latex-kit`. This module is what project files import:
|
|
5
|
-
* `defineConfig` for latex-kit.config.ts
|
|
6
|
-
*
|
|
5
|
+
* `defineConfig` for latex-kit.config.ts; `z`, the shared types and `ref()`
|
|
6
|
+
* for schema.ts; `defineDocument` for TypeScript records; `defineComponent`,
|
|
7
|
+
* `table`, `tex` and friends for components/; `defineClause` for clauses.
|
|
7
8
|
*/
|
|
8
9
|
export * from './build';
|
|
9
10
|
export * from './check';
|
|
10
11
|
export * from './config';
|
|
12
|
+
export * from './diff';
|
|
13
|
+
export * from './import';
|
|
14
|
+
export * from './lock';
|
|
11
15
|
export * from './project';
|
|
16
|
+
export * from './scaffold';
|
|
17
|
+
export type { Cell, ClauseDefinition, Column, Component, ComponentContext, Exhibit, TableOptions } from '@latex-kit/components';
|
|
18
|
+
export { address, bilingual, BUILTIN_COMPONENTS, date, defineClause, defineComponent, escapeLatex, exhibit, exhibits, get, money, number, percent, raw, RawLatex, signatures, table, tex, } from '@latex-kit/components';
|
|
12
19
|
export * from '@latex-kit/schema';
|
package/index.js
CHANGED
|
@@ -14,15 +14,40 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.tex = exports.table = exports.signatures = exports.RawLatex = exports.raw = exports.percent = exports.number = exports.money = exports.get = exports.exhibits = exports.exhibit = exports.escapeLatex = exports.defineComponent = exports.defineClause = exports.date = exports.BUILTIN_COMPONENTS = exports.bilingual = exports.address = void 0;
|
|
17
18
|
/**
|
|
18
19
|
* latex-kit: typed, reproducible LaTeX documents.
|
|
19
20
|
*
|
|
20
21
|
* The CLI is `latex-kit`. This module is what project files import:
|
|
21
|
-
* `defineConfig` for latex-kit.config.ts
|
|
22
|
-
*
|
|
22
|
+
* `defineConfig` for latex-kit.config.ts; `z`, the shared types and `ref()`
|
|
23
|
+
* for schema.ts; `defineDocument` for TypeScript records; `defineComponent`,
|
|
24
|
+
* `table`, `tex` and friends for components/; `defineClause` for clauses.
|
|
23
25
|
*/
|
|
24
26
|
__exportStar(require("./build"), exports);
|
|
25
27
|
__exportStar(require("./check"), exports);
|
|
26
28
|
__exportStar(require("./config"), exports);
|
|
29
|
+
__exportStar(require("./diff"), exports);
|
|
30
|
+
__exportStar(require("./import"), exports);
|
|
31
|
+
__exportStar(require("./lock"), exports);
|
|
27
32
|
__exportStar(require("./project"), exports);
|
|
33
|
+
__exportStar(require("./scaffold"), exports);
|
|
34
|
+
var components_1 = require("@latex-kit/components");
|
|
35
|
+
Object.defineProperty(exports, "address", { enumerable: true, get: function () { return components_1.address; } });
|
|
36
|
+
Object.defineProperty(exports, "bilingual", { enumerable: true, get: function () { return components_1.bilingual; } });
|
|
37
|
+
Object.defineProperty(exports, "BUILTIN_COMPONENTS", { enumerable: true, get: function () { return components_1.BUILTIN_COMPONENTS; } });
|
|
38
|
+
Object.defineProperty(exports, "date", { enumerable: true, get: function () { return components_1.date; } });
|
|
39
|
+
Object.defineProperty(exports, "defineClause", { enumerable: true, get: function () { return components_1.defineClause; } });
|
|
40
|
+
Object.defineProperty(exports, "defineComponent", { enumerable: true, get: function () { return components_1.defineComponent; } });
|
|
41
|
+
Object.defineProperty(exports, "escapeLatex", { enumerable: true, get: function () { return components_1.escapeLatex; } });
|
|
42
|
+
Object.defineProperty(exports, "exhibit", { enumerable: true, get: function () { return components_1.exhibit; } });
|
|
43
|
+
Object.defineProperty(exports, "exhibits", { enumerable: true, get: function () { return components_1.exhibits; } });
|
|
44
|
+
Object.defineProperty(exports, "get", { enumerable: true, get: function () { return components_1.get; } });
|
|
45
|
+
Object.defineProperty(exports, "money", { enumerable: true, get: function () { return components_1.money; } });
|
|
46
|
+
Object.defineProperty(exports, "number", { enumerable: true, get: function () { return components_1.number; } });
|
|
47
|
+
Object.defineProperty(exports, "percent", { enumerable: true, get: function () { return components_1.percent; } });
|
|
48
|
+
Object.defineProperty(exports, "raw", { enumerable: true, get: function () { return components_1.raw; } });
|
|
49
|
+
Object.defineProperty(exports, "RawLatex", { enumerable: true, get: function () { return components_1.RawLatex; } });
|
|
50
|
+
Object.defineProperty(exports, "signatures", { enumerable: true, get: function () { return components_1.signatures; } });
|
|
51
|
+
Object.defineProperty(exports, "table", { enumerable: true, get: function () { return components_1.table; } });
|
|
52
|
+
Object.defineProperty(exports, "tex", { enumerable: true, get: function () { return components_1.tex; } });
|
|
28
53
|
__exportStar(require("@latex-kit/schema"), exports);
|
package/lock.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* latex-kit.lock: the exact images a project builds with. Commit it. A newer
|
|
3
|
+
* latex-kit with a newer default image keeps building this project with the
|
|
4
|
+
* locked one, so PDFs do not change until `latex-kit lock` moves the pins.
|
|
5
|
+
*/
|
|
6
|
+
export declare const LOCK_FILE = "latex-kit.lock";
|
|
7
|
+
export interface Lock {
|
|
8
|
+
lockfileVersion: 1;
|
|
9
|
+
/** The TeX Live image, by digest. */
|
|
10
|
+
image: string;
|
|
11
|
+
/** The pandoc image `latex-kit import` uses, by digest. */
|
|
12
|
+
pandocImage: string;
|
|
13
|
+
}
|
|
14
|
+
export declare class LockError extends Error {
|
|
15
|
+
name: string;
|
|
16
|
+
}
|
|
17
|
+
/** The pins this version of latex-kit would write. */
|
|
18
|
+
export declare function currentPins(): Lock;
|
|
19
|
+
export declare function readLock(root: string): Lock | null;
|
|
20
|
+
/** Write the current pins. Returns the previous lock, if any. */
|
|
21
|
+
export declare function writeLock(root: string): {
|
|
22
|
+
lock: Lock;
|
|
23
|
+
previous: Lock | null;
|
|
24
|
+
};
|