latex-kit 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +21 -2
  2. package/args.js +3 -3
  3. package/boilerplates.d.ts +14 -1
  4. package/boilerplates.js +200 -2
  5. package/build.d.ts +22 -2
  6. package/build.js +230 -95
  7. package/check.js +4 -3
  8. package/cli.js +2 -2
  9. package/commands.js +1 -0
  10. package/config.d.ts +13 -4
  11. package/config.js +1 -1
  12. package/diff.d.ts +2 -2
  13. package/diff.js +3 -3
  14. package/esm/args.js +3 -3
  15. package/esm/boilerplates.d.ts +14 -1
  16. package/esm/boilerplates.js +196 -1
  17. package/esm/build.d.ts +22 -2
  18. package/esm/build.js +231 -98
  19. package/esm/check.js +4 -3
  20. package/esm/cli.js +2 -2
  21. package/esm/commands.js +2 -1
  22. package/esm/config.d.ts +13 -4
  23. package/esm/config.js +1 -1
  24. package/esm/diff.d.ts +2 -2
  25. package/esm/diff.js +3 -3
  26. package/esm/import.js +1 -1
  27. package/esm/index.d.ts +6 -2
  28. package/esm/index.js +5 -2
  29. package/esm/lock.d.ts +24 -0
  30. package/esm/lock.js +50 -0
  31. package/esm/paper-style.d.ts +10 -0
  32. package/esm/paper-style.js +10 -0
  33. package/esm/project-commands.d.ts +4 -0
  34. package/esm/project-commands.js +76 -6
  35. package/esm/project.d.ts +18 -2
  36. package/esm/project.js +92 -5
  37. package/esm/render.js +4 -2
  38. package/esm/scaffold.d.ts +2 -1
  39. package/esm/scaffold.js +1 -1
  40. package/esm/usage.js +28 -7
  41. package/import.js +1 -1
  42. package/index.d.ts +6 -2
  43. package/index.js +24 -2
  44. package/lock.d.ts +24 -0
  45. package/lock.js +57 -0
  46. package/package.json +16 -17
  47. package/paper-style.d.ts +10 -0
  48. package/paper-style.js +13 -0
  49. package/project-commands.d.ts +4 -0
  50. package/project-commands.js +78 -6
  51. package/project.d.ts +18 -2
  52. package/project.js +90 -3
  53. package/render.js +4 -2
  54. package/scaffold.d.ts +2 -1
  55. package/scaffold.js +1 -1
  56. package/usage.js +28 -7
package/esm/cli.js CHANGED
@@ -18,8 +18,8 @@ const app = new CLI(commands, {
18
18
  version: version(),
19
19
  minimistOpts: {
20
20
  alias: { h: 'help', v: 'version', o: 'out', e: 'engine' },
21
- boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only', 'force', 'schema', 'paper'],
22
- string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template', 'name', 'against'],
21
+ boolean: ['help', 'version', 'local', 'verify', 'json', 'final', 'strict', 'tex-only', 'force', 'schema', 'paper', 'check'],
22
+ string: ['out', 'engine', 'image', 'root', 'platform', 'source-date-epoch', 'variant', 'template', 'name', 'against', 'only', 'locale', 'signatures', 'preset'],
23
23
  default: { strict: undefined, schema: true },
24
24
  },
25
25
  });
package/esm/commands.js CHANGED
@@ -3,7 +3,7 @@ import { join } from 'path';
3
3
  import chalk from 'yanse';
4
4
  import { UsageError } from './args';
5
5
  import { doctorCommand } from './doctor';
6
- import { buildCommand, checkCommand, cleanCommand, diffCommand, fieldsCommand, importCommand, initCommand, newCommand, styCommand, typegenCommand, watchCommand } from './project-commands';
6
+ import { buildCommand, checkCommand, cleanCommand, diffCommand, fieldsCommand, importCommand, initCommand, lockCommand, newCommand, styCommand, typegenCommand, watchCommand } from './project-commands';
7
7
  import { renderCommand } from './render';
8
8
  import { help } from './usage';
