latex-kit 0.4.1 → 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/esm/lock.js ADDED
@@ -0,0 +1,50 @@
1
+ import { DEFAULT_IMAGE, PANDOC_IMAGE } from '@latex-kit/render';
2
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
3
+ import { join } from 'path';
4
+ /**
5
+ * latex-kit.lock: the exact images a project builds with. Commit it. A newer
6
+ * latex-kit with a newer default image keeps building this project with the
7
+ * locked one, so PDFs do not change until `latex-kit lock` moves the pins.
8
+ */
9
+ export const LOCK_FILE = 'latex-kit.lock';
10
+ export class LockError extends Error {
11
+ name = 'LockError';
12
+ }
13
+ const PINNED = /@sha256:[0-9a-f]{64}$/;
14
+ /** The pins this version of latex-kit would write. */
15
+ export function currentPins() {
16
+ return { lockfileVersion: 1, image: DEFAULT_IMAGE, pandocImage: PANDOC_IMAGE };
17
+ }
18
+ export function readLock(root) {
19
+ const file = join(root, LOCK_FILE);
20
+ if (!existsSync(file))
21
+ return null;
22
+ let raw;
23
+ try {
24
+ raw = JSON.parse(readFileSync(file, 'utf8'));
25
+ }
26
+ catch (e) {
27
+ throw new LockError(`${LOCK_FILE} is not valid JSON: ${e.message}`);
28
+ }
29
+ const l = raw;
30
+ if (!l || typeof l !== 'object' || l.lockfileVersion !== 1)
31
+ throw new LockError(`${LOCK_FILE}: unknown lockfileVersion (this latex-kit reads version 1)`);
32
+ for (const k of ['image', 'pandocImage']) {
33
+ if (typeof l[k] !== 'string' || !PINNED.test(l[k]))
34
+ throw new LockError(`${LOCK_FILE}: ${k} must be an image pinned by digest (…@sha256:<64 hex>)`);
35
+ }
36
+ return l;
37
+ }
38
+ /** Write the current pins. Returns the previous lock, if any. */
39
+ export function writeLock(root) {
40
+ let previous = null;
41
+ try {
42
+ previous = readLock(root);
43
+ }
44
+ catch {
45
+ // an unreadable lock is replaced
46
+ }
47
+ const lock = currentPins();
48
+ writeFileSync(join(root, LOCK_FILE), JSON.stringify(lock, null, 2) + '\n');
49
+ return { lock, previous };
50
+ }
@@ -1,4 +1,6 @@
1
1
  import type { ParsedArgs } from 'minimist';
2
+ /** `--only nda-*,invoice-0001`: comma-separated names, * matches anything. */
3
+ export declare function onlyMatcher(only: unknown): ((name: string) => boolean) | null;
2
4
  export declare function buildCommand(argv: Partial<ParsedArgs>): Promise<number>;
3
5
  export declare function checkCommand(argv: Partial<ParsedArgs>): Promise<number>;
4
6
  export declare function fieldsCommand(argv: Partial<ParsedArgs>): Promise<number>;
@@ -6,6 +8,8 @@ export declare function typegenCommand(argv: Partial<ParsedArgs>): Promise<numbe
6
8
  export declare function styCommand(argv: Partial<ParsedArgs>): Promise<number>;
7
9
  export declare function importCommand(argv: Partial<ParsedArgs>): Promise<number>;
8
10
  export declare function diffCommand(argv: Partial<ParsedArgs>): Promise<number>;
11
+ /** Pin the TeX and pandoc images in latex-kit.lock (commit it). */
12
+ export declare function lockCommand(argv: Partial<ParsedArgs>): Promise<number>;
9
13
  export declare function initCommand(argv: Partial<ParsedArgs>): Promise<number>;
10
14
  export declare function newCommand(argv: Partial<ParsedArgs>): Promise<number>;
11
15
  export declare function cleanCommand(argv: Partial<ParsedArgs>): Promise<number>;
