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/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/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, image: project.lock?.pandocImage });
|
|
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
|
@@ -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/esm/index.js
CHANGED
|
@@ -2,11 +2,17 @@
|
|
|
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 { address, bilingual, BUILTIN_COMPONENTS, date, defineClause, defineComponent, escapeLatex, exhibit, exhibits, get, money, number, percent, raw, RawLatex, signatures, table, tex, } from '@latex-kit/components';
|
|
12
18
|
export * from '@latex-kit/schema';
|
package/esm/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/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,6 +1,20 @@
|
|
|
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>;
|
|
5
7
|
export declare function typegenCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
6
8
|
export declare function styCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
9
|
+
export declare function importCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
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>;
|
|
13
|
+
export declare function initCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
14
|
+
export declare function newCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
15
|
+
export declare function cleanCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
|
16
|
+
/**
|
|
17
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
18
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
19
|
+
*/
|
|
20
|
+
export declare function watchCommand(argv: Partial<ParsedArgs>): Promise<number>;
|
package/esm/project-commands.js
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import { ENGINES } from '@latex-kit/render';
|
|
2
2
|
import { documentJsonSchema, generateTypes, loadDocument } from '@latex-kit/schema';
|
|
3
3
|
import { formatDiagnostic, LATEX_KIT_STY, VARIANTS } from '@latex-kit/template';
|
|
4
|
-
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
|
5
|
-
import { join, relative } from 'path';
|
|
4
|
+
import { existsSync, mkdirSync, rmSync, watch as fsWatch, writeFileSync } from 'fs';
|
|
5
|
+
import { isAbsolute, join, relative } from 'path';
|
|
6
6
|
import chalk from 'yanse';
|
|
7
7
|
import { UsageError } from './args';
|
|
8
8
|
import { buildBlank, buildDocument, BuildError } from './build';
|
|
9
9
|
import { checkProject, templateFields } from './check';
|
|
10
|
+
import { version } from './commands';
|
|
11
|
+
import { diffDocument, diffFiles } from './diff';
|
|
12
|
+
import { importDocument } from './import';
|
|
13
|
+
import { currentPins, LOCK_FILE, writeLock } from './lock';
|
|
10
14
|
import { Project } from './project';
|
|
15
|
+
import { initProject, newDocument, newTemplate } from './scaffold';
|
|
11
16
|
function printDiagnostics(ds, json) {
|
|
12
17
|
if (json)
|
|
13
18
|
return;
|
|
@@ -15,12 +20,35 @@ function printDiagnostics(ds, json) {
|
|
|
15
20
|
console.error((d.severity === 'error' ? chalk.red : chalk.yellow)(formatDiagnostic(d)));
|
|
16
21
|
}
|
|
17
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
|
+
}
|
|
18
43
|
export async function buildCommand(argv) {
|
|
19
44
|
const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
|
|
20
45
|
if (!VARIANTS.includes(variant))
|
|
21
46
|
throw new UsageError(`--variant must be one of ${VARIANTS.join(', ')}`);
|
|
22
|
-
if (argv.engine && !ENGINES.includes(argv.engine))
|
|
23
|
-
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);
|
|
24
52
|
const project = await Project.open(argv.root);
|
|
25
53
|
const options = {
|
|
26
54
|
variant,
|
|
@@ -31,13 +59,16 @@ export async function buildCommand(argv) {
|
|
|
31
59
|
platform: argv.platform,
|
|
32
60
|
verify: Boolean(argv.verify),
|
|
33
61
|
texOnly: Boolean(argv['tex-only']),
|
|
62
|
+
locale: checkLocale(argv.locale),
|
|
63
|
+
force: Boolean(argv.force),
|
|
64
|
+
signatures: argv.signatures,
|
|
34
65
|
};
|
|
35
66
|
const json = Boolean(argv.json);
|
|
36
67
|
const log = (s) => !json && console.error(s);
|
|
37
68
|
const targets = [];
|
|
38
69
|
const files = (argv._ ?? []).map(String);
|
|
39
70
|
if (variant === 'blank' && files.length === 0) {
|
|
40
|
-
const names = argv.template ? [String(argv.template)] : project.templateNames();
|
|
71
|
+
const names = (argv.template ? [String(argv.template)] : project.templateNames()).filter((n) => !only || only(n));
|
|
41
72
|
for (const n of names)
|
|
42
73
|
targets.push({ label: `template ${n}`, run: () => buildBlank(project, n, options) });
|
|
43
74
|
}
|
|
@@ -54,13 +85,21 @@ export async function buildCommand(argv) {
|
|
|
54
85
|
keep.push(f);
|
|
55
86
|
docs = keep;
|
|
56
87
|
}
|
|
88
|
+
if (only)
|
|
89
|
+
docs = docs.filter((f) => only(project.documentName(f)));
|
|
57
90
|
for (const f of docs)
|
|
58
91
|
targets.push({ label: rel(f), run: () => buildDocument(project, f, options) });
|
|
59
92
|
}
|
|
60
93
|
if (targets.length === 0) {
|
|
94
|
+
if (only) {
|
|
95
|
+
log(chalk.red(`--only ${argv.only} matched nothing`));
|
|
96
|
+
return 1;
|
|
97
|
+
}
|
|
61
98
|
log(chalk.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
|
|
62
99
|
return 0;
|
|
63
100
|
}
|
|
101
|
+
for (const d of project.codeDiagnostics)
|
|
102
|
+
printDiagnostics([d], json);
|
|
64
103
|
const results = [];
|
|
65
104
|
let failed = 0;
|
|
66
105
|
for (const t of targets) {
|
|
@@ -73,7 +112,8 @@ export async function buildCommand(argv) {
|
|
|
73
112
|
failed++;
|
|
74
113
|
results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
|
|
75
114
|
if (!json) {
|
|
76
|
-
|
|
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}`) : ''}`);
|
|
77
117
|
if (r.minted)
|
|
78
118
|
console.log(chalk.dim(` minted ${r.docId} and saved it in ${t.label}`));
|
|
79
119
|
if (r.verified !== undefined)
|
|
@@ -130,7 +170,7 @@ export async function fieldsCommand(argv) {
|
|
|
130
170
|
const width = Math.max(...fields.map((f) => f.absolute.length), 4);
|
|
131
171
|
for (const f of fields) {
|
|
132
172
|
const filters = f.filters.length ? chalk.cyan(` | ${f.filters.join(' | ')}`) : '';
|
|
133
|
-
console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(
|
|
173
|
+
console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(9))} ${chalk.dim(`${f.file}:${f.line}`)}${filters}`);
|
|
134
174
|
}
|
|
135
175
|
return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
|
|
136
176
|
}
|
|
@@ -161,3 +201,188 @@ export async function styCommand(argv) {
|
|
|
161
201
|
console.log(`${chalk.green('✓')} ${rel(file)} (lets editors compile templates as blank previews)`);
|
|
162
202
|
return 0;
|
|
163
203
|
}
|
|
204
|
+
export async function importCommand(argv) {
|
|
205
|
+
const file = argv._?.[0];
|
|
206
|
+
if (!file)
|
|
207
|
+
throw new UsageError('usage: latex-kit import <file.docx|.md|.html|.tex> [--name <template>] [--force]');
|
|
208
|
+
const project = await Project.open(argv.root);
|
|
209
|
+
const r = await importDocument(project, String(file), {
|
|
210
|
+
name: argv.name,
|
|
211
|
+
force: Boolean(argv.force),
|
|
212
|
+
backend: argv.local ? 'local' : undefined,
|
|
213
|
+
schema: argv.schema !== false,
|
|
214
|
+
});
|
|
215
|
+
console.log(`${chalk.green('✓')} ${rel(r.template)}`);
|
|
216
|
+
if (r.media)
|
|
217
|
+
console.log(chalk.dim(` images in ${rel(r.media)}`));
|
|
218
|
+
console.log(chalk.dim(` ${r.converted.length} placeholder${r.converted.length === 1 ? '' : 's'} became \\field{…}`));
|
|
219
|
+
for (const s of r.skipped)
|
|
220
|
+
console.log(chalk.yellow(` line ${s.line}: left ${s.from} as is (not a valid field path)`));
|
|
221
|
+
if (r.schema)
|
|
222
|
+
console.log(chalk.dim(` starter schema: ${rel(r.schema)} (every field is a string; tighten it)`));
|
|
223
|
+
console.log(chalk.dim(` next: latex-kit fields ${r.name}, then latex-kit build --variant blank --template ${r.name}`));
|
|
224
|
+
return 0;
|
|
225
|
+
}
|
|
226
|
+
export async function diffCommand(argv) {
|
|
227
|
+
const args = (argv._ ?? []).map(String);
|
|
228
|
+
const variant = (argv.variant ?? 'final');
|
|
229
|
+
if (!VARIANTS.includes(variant))
|
|
230
|
+
throw new UsageError(`--variant must be one of ${VARIANTS.join(', ')}`);
|
|
231
|
+
const project = await Project.open(argv.root);
|
|
232
|
+
const options = { variant, engine: argv.engine, backend: argv.local ? 'local' : undefined, image: argv.image, platform: argv.platform };
|
|
233
|
+
const abs = (p) => join(process.cwd(), p);
|
|
234
|
+
let result;
|
|
235
|
+
try {
|
|
236
|
+
if (args.length === 2 && !argv.against) {
|
|
237
|
+
result = await diffFiles(project, abs(args[0]), abs(args[1]), options);
|
|
238
|
+
}
|
|
239
|
+
else if (args.length === 1 && argv.against) {
|
|
240
|
+
result = await diffDocument(project, abs(args[0]), String(argv.against), options);
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
throw new UsageError('usage: latex-kit diff <old.tex> <new.tex>\n latex-kit diff <document> --against <git-ref>');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch (e) {
|
|
247
|
+
if (e instanceof BuildError) {
|
|
248
|
+
printDiagnostics(e.diagnostics, Boolean(argv.json));
|
|
249
|
+
console.error(chalk.red(`✗ ${e.message}`));
|
|
250
|
+
return 1;
|
|
251
|
+
}
|
|
252
|
+
throw e;
|
|
253
|
+
}
|
|
254
|
+
if (argv.json)
|
|
255
|
+
console.log(JSON.stringify({ pdf: rel(result.pdf), tex: rel(result.tex), old: rel(result.old), new: rel(result.new) }, null, 2));
|
|
256
|
+
else
|
|
257
|
+
console.log(`${chalk.green('✓')} ${rel(result.pdf)} ${chalk.dim('(insertions underlined in blue, deletions struck through in red)')}`);
|
|
258
|
+
return 0;
|
|
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
|
+
}
|
|
284
|
+
export async function initCommand(argv) {
|
|
285
|
+
const dir = join(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
|
|
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
|
+
}
|
|
291
|
+
for (const f of r.written)
|
|
292
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
293
|
+
for (const f of r.skipped)
|
|
294
|
+
console.log(chalk.dim(` kept ${rel(f)} (exists)`));
|
|
295
|
+
const cd = rel(dir) === '.' ? '' : `cd ${rel(dir)} && `;
|
|
296
|
+
console.log(argv.paper
|
|
297
|
+
? chalk.dim(`\nnext: ${cd}latex-kit render paper/main.tex --verify`)
|
|
298
|
+
: chalk.dim(`\nnext: ${cd}latex-kit check && latex-kit build`));
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
301
|
+
export async function newCommand(argv) {
|
|
302
|
+
const [kind, name] = (argv._ ?? []).map(String);
|
|
303
|
+
const project = await Project.open(argv.root);
|
|
304
|
+
if (kind === 'template' && name) {
|
|
305
|
+
const r = newTemplate(project, name, Boolean(argv.force));
|
|
306
|
+
for (const f of r.written)
|
|
307
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
308
|
+
console.log(chalk.dim(`\nnext: latex-kit new document <name> --template ${name}`));
|
|
309
|
+
return 0;
|
|
310
|
+
}
|
|
311
|
+
if (kind === 'document' && name) {
|
|
312
|
+
if (!argv.template)
|
|
313
|
+
throw new UsageError('usage: latex-kit new document <name> --template <template>');
|
|
314
|
+
const r = await newDocument(project, name, String(argv.template), Boolean(argv.force));
|
|
315
|
+
for (const f of r.written)
|
|
316
|
+
console.log(`${chalk.green('+')} ${rel(f)}`);
|
|
317
|
+
if (r.schemaFile)
|
|
318
|
+
console.log(chalk.dim(` editors autocomplete it from ${rel(r.schemaFile)}`));
|
|
319
|
+
console.log(chalk.dim(`\nnext: fill in the data, then latex-kit build ${r.written[0] ? rel(r.written[0]) : ''}`));
|
|
320
|
+
return 0;
|
|
321
|
+
}
|
|
322
|
+
throw new UsageError('usage: latex-kit new template <name>\n latex-kit new document <name> --template <template>');
|
|
323
|
+
}
|
|
324
|
+
export async function cleanCommand(argv) {
|
|
325
|
+
const project = await Project.open(argv.root);
|
|
326
|
+
const rel = relative(project.root, project.outDir);
|
|
327
|
+
if (rel === '' || rel.startsWith('..') || isAbsolute(rel))
|
|
328
|
+
throw new UsageError(`refusing to delete ${project.outDir}: the out folder must be inside the project`);
|
|
329
|
+
if (!existsSync(project.outDir)) {
|
|
330
|
+
console.log(chalk.dim(`nothing to clean (${project.rel(project.outDir)}/ does not exist)`));
|
|
331
|
+
return 0;
|
|
332
|
+
}
|
|
333
|
+
rmSync(project.outDir, { recursive: true, force: true });
|
|
334
|
+
console.log(`${chalk.green('✓')} removed ${project.rel(project.outDir)}/`);
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Rebuild when templates, snippets, clauses, data or records change. Builds
|
|
339
|
+
* drafts unless --variant says otherwise; never mints IDs (use build --final).
|
|
340
|
+
*/
|
|
341
|
+
export async function watchCommand(argv) {
|
|
342
|
+
const variant = (argv.variant ?? 'draft');
|
|
343
|
+
if (variant === 'final' || variant === 'signed')
|
|
344
|
+
throw new UsageError('watch builds drafts or blanks; run latex-kit build --final when you are done');
|
|
345
|
+
const project = await Project.open(argv.root);
|
|
346
|
+
const dirs = [project.config.templates, project.config.snippets, project.config.clauses, project.config.data, project.config.documents]
|
|
347
|
+
.map((d) => project.path(d))
|
|
348
|
+
.filter((d) => existsSync(d));
|
|
349
|
+
if (dirs.length === 0)
|
|
350
|
+
throw new UsageError('nothing to watch: no templates/, data/ or documents/ here');
|
|
351
|
+
let running = false;
|
|
352
|
+
let again = false;
|
|
353
|
+
let timer = null;
|
|
354
|
+
const run = async () => {
|
|
355
|
+
if (running) {
|
|
356
|
+
again = true;
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
running = true;
|
|
360
|
+
console.log(chalk.dim(`\n— ${new Date().toLocaleTimeString()} —`));
|
|
361
|
+
try {
|
|
362
|
+
await buildCommand({ ...argv, variant });
|
|
363
|
+
}
|
|
364
|
+
catch (e) {
|
|
365
|
+
console.error(chalk.red(e.message));
|
|
366
|
+
}
|
|
367
|
+
running = false;
|
|
368
|
+
if (again) {
|
|
369
|
+
again = false;
|
|
370
|
+
void run();
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
const schedule = (file) => {
|
|
374
|
+
// generated files and editor swap files are not changes worth a build
|
|
375
|
+
if (file && /(\.schema\.json|types\.d\.ts|~|\.swp)$/.test(file))
|
|
376
|
+
return;
|
|
377
|
+
if (timer)
|
|
378
|
+
clearTimeout(timer);
|
|
379
|
+
timer = setTimeout(() => void run(), 250);
|
|
380
|
+
};
|
|
381
|
+
for (const d of dirs)
|
|
382
|
+
fsWatch(d, { recursive: true }, (_event, file) => schedule(file ? String(file) : null));
|
|
383
|
+
console.log(chalk.dim(`watching ${dirs.map((d) => project.rel(d)).join(', ')} (Ctrl-C to stop)`));
|
|
384
|
+
await run();
|
|
385
|
+
return new Promise(() => {
|
|
386
|
+
// runs until interrupted
|
|
387
|
+
});
|
|
388
|
+
}
|
package/esm/project.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { JsonSchema, TemplateMeta, z } from '@latex-kit/schema';
|
|
2
|
-
import { CompiledTemplate } 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,10 +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;
|
|
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[];
|
|
20
32
|
private constructor();
|
|
21
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[];
|
|
22
39
|
path(...parts: string[]): string;
|
|
23
40
|
rel(file: string): string;
|
|
24
41
|
get templatesDir(): string;
|
|
@@ -38,6 +55,8 @@ export declare class Project {
|
|
|
38
55
|
* `.tex` is added when the name has no extension. Never outside the project.
|
|
39
56
|
*/
|
|
40
57
|
loadSnippet: (name: string, from: string) => CompiledTemplate | null;
|
|
58
|
+
/** \\clause{id}: `clauses/<id>.tex` (or `.ts`) from the clause library. */
|
|
59
|
+
loadClause: (id: string) => LoadedClause | null;
|
|
41
60
|
/** Absolute paths of every snippet loaded so far. */
|
|
42
61
|
snippetFiles(): string[];
|
|
43
62
|
}
|