9
9
  /** The package version, from package.json next to the built files. */
@@ -29,6 +29,7 @@ const COMMANDS = {
29
29
  import: importCommand,
30
30
  diff: diffCommand,
31
31
  sty: styCommand,
32
+ lock: lockCommand,
32
33
  render: renderCommand,
33
34
  doctor: doctorCommand,
34
35
  };
package/esm/config.d.ts CHANGED
@@ -1,12 +1,14 @@
1
- import type { Backend, Engine } from '@latex-kit/render';
1
+ import type { Backend, EngineChoice } from '@latex-kit/render';
2
2
  /** latex-kit.config.ts (or .js, .mjs, .cjs, .json) at the project root. */
3
3
  export interface LatexKitConfig {
4
4
  /** One folder per template: `<templates>/<name>/template.tex` and optional `schema.ts`. Default `templates`. */
5
5
  templates?: string;
6
6
  /** Shared pieces for \snippet{name}. Default `snippets`. */
7
7
  snippets?: string;
8
- /** The clause library for \\clause{id}: `<clauses>/<id>.tex`. Default `clauses`. */
8
+ /** The clause library for \\clause{id}: `<clauses>/<id>.tex` or `.ts`. Default `clauses`. */
9
9
  clauses?: string;
10
+ /** TypeScript components for \\component{name}{path}: `<components>/<name>.ts`. Default `components`. */
11
+ components?: string;
10
12
  /** Shared records that references point at: `<data>/<collection>/<id>.json`. Default `data`. */
11
13
  data?: string;
12
14
  /** Document records: `<documents>/<name>.json|yaml|ts`. Default `documents`. */
@@ -15,12 +17,19 @@ export interface LatexKitConfig {
15
17
  out?: string;
16
18
  /** Default locale for dates, numbers and money. Default `en-US`. */
17
19
  locale?: string;
18
- engine?: Engine;
20
+ /** Default `auto`: chosen from the packages each document loads. */
21
+ engine?: EngineChoice;
22
+ /**
23
+ * Folder with signature images for signed builds (`<name>.png|pdf|jpg`).
24
+ * Keep it outside the repository; `--signatures` and LATEX_KIT_SIGNATURES
25
+ * override it. A leading ~ is the home folder.
26
+ */
27
+ signatures?: string;
19
28
  backend?: Backend;
20
29
  image?: string;
21
30
  platform?: string | null;
22
31
  }
23
- export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'clauses' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform'> & {
32
+ export type ResolvedConfig = Required<Pick<LatexKitConfig, 'templates' | 'snippets' | 'clauses' | 'components' | 'data' | 'documents' | 'out' | 'locale'>> & Pick<LatexKitConfig, 'engine' | 'backend' | 'image' | 'platform' | 'signatures'> & {
24
33
  file: string | null;
25
34
  };
26
35
  export declare function defineConfig(config: LatexKitConfig): LatexKitConfig;
package/esm/config.js CHANGED
@@ -5,7 +5,7 @@ export function defineConfig(config) {
5
5
  return config;
6
6
  }
7
7
  export const CONFIG_FILES = ['latex-kit.config.ts', 'latex-kit.config.mts', 'latex-kit.config.js', 'latex-kit.config.mjs', 'latex-kit.config.cjs', 'latex-kit.config.json'];
8
- const DEFAULTS = { templates: 'templates', snippets: 'snippets', clauses: 'clauses', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
8
+ const DEFAULTS = { templates: 'templates', snippets: 'snippets', clauses: 'clauses', components: 'components', data: 'data', documents: 'documents', out: 'out', locale: 'en-US' };
9
9
  export async function loadConfig(root) {
10
10
  for (const name of CONFIG_FILES) {
11
11
  const file = join(resolve(root), name);
package/esm/diff.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { Engine } from '@latex-kit/render';
1
+ import { EngineChoice } from '@latex-kit/render';
2
2
  import { Variant } from '@latex-kit/template';
3
3
  import { Project } from './project';
4
4
  export interface DiffOptions {
5
5
  variant?: Variant;
6
- engine?: Engine;
6
+ engine?: EngineChoice;
7
7
  backend?: 'docker' | 'local';
8
8
  image?: string;
9
9
  platform?: string | null;
package/esm/diff.js CHANGED
@@ -15,14 +15,14 @@ async function redline(project, oldTex, newTex, dir, name, texInputs, options) {
15
15
  writeFileSync(join(dir, 'latex-kit.sty'), LATEX_KIT_STY);
16
16
  const tex = join(dir, `${name}.tex`);
17
17
  const rel = (p) => relative(project.root, p);
18
- await runLatexdiff({ root: project.root, old: rel(oldTex), new: rel(newTex), output: rel(tex), backend: options.backend, image: options.image, platform: options.platform });
18
+ await runLatexdiff({ root: project.root, old: rel(oldTex), new: rel(newTex), output: rel(tex), backend: options.backend, image: project.image(options.image), platform: options.platform });
19
19
  const r = await render({
20
20
  file: tex,
21
21
  root: project.root,
22
22
  outDir: rel(dir),
23
- engine: options.engine ?? project.config.engine ?? 'lualatex',
23
+ engine: options.engine ?? project.config.engine ?? 'auto',
24
24
  backend: options.backend ?? project.config.backend,
25
- image: options.image ?? project.config.image,
25
+ image: project.image(options.image),
26
26
  platform: options.platform !== undefined ? options.platform : project.config.platform,
27
27
  texInputs: [rel(dir), ...texInputs.map(rel)],
28
28
  });
package/esm/import.js CHANGED
@@ -87,7 +87,7 @@ export async function importDocument(project, file, options = {}) {
87
87
  }
88
88
  const mediaDir = join(dir, 'media');
89
89
  try {
90
- await runPandoc({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend });
90
+ await runPandoc({ root: project.root, input: source, output: target, extractMedia: mediaDir, backend: options.backend, image: project.lock?.pandocImage });
91
91
  }
92
92
  finally {
93
93
  if (staged)
package/esm/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/esm/index.js CHANGED
@@ -2,14 +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, 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 { address, bilingual, BUILTIN_COMPONENTS, date, defineClause, defineComponent, escapeLatex, exhibit, exhibits, get, money, number, percent, raw, RawLatex, signatures, table, tex, } from '@latex-kit/components';
15
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
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The Constructive whitepaper style, from constructive-io/rls-whitepaper and
3
+ * hyperweb-whitepaper (tex/headers/): the code colour palette and the
4
+ * TypeScript listings style, copied verbatim so new papers look like ours.
5
+ * Regenerate from those files rather than editing here.
6
+ */
7
+ /** tex/headers/colors.tex */
8
+ export declare const WHITEPAPER_COLORS_TEX = "% Define colors for code highlighting\n\\definecolor{lightpurple}{rgb}{0.85, 0.85, 1}\n\\definecolor{white}{rgb}{1, 1, 1}\n\\definecolor{codegray}{gray}{0.9}\n\\definecolor{codeblue}{rgb}{0,0,0.6}\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{codebackground}{rgb}{0.95,0.95,0.95}\n\\definecolor{codeorange}{rgb}{1, 0.6, 0.2}\n\\definecolor{codered}{rgb}{0.8, 0, 0}\n\\definecolor{codeyellow}{rgb}{0.9, 0.9, 0.4}\n\\definecolor{codeteal}{rgb}{0, 0.5, 0.5}\n\\definecolor{codepink}{rgb}{1, 0.5, 0.7}\n\\definecolor{codebrown}{rgb}{0.6, 0.4, 0.2}\n\\definecolor{codelightblue}{rgb}{0.7, 0.85, 1}\n\\definecolor{codelightgreen}{rgb}{0.7, 1, 0.7}\n\\definecolor{codedarkblue}{rgb}{0, 0.2, 0.5}\n\\definecolor{codedarkpurple}{rgb}{0.4, 0.2, 0.6}\n\\definecolor{black}{rgb}{0, 0, 0}\n\\pagecolor{white}";
9
+ /** tex/headers/typescript.tex */
10
+ export declare const WHITEPAPER_TYPESCRIPT_TEX = "% Code style definition\n\\lstdefinelanguage{typescript}{\n keywords={abstract, arguments, await, boolean, break, byte, case, catch,\n class, const, continue, debugger, default, delete, do, double, else,\n enum, eval, export, extends, false, final, finally, float, for,\n function, goto, if, implements, import, in, instanceof, int, interface,\n let, long, native, new, null, package, private, protected, public,\n return, short, static, super, switch, synchronized, this, throw,\n throws, transient, true, try, typeof, var, void, volatile, while, with,\n yield, async, from, of},\n keywordstyle=\\color{codeblue},\n sensitive=true,\n comment=[l]{//},\n morecomment=[s]{/*}{*/},\n commentstyle=\\color{codegreen},\n stringstyle=\\color{codepurple},\n morestring=[b]',\n morestring=[b]\"\n}\n\n% Enhanced Code Style Definition for TypeScript and JavaScript\n\\lstdefinestyle{typescript}{\n language=typescript,\n backgroundcolor=\\color{white},\n basicstyle=\\ttfamily\\footnotesize,\n breakatwhitespace=false,\n breaklines=true,\n captionpos=b,\n keepspaces=true,\n numbers=left,\n numbersep=5pt,\n showspaces=false,\n showstringspaces=false,\n showtabs=false,\n tabsize=2,\n numberstyle=\\tiny\\color{black},\n % Additional TypeScript-specific highlighting\n moredelim=[is][\\textcolor{codepurple}]{\\#\\{}{\\}}, % Template literals\n moredelim=[is][\\textcolor{codeblue}]{<}{>}, % Generic types\n literate=\n {=>}{{\\textcolor{codeblue}{=>}}}2 \n {interface}{{\\textcolor{codeblue}{interface}}}9\n {type}{{\\textcolor{codered}{type}}}4\n {export}{{\\textcolor{codegreen}{export}}}6\n {import}{{\\textcolor{codeorange}{import}}}6\n {from}{{\\textcolor{codeblue}{from}}}4\n {return}{{\\textcolor{codeteal}{return}}}6 \n {function}{{\\textcolor{codeblue}{function}}}8\n {string}{{\\textcolor{codepink}{string}}}6 \n {let}{{\\textcolor{codered}{let}}}3 \n% {const}{{\\textcolor{codedarkpurple}{const}}}5 \n {var}{{\\textcolor{codelightblue}{var}}}3 \n {while}{{\\textcolor{codered}{while}}}5 \n {if}{{\\textcolor{codeorange}{if}}}2 \n {else}{{\\textcolor{codeyellow}{else}}}4\n\t{@onlyOwner}{{\\textcolor{codered}{@onlyOwner}}}9\n\t{@instantiate}{{\\textcolor{codered}{@instantiate}}}{10}\n}\n\n";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The Constructive whitepaper style, from constructive-io/rls-whitepaper and
3
+ * hyperweb-whitepaper (tex/headers/): the code colour palette and the
4
+ * TypeScript listings style, copied verbatim so new papers look like ours.
5
+ * Regenerate from those files rather than editing here.
6
+ */
7
+ /** tex/headers/colors.tex */
8
+ export const WHITEPAPER_COLORS_TEX = '% Define colors for code highlighting\n\\definecolor{lightpurple}{rgb}{0.85, 0.85, 1}\n\\definecolor{white}{rgb}{1, 1, 1}\n\\definecolor{codegray}{gray}{0.9}\n\\definecolor{codeblue}{rgb}{0,0,0.6}\n\\definecolor{codegreen}{rgb}{0,0.6,0}\n\\definecolor{codepurple}{rgb}{0.58,0,0.82}\n\\definecolor{codebackground}{rgb}{0.95,0.95,0.95}\n\\definecolor{codeorange}{rgb}{1, 0.6, 0.2}\n\\definecolor{codered}{rgb}{0.8, 0, 0}\n\\definecolor{codeyellow}{rgb}{0.9, 0.9, 0.4}\n\\definecolor{codeteal}{rgb}{0, 0.5, 0.5}\n\\definecolor{codepink}{rgb}{1, 0.5, 0.7}\n\\definecolor{codebrown}{rgb}{0.6, 0.4, 0.2}\n\\definecolor{codelightblue}{rgb}{0.7, 0.85, 1}\n\\definecolor{codelightgreen}{rgb}{0.7, 1, 0.7}\n\\definecolor{codedarkblue}{rgb}{0, 0.2, 0.5}\n\\definecolor{codedarkpurple}{rgb}{0.4, 0.2, 0.6}\n\\definecolor{black}{rgb}{0, 0, 0}\n\\pagecolor{white}';
9
+ /** tex/headers/typescript.tex */
10
+ export const WHITEPAPER_TYPESCRIPT_TEX = "% Code style definition\n\\lstdefinelanguage{typescript}{\n keywords={abstract, arguments, await, boolean, break, byte, case, catch,\n class, const, continue, debugger, default, delete, do, double, else,\n enum, eval, export, extends, false, final, finally, float, for,\n function, goto, if, implements, import, in, instanceof, int, interface,\n let, long, native, new, null, package, private, protected, public,\n return, short, static, super, switch, synchronized, this, throw,\n throws, transient, true, try, typeof, var, void, volatile, while, with,\n yield, async, from, of},\n keywordstyle=\\color{codeblue},\n sensitive=true,\n comment=[l]{//},\n morecomment=[s]{/*}{*/},\n commentstyle=\\color{codegreen},\n stringstyle=\\color{codepurple},\n morestring=[b]',\n morestring=[b]\"\n}\n\n% Enhanced Code Style Definition for TypeScript and JavaScript\n\\lstdefinestyle{typescript}{\n language=typescript,\n backgroundcolor=\\color{white},\n basicstyle=\\ttfamily\\footnotesize,\n breakatwhitespace=false,\n breaklines=true,\n captionpos=b,\n keepspaces=true,\n numbers=left,\n numbersep=5pt,\n showspaces=false,\n showstringspaces=false,\n showtabs=false,\n tabsize=2,\n numberstyle=\\tiny\\color{black},\n % Additional TypeScript-specific highlighting\n moredelim=[is][\\textcolor{codepurple}]{\\#\\{}{\\}}, % Template literals\n moredelim=[is][\\textcolor{codeblue}]{<}{>}, % Generic types\n literate=\n {=>}{{\\textcolor{codeblue}{=>}}}2 \n {interface}{{\\textcolor{codeblue}{interface}}}9\n {type}{{\\textcolor{codered}{type}}}4\n {export}{{\\textcolor{codegreen}{export}}}6\n {import}{{\\textcolor{codeorange}{import}}}6\n {from}{{\\textcolor{codeblue}{from}}}4\n {return}{{\\textcolor{codeteal}{return}}}6 \n {function}{{\\textcolor{codeblue}{function}}}8\n {string}{{\\textcolor{codepink}{string}}}6 \n {let}{{\\textcolor{codered}{let}}}3 \n% {const}{{\\textcolor{codedarkpurple}{const}}}5 \n {var}{{\\textcolor{codelightblue}{var}}}3 \n {while}{{\\textcolor{codered}{while}}}5 \n {if}{{\\textcolor{codeorange}{if}}}2 \n {else}{{\\textcolor{codeyellow}{else}}}4\n\t{@onlyOwner}{{\\textcolor{codered}{@onlyOwner}}}9\n\t{@instantiate}{{\\textcolor{codered}{@instantiate}}}{10}\n}\n\n";
@@ -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>;
@@ -5,11 +5,13 @@ import { existsSync, mkdirSync, rmSync, watch as fsWatch, writeFileSync } from '
5
5
  import { isAbsolute, join, relative } from 'path';
6
6
  import chalk from 'yanse';
7
7
  import { UsageError } from './args';
8
+ import { PAPER_PRESETS } from './boilerplates';
8
9
  import { buildBlank, buildDocument, BuildError } from './build';
9
10
  import { checkProject, templateFields } from './check';
10
11
  import { version } from './commands';
11
12
  import { diffDocument, diffFiles } from './diff';
12
13
  import { importDocument } from './import';
14
+ import { currentPins, LOCK_FILE, writeLock } from './lock';
13
15
  import { Project } from './project';
14
16
  import { initProject, newDocument, newTemplate } from './scaffold';
15
17
  function printDiagnostics(ds, json) {
@@ -19,12 +21,35 @@ function printDiagnostics(ds, json) {
19
21
  console.error((d.severity === 'error' ? chalk.red : chalk.yellow)(formatDiagnostic(d)));
20
22
  }
21
23
  const rel = (p) => (p ? relative(process.cwd(), p) : null);
24
+ /** `--only nda-*,invoice-0001`: comma-separated names, * matches anything. */
25
+ export function onlyMatcher(only) {
26
+ if (only === undefined || only === null || only === '' || only === true)
27
+ return null;
28
+ const patterns = (Array.isArray(only) ? only : [only]).flatMap((o) => String(o).split(',')).map((p) => p.trim()).filter(Boolean);
29
+ if (patterns.length === 0)
30
+ return null;
31
+ const res = patterns.map((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`));
32
+ return (name) => res.some((r) => r.test(name));
33
+ }
34
+ function checkLocale(locale) {
35
+ if (locale === undefined)
36
+ return undefined;
37
+ try {
38
+ return Intl.getCanonicalLocales(String(locale))[0];
39
+ }
40
+ catch {
41
+ throw new UsageError(`--locale ${locale} is not a language tag (like en-US or ja-JP)`);
42
+ }
43
+ }
22
44
  export async function buildCommand(argv) {
23
45
  const variant = (argv.variant ?? (argv.final ? 'final' : 'draft'));
24
46
  if (!VARIANTS.includes(variant))
25
47
  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(', ')}`);
48
+ if (argv.engine && argv.engine !== 'auto' && !ENGINES.includes(argv.engine))
49
+ throw new UsageError(`--engine must be auto or one of ${ENGINES.join(', ')}`);
50
+ if (argv.signatures !== undefined && variant !== 'signed')
51
+ throw new UsageError('--signatures only applies to --variant signed');
52
+ const only = onlyMatcher(argv.only);
28
53
  const project = await Project.open(argv.root);
29
54
  const options = {
30
55
  variant,
@@ -35,13 +60,16 @@ export async function buildCommand(argv) {
35
60
  platform: argv.platform,
36
61
  verify: Boolean(argv.verify),
37
62
  texOnly: Boolean(argv['tex-only']),
63
+ locale: checkLocale(argv.locale),
64
+ force: Boolean(argv.force),
65
+ signatures: argv.signatures,
38
66
  };
39
67
  const json = Boolean(argv.json);
40
68
  const log = (s) => !json && console.error(s);
41
69
  const targets = [];
42
70
  const files = (argv._ ?? []).map(String);
43
71
  if (variant === 'blank' && files.length === 0) {
44
- const names = argv.template ? [String(argv.template)] : project.templateNames();
72
+ const names = (argv.template ? [String(argv.template)] : project.templateNames()).filter((n) => !only || only(n));
45
73
  for (const n of names)
46
74
  targets.push({ label: `template ${n}`, run: () => buildBlank(project, n, options) });
47
75
  }
@@ -58,13 +86,21 @@ export async function buildCommand(argv) {
58
86
  keep.push(f);
59
87
  docs = keep;
60
88
  }
89
+ if (only)
90
+ docs = docs.filter((f) => only(project.documentName(f)));
61
91
  for (const f of docs)
62
92
  targets.push({ label: rel(f), run: () => buildDocument(project, f, options) });
63
93
  }
64
94
  if (targets.length === 0) {
95
+ if (only) {
96
+ log(chalk.red(`--only ${argv.only} matched nothing`));
97
+ return 1;
98
+ }
65
99
  log(chalk.yellow(`nothing to build (no documents in ${project.rel(project.documentsDir)}/)`));
66
100
  return 0;
67
101
  }
102
+ for (const d of project.codeDiagnostics)
103
+ printDiagnostics([d], json);
68
104
  const results = [];
69
105
  let failed = 0;
70
106
  for (const t of targets) {
@@ -77,7 +113,8 @@ export async function buildCommand(argv) {
77
113
  failed++;
78
114
  results.push({ ...r, tex: rel(r.tex), pdf: rel(r.pdf), diagnostics: r.diagnostics.length });
79
115
  if (!json) {
80
- console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${r.docId ? chalk.dim(` ${r.docId}`) : ''}`);
116
+ 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(' ');
117
+ console.log(`${bad ? chalk.red('✗') : chalk.green('✓')} ${rel(r.pdf ?? r.tex)}${notes ? chalk.dim(` ${notes}`) : ''}`);
81
118
  if (r.minted)
82
119
  console.log(chalk.dim(` minted ${r.docId} and saved it in ${t.label}`));
83
120
  if (r.verified !== undefined)
@@ -134,7 +171,7 @@ export async function fieldsCommand(argv) {
134
171
  const width = Math.max(...fields.map((f) => f.absolute.length), 4);
135
172
  for (const f of fields) {
136
173
  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}`);
174
+ console.log(`${f.absolute.padEnd(width)} ${chalk.dim(f.kind.padEnd(9))} ${chalk.dim(`${f.file}:${f.line}`)}${filters}`);
138
175
  }
139
176
  return diagnostics.some((d) => d.severity === 'error') ? 1 : 0;
140
177
  }
@@ -221,9 +258,42 @@ export async function diffCommand(argv) {
221
258
  console.log(`${chalk.green('✓')} ${rel(result.pdf)} ${chalk.dim('(insertions underlined in blue, deletions struck through in red)')}`);
222
259
  return 0;
223
260
  }
261
+ /** Pin the TeX and pandoc images in latex-kit.lock (commit it). */
262
+ export async function lockCommand(argv) {
263
+ const project = await Project.open(argv.root);
264
+ const pins = currentPins();
265
+ const file = join(project.root, LOCK_FILE);
266
+ if (argv.check) {
267
+ if (!project.lock) {
268
+ console.log(chalk.yellow(`no ${LOCK_FILE}: builds use this latex-kit's default image`));
269
+ return 1;
270
+ }
271
+ const stale = project.lock.image !== pins.image || project.lock.pandocImage !== pins.pandocImage;
272
+ 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`);
273
+ return stale ? 1 : 0;
274
+ }
275
+ const { lock, previous } = writeLock(project.root);
276
+ console.log(`${chalk.green('✓')} ${rel(file)}`);
277
+ if (previous && previous.image !== lock.image)
278
+ console.log(chalk.dim(` image ${previous.image}\n → ${lock.image}\n rebuilt PDFs will differ from earlier ones`));
279
+ else if (!previous)
280
+ console.log(chalk.dim(` image ${lock.image}`));
281
+ else
282
+ console.log(chalk.dim(' already up to date'));
283
+ return 0;
284
+ }
224
285
  export async function initCommand(argv) {
225
286
  const dir = join(process.cwd(), argv._?.[0] ? String(argv._[0]) : '.');
226
- const r = initProject(dir, { paper: Boolean(argv.paper), force: Boolean(argv.force), version: version() });
287
+ const preset = (argv.preset ?? 'whitepaper');
288
+ if (!PAPER_PRESETS.includes(preset))
289
+ throw new UsageError(`--preset must be one of ${PAPER_PRESETS.join(', ')}`);
290
+ if (argv.preset && !argv.paper)
291
+ throw new UsageError('--preset only applies to init --paper');
292
+ const r = initProject(dir, { paper: Boolean(argv.paper), preset, force: Boolean(argv.force), version: version() });
293
+ if (!argv.paper && !existsSync(join(dir, LOCK_FILE))) {
294
+ writeLock(dir);
295
+ r.written.push(join(dir, LOCK_FILE));
296
+ }
227
297
  for (const f of r.written)
228
298
  console.log(`${chalk.green('+')} ${rel(f)}`);
229
299
  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
  };