@@ -10,6 +10,7 @@ import { checkProject, templateFields } from './check';
10
10
  import { version } from './commands';
11
11
  import { diffDocument, diffFiles } from './diff';
12
12
  import { importDocument } from './import';
13
+ import { currentPins, LOCK_FILE, writeLock } from './lock';
13
14
  import { Project } from './project';
14
15
  import { initProject, newDocument, newTemplate } from './scaffold';
15
16
  function printDiagnostics(ds, json) {
@@ -19,12 +20,35 @@ function printDiagnostics(ds, json) {
19
20
  console.error((d.severity === 'error' ? chalk.red : chalk.yellow)(formatDiagnostic(d)));
20
21
  }
21
22
  const rel = (p) => (p ? relative(process.cwd(), p) : null);
23
+ /** `--only nda-*,invoice-0001`: comma-separated names, * matches anything. */
24
+ export function onlyMatcher(only) {
25
+ if (only === undefined || only === null || only === '' || only === true)
26
+ return null;
27
+ const patterns = (Array.isArray(only) ? only : [only]).flatMap((o) => String(o).split(',')).map((p) => p.trim()).filter(Boolean);
28
+ if (patterns.length === 0)
29
+ return null;
30
+ const res = patterns.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`));
31
+ return (name) => res.some((r) => r.test(name));
32
+ }
33
+ function checkLocale(locale) {
34
+ if (locale === undefined)
35
+ return undefined;
36
+ try {
37
+ return Intl.getCanonicalLocales(String(locale))[0];
38
+ }
39
+ catch {
40
+ throw new UsageError(`--locale ${locale} is not a language tag (like en-US or ja-JP)`);
41
+ }
42
+ }
22
43
  export async function buildCommand(argv) {
23
44
  const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
24
45
  if (!VARIANTS.includes(variant))
25
46
  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(', ')}`);
47
+ if (argv.engine && argv.engine !== 'auto' && !ENGINES.includes(argv.engine))
48
+ throw new UsageError(`--engine must be auto or one of ${ENGINES.join(', ')}`);
49
+ if (argv.signatures !== undefined && variant !== 'signed')
50
+ throw new UsageError('--signatures only applies to --variant signed');
51
+ const only = onlyMatcher(argv.only);
28
52
  const project = await Project.open(argv.root);
29
53
  const options = {
30
54
  variant,
@@ -35,13 +59,16 @@ export async function buildCommand(argv) {
35
59
  platform: argv.platform,
36
60
  verify: Boolean(argv.verify),
37
61
  texOnly: Boolean(argv['tex-only']),
62
+ locale: checkLocale(argv.locale),
63
+ force: Boolean(argv.force),
64
+ signatures: argv.signatures,
38
65
  };
39
66
  const json = Boolean(argv.json);
40
67
  const log = (s) => !json && console.error(s);
41
68
  const targets = [];
42
69
  const files = (argv._ ?? []).map(String);
43
70
  if (variant === 'blank' && files.length === 0) {
44
- const names = argv.template ? [String(argv.template)] : project.templateNames();
71
+ const names = (argv.template ? [String(argv.template)] : project.templateNames()).filter((n) => !only || only(n));
45
72
  for (const n of names)
46
73
  targets.push({ label: `template ${n}`, run: () => buildBlank(project, n, options) });
47
74
  }
@@ -58,13 +85,21 @@ export async function buildCommand(argv) {
58
85
  keep.push(f);
59
86
  docs = keep;
60
87
  }
88
+ if (only)
89
+ docs = docs.filter((f) => only(project.documentName(f)));
61
90
  for (const f of docs)
62
91
  targets.push({ label: rel(f), run: () => buildDocument(project, f, options) });
63
92
  }
64
93
  if (targets.length === 0) {
94
+ if (only) {
95
+ log(chalk.red(`--only ${argv.only} matched nothing`));
96
+ return 1;
97
+ }
65
98
  log(chalk.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
66
99
  return 0;
67
100
  }
101
+ for (const d of project.codeDiagnostics)
102
+ printDiagnostics([d], json);
68
103
  const results = [];
69
104
  let failed = 0;
70
105
  for (const t of targets) {
@@ -77,7 +112,8 @@ export async function buildCommand(argv) {
77
112
  failed++;
78
113
  results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
79
114
  if (!json) {
80
- console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${r.docId ? chalk.dim(` ${r.docId}`) : ''}`);
115
+ const notes = [r.docId, r.cached ? 'unchanged' : null, r.engine && r.engineReason !== 'chosen' && r.engine !== 'lualatex' ? `${r.engine}, ${r.engineReason?.replace(/^auto: /, '')}` : null].filter(Boolean).join(' ');
116
+ console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${notes ? chalk.dim(` ${notes}`) : ''}`);
81
117
  if (r.minted)
82
118
  console.log(chalk.dim(` minted ${r.docId} and saved it in ${t.label}`));
83
119
  if (r.verified !== undefined)
@@ -134,7 +170,7 @@ export async function fieldsCommand(argv) {
134
170
  const width = Math.max(...fields.map((f) => f.absolute.length), 4);
135
171
  for (const f of fields) {
136
172
  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}`);
173
+ console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(9))} ${chalk.dim(`${f.file}:${f.line}`)}${filters}`);
138
174
  }
139
175
  return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
140
176
  }
@@ -221,9 +257,37 @@ export async function diffCommand(argv) {
221
257
  console.log(`${chalk.green('✓')} ${rel(result.pdf)} ${chalk.dim('(insertions underlined in blue, deletions struck through in red)')}`);
222
258
  return 0;
223
259
  }
260
+ /** Pin the TeX and pandoc images in latex-kit.lock (commit it). */
261
+ export async function lockCommand(argv) {
262
+ const project = await Project.open(argv.root);
263
+ const pins = currentPins();
264
+ const file = join(project.root, LOCK_FILE);
265
+ if (argv.check) {
266
+ if (!project.lock) {
267
+ console.log(chalk.yellow(`no ${LOCK_FILE}: builds use this latex-kit's default image`));
268
+ return 1;
269
+ }
270
+ const stale = project.lock.image !== pins.image || project.lock.pandocImage !== pins.pandocImage;
271
+ console.log(stale ? chalk.yellow(`${rel(file)} pins older images than this latex-kit's defaults; run latex-kit lock to move them (PDF bytes will change)`) : `${chalk.green('✓')} ${rel(file)} matches this latex-kit`);
272
+ return stale ? 1 : 0;
273
+ }
274
+ const { lock, previous } = writeLock(project.root);
275
+ console.log(`${chalk.green('✓')} ${rel(file)}`);
276
+ if (previous && previous.image !== lock.image)
277
+ console.log(chalk.dim(` image ${previous.image}\n → ${lock.image}\n rebuilt PDFs will differ from earlier ones`));
278
+ else if (!previous)
279
+ console.log(chalk.dim(` image ${lock.image}`));
280
+ else
281
+ console.log(chalk.dim(' already up to date'));
282
+ return 0;
283
+ }
224
284
  export async function initCommand(argv) {
225
285
  const dir = join(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
226
286
  const r = initProject(dir, { paper: Boolean(argv.paper), force: Boolean(argv.force), version: version() });
287
+ if (!argv.paper && !existsSync(join(dir, LOCK_FILE))) {
288
+ writeLock(dir);
289
+ r.written.push(join(dir, LOCK_FILE));
290
+ }
227
291
  for (const f of r.written)
228
292
  console.log(`${chalk.green('+')} ${rel(f)}`);
229
293
  for (const f of r.skipped)
package/esm/project.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { JsonSchema, TemplateMeta, z } from '@latex-kit/schema';
2
- import { CompiledTemplate, LoadedClause } from '@latex-kit/template';
2
+ import { CompiledTemplate, Component, Diagnostic, LoadedClause } from '@latex-kit/template';
3
3
  import { ResolvedConfig } from './config';
4
+ import { Lock } from './lock';
4
5
  export interface Template {
5
6
  name: string;
6
7
  dir: string;
@@ -15,11 +16,26 @@ export interface Template {
15
16
  export declare class Project {
16
17
  readonly root: string;
17
18
  readonly config: ResolvedConfig;
19
+ /** latex-kit.lock, when the project has one. */
20
+ readonly lock: Lock | null;
18
21
  private templates;
19
22
  private snippets;
20
23
  private clauses;
24
+ /** Clauses written in TypeScript, loaded when the project opens. */
25
+ private codeClauses;
26
+ /** Built-in components, then the project's own (which win). */
27
+ readonly components: Record<string, Component>;
28
+ /** Source files of the project's components, by name. */
29
+ readonly componentFiles: Record<string, string>;
30
+ /** Problems loading components/ and TypeScript clauses. */
31
+ readonly codeDiagnostics: Diagnostic[];
21
32
  private constructor();
22
33
  static open(root?: string): Promise<Project>;
34
+ /** The Docker image to build with: --image, then config, then latex-kit.lock. */
35
+ image(override?: string): string | undefined;
36
+ private loadCode;
37
+ /** Names \\component can use. */
38
+ componentNames(): string[];
23
39
  path(...parts: string[]): string;
24
40
  rel(file: string): string;
25
41
  get templatesDir(): string;
@@ -39,7 +55,7 @@ export declare class Project {
39
55
  * `.tex` is added when the name has no extension. Never outside the project.
40
56
  */
41
57
  loadSnippet: (name: string, from: string) => CompiledTemplate | null;
42
- /** \\clause{id}: `clauses/<id>.tex` from the clause library. */
58
+ /** \\clause{id}: `clauses/<id>.tex` (or `.ts`) from the clause library. */
43
59
  loadClause: (id: string) => LoadedClause | null;
44
60
  /** Absolute paths of every snippet loaded so far. */
45
61
  snippetFiles(): string[];
package/esm/project.js CHANGED
@@ -1,23 +1,107 @@
1
- import { DATA_EXTENSIONS, loadTemplateSchema, toJsonSchema } from '@latex-kit/schema';
2
- import { compileTemplate, isRelativeName, parseClauseHeader } from '@latex-kit/template';
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();
14
- constructor(root, config) {
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) {
15
48
  this.root = root;
16
49
  this.config = config;
50
+ this.lock = lock;
17
51
  }
18
52
  static async open(root = process.cwd()) {
19
53
  const abs = resolve(root);
20
- return new Project(abs, await loadConfig(abs));
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();
21
105
  }
22
106
  path(...parts) {
23
107
  return join(this.root, ...parts);
@@ -119,7 +203,7 @@ export class Project {
119
203
  }
120
204
  return null;
121
205
  };
122
- /** \\clause{id}: `clauses/<id>.tex` from the clause library. */
206
+ /** \\clause{id}: `clauses/<id>.tex` (or `.ts`) from the clause library. */
123
207
  loadClause = (id) => {
124
208
  if (this.clauses.has(id))
125
209
  return this.clauses.get(id);
@@ -129,6 +213,9 @@ export class Project {
129
213
  const text = readFileSync(file, 'utf8');
130
214
  loaded = { id, template: compileTemplate(text, this.rel(file)), ...parseClauseHeader(text) };
131
215
  }
216
+ else if (this.codeClauses.has(id)) {
217
+ loaded = this.codeClauses.get(id);
218
+ }
132
219
  this.clauses.set(id, loaded);
133
220
  return loaded;
134
221
  };
package/esm/render.js CHANGED
@@ -7,6 +7,7 @@ function summary(r) {
7
7
  pdf: relative(process.cwd(), r.pdf),
8
8
  sha256: r.sha256,
9
9
  engine: r.engine,
10
+ engineReason: r.engineReason,
10
11
  backend: r.backend,
11
12
  image: r.image,
12
13
  sourceDateEpoch: r.sourceDateEpoch,
@@ -38,8 +39,9 @@ export async function renderCommand(argv, prompter) {
38
39
  console.error(s);
39
40
  };
40
41
  try {
41
- log(chalk.dim(`rendering ${opts.file} with ${opts.engine} (${opts.backend})…`));
42
+ log(chalk.dim(`rendering ${opts.file} (${opts.backend})…`));
42
43
  const first = await render({ ...opts, file: opts.file });
44
+ log(chalk.dim(` engine ${first.engine}${first.engineReason === 'chosen' ? '' : ` (${first.engineReason})`}`));
43
45
  for (const d of first.diagnostics)
44
46
  log(chalk.yellow(formatDiagnostic(d)));
45
47
  if (!first.reproducible) {
@@ -49,7 +51,7 @@ export async function renderCommand(argv, prompter) {
49
51
  if (argv.verify) {
50
52
  // same output path: some tools (Ghostscript) hash the path into the PDF ID
51
53
  log(chalk.dim('rendering again to check the output is byte-identical…'));
52
- const second = await render({ ...opts, file: opts.file, sourceDateEpoch: first.sourceDateEpoch });
54
+ const second = await render({ ...opts, file: opts.file, engine: first.engine, sourceDateEpoch: first.sourceDateEpoch });
53
55
  verified = second.sha256 === first.sha256;
54
56
  }
55
57
  if (argv.json) {
package/esm/usage.js CHANGED
@@ -18,6 +18,7 @@ Project commands (run in a folder with templates/, data/, documents/)
18
18
  fields <template> List every field a template reads
19
19
  typegen Write JSON Schema and .d.ts for each template's data
20
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
21
22
  import <file> Turn a Word/Markdown/HTML document (or an older .tex)
22
23
  into a template; {{x}} and @GROUP@FIELD@ become \\field
23
24
  diff <document> --against <ref>
@@ -41,7 +42,7 @@ always produces the same PDF bytes.
41
42
 
42
43
  Options
43
44
  -o, --out <dir> Output directory, relative to --root (default: out)
44
- -e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
45
+ -e, --engine <name> auto (default), lualatex, xelatex, pdflatex or pdfps
45
46
  --root <dir> Directory TeX can see (default: current directory)
46
47
  --image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
47
48
  --platform <os/arch> Docker --platform (default: native)
@@ -50,7 +51,10 @@ Options
50
51
  --verify Build twice and fail if the PDFs differ
51
52
  --json Print a JSON summary on stdout
52
53
 
53
- Only lualatex is byte-reproducible in the default image.
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.
54
58
  `;
55
59
  const BUILD = `latex-kit build [documents…] [options]
56
60
 
@@ -62,20 +66,34 @@ Variants
62
66
  as red markers (they fail instead when CI=true or --strict)
63
67
  --variant final No marks. Missing values fail. Mints a document ID on the
64
68
  --final first build and saves it in the record (JSON/YAML)
65
- --variant signed Like final; templates can test \\when{$variant == "signed"}
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 } }
66
74
  --variant blank Every field is a labelled line. With no documents, builds
67
75
  each template (or --template <name>) as an empty form
68
76
 
69
77
  Options
70
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
71
84
  --strict Fail on missing values in drafts too
72
- -e, --engine <name> lualatex (default), xelatex, pdflatex or pdfps
85
+ --force Rebuild even if the PDF is up to date
86
+ -e, --engine <name> auto (default), lualatex, xelatex, pdflatex or pdfps
73
87
  --local Use latexmk on PATH instead of Docker
74
- --image <ref> Docker image (default: pinned ghcr.io/constructive-io/latex-kit)
88
+ --image <ref> Docker image (default: latex-kit.lock, else the pinned
89
+ ghcr.io/constructive-io/latex-kit)
75
90
  --verify Build twice and fail unless the PDFs are identical
76
91
  --tex-only Write the .tex without running TeX
77
92
  --json JSON results on stdout
78
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.
79
97
  `;
80
98
  const DOCTOR = `latex-kit doctor [--image <ref>] [--json]
81
99
 
package/import.js CHANGED
@@ -92,7 +92,7 @@ async function importDocument(project, file, options = {}) {
92
92
  }
93
93
  const mediaDir = (0, path_1.join)(dir, 'media');
94
94
  try {
95
- await (0, render_1.runPandoc)({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend });
95
+ await (0, render_1.runPandoc)({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend, image: project.lock?.pandocImage });
96
96
  }
97
97
  finally {
98
98
  if (staged)
package/index.d.ts CHANGED
@@ -2,14 +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, and `z` plus the shared types and
6
- * `ref()` for templates' schema.ts and TypeScript records.
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';
11
12
  export * from './diff';
12
13
  export * from './import';
14
+ export * from './lock';
13
15
  export * from './project';
14
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';
15
19
  export * from '@latex-kit/schema';
package/index.js CHANGED
@@ -14,18 +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, and `z` plus the shared types and
22
- * `ref()` for templates' schema.ts and TypeScript records.
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);
27
29
  __exportStar(require("./diff"), exports);
28
30
  __exportStar(require("./import"), exports);
31
+ __exportStar(require("./lock"), exports);
29
32
  __exportStar(require("./project"), exports);
30
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; } });
31
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
+ };
package/lock.js ADDED
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LockError = exports.LOCK_FILE = void 0;
4
+ exports.currentPins = currentPins;
5
+ exports.readLock = readLock;
6
+ exports.writeLock = writeLock;
7
+ const render_1 = require("@latex-kit/render");
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ /**
11
+ * latex-kit.lock: the exact images a project builds with. Commit it. A newer
12
+ * latex-kit with a newer default image keeps building this project with the
13
+ * locked one, so PDFs do not change until `latex-kit lock` moves the pins.
14
+ */
15
+ exports.LOCK_FILE = 'latex-kit.lock';
16
+ class LockError extends Error {
17
+ name = 'LockError';
18
+ }
19
+ exports.LockError = LockError;
20
+ const PINNED = /@sha256:[0-9a-f]{64}$/;
21
+ /** The pins this version of latex-kit would write. */
22
+ function currentPins() {
23
+ return { lockfileVersion: 1, image: render_1.DEFAULT_IMAGE, pandocImage: render_1.PANDOC_IMAGE };
24
+ }
25
+ function readLock(root) {
26
+ const file = (0, path_1.join)(root, exports.LOCK_FILE);
27
+ if (!(0, fs_1.existsSync)(file))
28
+ return null;
29
+ let raw;
30
+ try {
31
+ raw = JSON.parse((0, fs_1.readFileSync)(file, 'utf8'));
32
+ }
33
+ catch (e) {
34
+ throw new LockError(`${exports.LOCK_FILE} is not valid JSON: ${e.message}`);
35
+ }
36
+ const l = raw;
37
+ if (!l || typeof l !== 'object' || l.lockfileVersion !== 1)
38
+ throw new LockError(`${exports.LOCK_FILE}: unknown lockfileVersion (this latex-kit reads version 1)`);
39
+ for (const k of ['image', 'pandocImage']) {
40
+ if (typeof l[k] !== 'string' || !PINNED.test(l[k]))
41
+ throw new LockError(`${exports.LOCK_FILE}: ${k} must be an image pinned by digest (…@sha256:<64 hex>)`);
42
+ }
43
+ return l;
44
+ }
45
+ /** Write the current pins. Returns the previous lock, if any. */
46
+ function writeLock(root) {
47
+ let previous = null;
48
+ try {
49
+ previous = readLock(root);
50
+ }
51
+ catch {
52
+ // an unreadable lock is replaced
53
+ }
54
+ const lock = currentPins();
55
+ (0, fs_1.writeFileSync)((0, path_1.join)(root, exports.LOCK_FILE), JSON.stringify(lock, null, 2) + '\n');
56
+ return { lock, previous };
57
+ }