@latex-kit/template 0.2.0 → 0.4.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 CHANGED
@@ -51,11 +51,56 @@ Document ID: \docid
51
51
  | `\sep{…}` | Inside `\each`: printed between items, not after the last |
52
52
  | `\snippet{name}` | Includes `name.tex` (next to the template, then `snippets/`) with the same data |
53
53
  | `\docid` | The document's ID, minted once and stored on the record |
54
+ | `\clause{id}` | Places a numbered clause from the library (`clauses/<id>.tex`), filled with the same data |
55
+ | `\clauseref{id}` | Prints that clause's number. A reference to a clause the document doesn't contain fails a final build |
56
+ | `\signature{party}` | A signature block for a party or signer (see below) |
57
+ | `\component{name}{path}` | Calls a TypeScript component with the value at `path` (empty: the whole record) |
54
58
 
55
59
  Special values: `$variant`, `$locale`, `$docid`, `$template`.
56
60
 
57
- `\snippet` and `\clauseref` (reserved for the coming clause library) are
58
- named so they never collide with LaTeX's `\partial` and `\ref`.
61
+ `\snippet` and `\clauseref` are named so they never collide with LaTeX's
62
+ `\partial` and `\ref`.
63
+
64
+ ### Clauses
65
+
66
+ A clause is a template fragment with a short header:
67
+
68
+ ```latex
69
+ % title: Confidentiality
70
+ % version: 3
71
+ The Recipient will keep it confidential for \field{termMonths|words} months,
72
+ subject to Section~\clauseref{nda/exclusions}.
73
+ ```
74
+
75
+ Each placed clause becomes `\lkclause{title}{label}` (a numbered section by
76
+ default; redefine `\lkclause` to change the style). Every build's manifest
77
+ lists the clause IDs and versions it used. A clause can also be TypeScript
78
+ (`defineClause` in [`@latex-kit/components`](../components)): a template
79
+ text `body`, or a `render(data, ctx)` function.
80
+
81
+ ### Signatures
82
+
83
+ `\signature{discloser}` prints `\lksignature{org}{name}{title}{signature}{date}`.
84
+ A party with a `signer` (or `kind: "organization"`) is an organization: its
85
+ name in bold, then the signer. Anything else with a `name` signs for itself.
86
+
87
+ | Variant | Signature line | Date line |
88
+ |---|---|---|
89
+ | `draft`, `final` | empty | empty |
90
+ | `blank` | empty; organization, name and title are labelled blanks | empty |
91
+ | `signed` | the signer's image (`signatureImage` option), else `/s/ Name` | the date from `signed: { discloser: { date } }` |
92
+
93
+ Two blocks fit side by side: `\signature{a}\hfill\signature{b}`. Change the
94
+ look with `\lksignaturewidth`, `\lksignatureheight`, or by redefining
95
+ `\lksignature`.
96
+
97
+ ### Components
98
+
99
+ `\component{name}{path}` calls a function from the `components` option with
100
+ the value at `path` and a context (variant, locale, `format()`,
101
+ `signature()`, `missing()`). It returns `tex`-tagged LaTeX, inserted as is,
102
+ or a string, which is escaped. Errors are reported at the macro. The
103
+ built-in components and helpers are in [`@latex-kit/components`](../components).
59
104
 
60
105
  ### Conditions
61
106
 
@@ -92,7 +137,7 @@ Dates, numbers and money follow the record's locale (`ja-JP`, `de-DE`, …).
92
137
  | `draft` | filled; a missing value prints a red `missing: path` box | DRAFT watermark, date and git commit |
93
138
  | `blank` | every field is a labelled line | none |
94
139
  | `final` | filled; a missing value is an error | none |
95
- | `signed` | like `final`; test `$variant == "signed"` for signature text | none |
140
+ | `signed` | like `final`; `\signature` blocks are signed | none |
96
141
 
97
142
  ## Usage
98
143
 
package/analyze.d.ts CHANGED
@@ -1,9 +1,10 @@
1
+ import { LoadedClause } from './clause';
1
2
  import { CompiledTemplate } from './compile';
2
3
  import { Diagnostic } from './diagnostics';
3
4
  import { JsonSchema } from './jsonschema';
4
5
  export interface FieldRef {
5
- /** How the template reads it: `field`, `raw`, `when`, `each`. */
6
- kind: 'field' | 'raw' | 'when' | 'each';
6
+ /** How the template reads it. */
7
+ kind: 'field' | 'raw' | 'when' | 'each' | 'signature' | 'component';
7
8
  /** The path as written, e.g. `item.price`. */
8
9
  path: string;
9
10
  /** The path from the data root, e.g. `items[].price`. */
@@ -17,10 +18,21 @@ export interface AnalyzeOptions {
17
18
  /** JSON Schema of the record's data. Without it only syntax is checked. */
18
19
  schema?: JsonSchema;
19
20
  loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
21
+ loadClause?: (id: string) => LoadedClause | null;
22
+ /** Names \component can use. Without it component names are not checked. */
23
+ components?: string[];
20
24
  }
21
25
  export interface AnalyzeResult {
22
26
  fields: FieldRef[];
23
27
  snippets: string[];
28
+ /** Library clauses the template can place, with versions. */
29
+ clauses: {
30
+ id: string;
31
+ version?: string;
32
+ file: string;
33
+ }[];
34
+ /** Components the template calls. */
35
+ components: string[];
24
36
  diagnostics: Diagnostic[];
25
37
  }
26
38
  /**
package/analyze.js CHANGED
@@ -14,6 +14,9 @@ function analyzeTemplate(template, options = {}) {
14
14
  const diagnostics = [...template.diagnostics];
15
15
  const fields = [];
16
16
  const snippets = [];
17
+ const clauses = [];
18
+ const components = [];
19
+ const refs = [];
17
20
  const stack = [template.file];
18
21
  const resolve = (path, scopes, loc) => {
19
22
  const [head, ...rest] = (0, path_1.splitPath)(path);
@@ -105,9 +108,58 @@ function analyzeTemplate(template, options = {}) {
105
108
  stack.pop();
106
109
  break;
107
110
  }
111
+ case 'clause': {
112
+ const clause = options.loadClause?.(node.id) ?? null;
113
+ if (!clause) {
114
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause not found: ${node.id}`, node.loc));
115
+ break;
116
+ }
117
+ if (stack.includes(clause.template.file)) {
118
+ diagnostics.push((0, diagnostics_1.diag)('error', `clause ${node.id} includes itself`, node.loc));
119
+ break;
120
+ }
121
+ if (!clauses.some((c) => c.id === node.id)) {
122
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
123
+ diagnostics.push(...clause.template.diagnostics);
124
+ if (!clause.title)
125
+ diagnostics.push((0, diagnostics_1.diag)('warning', `clause ${node.id} has no "% title:" line, so it prints as a bare number`, { file: clause.template.file, line: 1, column: 1 }));
126
+ }
127
+ stack.push(clause.template.file);
128
+ walk(clause.template.nodes, scopes);
129
+ stack.pop();
130
+ break;
131
+ }
132
+ case 'clauseref':
133
+ refs.push({ id: node.id, loc: node.loc });
134
+ break;
135
+ case 'signature': {
136
+ const { absolute, schema } = resolve(node.path, scopes, node.loc);
137
+ fields.push({ kind: 'signature', path: node.path, absolute, filters: [], ...node.loc });
138
+ if (root && schema !== undefined && (0, jsonschema_1.schemaAt)(schema, ['name'], root) === undefined) {
139
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\signature{${node.path}}: ${absolute} has no name in the schema, so it is not a party or signer`, node.loc));
140
+ }
141
+ break;
142
+ }
143
+ case 'component': {
144
+ if (!components.includes(node.name))
145
+ components.push(node.name);
146
+ if (options.components && !options.components.includes(node.name)) {
147
+ diagnostics.push((0, diagnostics_1.diag)('error', `unknown component ${node.name} (known: ${[...options.components].sort().join(', ') || 'none'})`, node.loc));
148
+ }
149
+ if (node.path) {
150
+ const { absolute } = resolve(node.path, scopes, node.loc);
151
+ fields.push({ kind: 'component', path: node.path, absolute, filters: [node.name], ...node.loc });
152
+ }
153
+ break;
154
+ }
108
155
  }
109
156
  }
110
157
  };
111
158
  walk(template.nodes, []);
112
- return { fields, snippets, diagnostics };
159
+ for (const r of refs) {
160
+ if (!clauses.some((c) => c.id === r.id)) {
161
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\clauseref{${r.id}}: the template never places \\clause{${r.id}}`, r.loc));
162
+ }
163
+ }
164
+ return { fields, snippets, clauses, components, diagnostics };
113
165
  }
package/clause.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { CompiledTemplate } from './compile';
2
+ import type { Component } from './component';
3
+ export interface ClauseMeta {
4
+ title?: string;
5
+ version?: string;
6
+ }
7
+ /** A clause from the library, compiled, with its header. */
8
+ export interface LoadedClause extends ClauseMeta {
9
+ id: string;
10
+ /** The clause text (empty for a clause written as a TypeScript function). */
11
+ template: CompiledTemplate;
12
+ /** A TypeScript clause's body, called with the record's data. */
13
+ render?: Component;
14
+ }
15
+ export interface ClauseUse {
16
+ id: string;
17
+ version?: string;
18
+ file: string;
19
+ }
20
+ /**
21
+ * Read a clause file's header: the leading `%` comment lines.
22
+ *
23
+ * % title: Confidentiality
24
+ * % version: 3
25
+ */
26
+ export declare function parseClauseHeader(text: string): ClauseMeta;
27
+ export declare const clauseLabel: (id: string) => string;
package/clause.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clauseLabel = void 0;
4
+ exports.parseClauseHeader = parseClauseHeader;
5
+ /**
6
+ * Read a clause file's header: the leading `%` comment lines.
7
+ *
8
+ * % title: Confidentiality
9
+ * % version: 3
10
+ */
11
+ function parseClauseHeader(text) {
12
+ const meta = {};
13
+ for (const line of text.split('\n')) {
14
+ const t = line.trim();
15
+ if (t === '')
16
+ continue;
17
+ if (!t.startsWith('%'))
18
+ break;
19
+ const m = /^%\s*(title|version)\s*:\s*(.*?)\s*$/i.exec(t);
20
+ if (m)
21
+ meta[m[1].toLowerCase()] = m[2];
22
+ }
23
+ return meta;
24
+ }
25
+ const clauseLabel = (id) => `clause:${id}`;
26
+ exports.clauseLabel = clauseLabel;
package/codemod.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export interface Converted {
2
+ /** The token as it appeared, e.g. `@COMPANY@LEGAL_NAME@` or `{{ party.name }}`. */
3
+ from: string;
4
+ /** What it became, e.g. `\field{company.legalName}`. */
5
+ to: string;
6
+ line: number;
7
+ }
8
+ export interface ConvertResult {
9
+ tex: string;
10
+ converted: Converted[];
11
+ /** Tokens that looked like placeholders but could not become a valid path. */
12
+ skipped: Converted[];
13
+ }
14
+ /** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
15
+ export declare function camelSegment(seg: string): string;
16
+ /**
17
+ * Turn placeholder tokens from older templates or Word documents into
18
+ * `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
19
+ * `{{ path }}` (common in Word/Markdown templates, also after pandoc
20
+ * escaped it). Anything that cannot become a valid path is left alone and
21
+ * reported.
22
+ */
23
+ export declare function convertPlaceholders(tex: string): ConvertResult;
24
+ /** Make sure a document loads latex-kit.sty, right before \begin{document}. */
25
+ export declare function ensureLatexKitPackage(tex: string): string;
package/codemod.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.camelSegment = camelSegment;
4
+ exports.convertPlaceholders = convertPlaceholders;
5
+ exports.ensureLatexKitPackage = ensureLatexKitPackage;
6
+ const path_1 = require("./path");
7
+ /** LEGAL_NAME → legalName, COMPANY → company, already camelCase → unchanged. */
8
+ function camelSegment(seg) {
9
+ const s = seg.replace(/\\_/g, '_');
10
+ if (!s.includes('_') && s !== s.toUpperCase())
11
+ return s;
12
+ const parts = s.toLowerCase().split('_').filter(Boolean);
13
+ return parts.map((p, i) => (i === 0 ? p : p[0].toUpperCase() + p.slice(1))).join('');
14
+ }
15
+ // @GROUP@FIELD@ with letters, digits and underscores (possibly escaped as \_ by pandoc)
16
+ const LEGACY = /@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@([A-Za-z](?:[A-Za-z0-9_]|\\_)*)@/g;
17
+ // {{ path }} as typed, or \{\{ path \}\} as pandoc escapes it
18
+ const MUSTACHE = /(?:\{\{|\\\{\\\{)\s*([^{}\\]*(?:\\_[^{}\\]*)*?)\s*(?:\}\}|\\\}\\\})/g;
19
+ function lineAt(text, offset) {
20
+ let n = 1;
21
+ for (let i = 0; i < offset; i++)
22
+ if (text.charCodeAt(i) === 10)
23
+ n++;
24
+ return n;
25
+ }
26
+ /**
27
+ * Turn placeholder tokens from older templates or Word documents into
28
+ * `\field{…}`: `@GROUP@FIELD@` (the legacy generator's tokens) and
29
+ * `{{ path }}` (common in Word/Markdown templates, also after pandoc
30
+ * escaped it). Anything that cannot become a valid path is left alone and
31
+ * reported.
32
+ */
33
+ function convertPlaceholders(tex) {
34
+ const converted = [];
35
+ const skipped = [];
36
+ let out = tex.replace(LEGACY, (whole, group, field, offset) => {
37
+ const path = `${camelSegment(group)}.${camelSegment(field)}`;
38
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(tex, offset) };
39
+ if (!(0, path_1.isPath)(path)) {
40
+ skipped.push(item);
41
+ return whole;
42
+ }
43
+ converted.push(item);
44
+ return item.to;
45
+ });
46
+ const before = out;
47
+ out = out.replace(MUSTACHE, (whole, inner, offset) => {
48
+ const path = inner.replace(/\\_/g, '_').trim();
49
+ const item = { from: whole, to: `\\field{${path}}`, line: lineAt(before, offset) };
50
+ if (!(0, path_1.isPath)(path)) {
51
+ skipped.push(item);
52
+ return whole;
53
+ }
54
+ converted.push(item);
55
+ return item.to;
56
+ });
57
+ return { tex: out, converted, skipped };
58
+ }
59
+ /** Make sure a document loads latex-kit.sty, right before \begin{document}. */
60
+ function ensureLatexKitPackage(tex) {
61
+ if (/\\usepackage\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/.test(tex))
62
+ return tex;
63
+ const at = tex.indexOf('\\begin{document}');
64
+ if (at === -1)
65
+ return tex;
66
+ return `${tex.slice(0, at)}\\usepackage{latex-kit}\n${tex.slice(at)}`;
67
+ }
package/compile.d.ts CHANGED
@@ -4,7 +4,10 @@ import { FieldSpec } from './filters';
4
4
  /**
5
5
  * The template language's macros and how many {…} arguments each takes.
6
6
  * Bare names keep templates readable; \snippet (not \partial, which is the
7
- * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
7
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
8
+ * inserts a numbered clause from the clause library; \clauseref prints its number.
9
+ * \signature prints a party's signature block; \component calls a TypeScript
10
+ * component with a value.
8
11
  */
9
12
  export declare const MACROS: {
10
13
  readonly field: 1;
@@ -15,7 +18,10 @@ export declare const MACROS: {
15
18
  readonly sep: 1;
16
19
  readonly snippet: 1;
17
20
  readonly docid: 0;
21
+ readonly clause: 1;
18
22
  readonly clauseref: 1;
23
+ readonly signature: 1;
24
+ readonly component: 2;
19
25
  };
20
26
  export type MacroName = keyof typeof MACROS;
21
27
  export type Node = {
@@ -51,6 +57,23 @@ export type Node = {
51
57
  } | {
52
58
  kind: 'docid';
53
59
  loc: Location;
60
+ } | {
61
+ kind: 'clause';
62
+ id: string;
63
+ loc: Location;
64
+ } | {
65
+ kind: 'clauseref';
66
+ id: string;
67
+ loc: Location;
68
+ } | {
69
+ kind: 'signature';
70
+ path: string;
71
+ loc: Location;
72
+ } | {
73
+ kind: 'component';
74
+ name: string;
75
+ path: string;
76
+ loc: Location;
54
77
  };
55
78
  export interface CompiledTemplate {
56
79
  file: string;
@@ -59,4 +82,6 @@ export interface CompiledTemplate {
59
82
  /** Syntax problems found while compiling. */
60
83
  diagnostics: Diagnostic[];
61
84
  }
85
+ /** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
86
+ export declare function isRelativeName(name: string): boolean;
62
87
  export declare function compileTemplate(text: string, file: string): CompiledTemplate;
package/compile.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MACROS = void 0;
4
+ exports.isRelativeName = isRelativeName;
4
5
  exports.compileTemplate = compileTemplate;
5
6
  const unified_latex_util_parse_1 = require("@unified-latex/unified-latex-util-parse");
6
7
  const condition_1 = require("./condition");
@@ -10,7 +11,10 @@ const path_1 = require("./path");
10
11
  /**
11
12
  * The template language's macros and how many {…} arguments each takes.
12
13
  * Bare names keep templates readable; \snippet (not \partial, which is the
13
- * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
14
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands. \clause
15
+ * inserts a numbered clause from the clause library; \clauseref prints its number.
16
+ * \signature prints a party's signature block; \component calls a TypeScript
17
+ * component with a value.
14
18
  */
15
19
  exports.MACROS = {
16
20
  field: 1,
@@ -21,11 +25,18 @@ exports.MACROS = {
21
25
  sep: 1,
22
26
  snippet: 1,
23
27
  docid: 0,
28
+ clause: 1,
24
29
  clauseref: 1,
30
+ signature: 1,
31
+ component: 2,
25
32
  };
26
33
  const parser = (0, unified_latex_util_parse_1.getParser)({
27
34
  macros: Object.fromEntries(Object.entries(exports.MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
28
35
  });
36
+ /** `parts/header`, `nda/confidentiality`: relative, no `..`, no empty segments. */
37
+ function isRelativeName(name) {
38
+ return /^[A-Za-z0-9_./-]+$/.test(name) && !name.split('/').some((s) => s === '..' || s === '' || s === '.');
39
+ }
29
40
  /** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
30
41
  function findMacros(text) {
31
42
  const out = [];
@@ -204,14 +215,18 @@ function compileTemplate(text, file) {
204
215
  pos = macroEnd;
205
216
  break;
206
217
  }
207
- case 'snippet': {
218
+ case 'snippet':
219
+ case 'clause': {
208
220
  const name = argText(0);
209
- if (!/^[A-Za-z0-9_\-./]+$/.test(name) || name.split('/').some((s) => s === '..' || s === '')) {
210
- diagnostics.push((0, diagnostics_1.diag)('error', `\\snippet{${name}}: use a relative name like parts/header`, loc));
221
+ if (!isRelativeName(name)) {
222
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\${occ.name}{${name}}: use a relative name like ${occ.name === 'clause' ? 'nda/confidentiality' : 'parts/header'}`, loc));
211
223
  }
212
- else {
224
+ else if (occ.name === 'snippet') {
213
225
  nodes.push({ kind: 'snippet', name, loc });
214
226
  }
227
+ else {
228
+ nodes.push({ kind: 'clause', id: name, loc });
229
+ }
215
230
  pos = macroEnd;
216
231
  break;
217
232
  }
@@ -221,10 +236,36 @@ function compileTemplate(text, file) {
221
236
  pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
222
237
  break;
223
238
  }
224
- case 'clauseref':
225
- diagnostics.push((0, diagnostics_1.diag)('error', '\\clauseref is reserved for the clause library, which is not available yet', loc));
239
+ case 'signature': {
240
+ const path = argText(0);
241
+ if (!(0, path_1.isPath)(path))
242
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\signature{${path}}: expected the path of a party, like discloser`, loc));
243
+ else
244
+ nodes.push({ kind: 'signature', path, loc });
245
+ pos = macroEnd;
246
+ break;
247
+ }
248
+ case 'component': {
249
+ const name = argText(0);
250
+ const path = argText(1);
251
+ if (!isRelativeName(name))
252
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\component{${name}}: use a name like line-items or tables/fees`, loc));
253
+ else if (path !== '' && !(0, path_1.isPath)(path))
254
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\component{${name}}{${path}}: invalid path (leave it empty for the whole record)`, loc));
255
+ else
256
+ nodes.push({ kind: 'component', name, path, loc });
226
257
  pos = macroEnd;
227
258
  break;
259
+ }
260
+ case 'clauseref': {
261
+ const id = argText(0);
262
+ if (!isRelativeName(id))
263
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\clauseref{${id}}: use the clause's name, like nda/confidentiality`, loc));
264
+ else
265
+ nodes.push({ kind: 'clauseref', id, loc });
266
+ pos = macroEnd;
267
+ break;
268
+ }
228
269
  }
229
270
  }
230
271
  catch (e) {
package/component.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { RawLatex } from '@latex-kit/escape';
2
+ /** What a component gets besides its value. */
3
+ export interface ComponentContext {
4
+ variant: 'draft' | 'blank' | 'final' | 'signed';
5
+ locale: string;
6
+ docId?: string;
7
+ template?: string;
8
+ /** The whole record's data. */
9
+ data: unknown;
10
+ /** The path the template passed (`\component{name}{path}`); '' for the whole record. */
11
+ path: string;
12
+ /**
13
+ * Format a value with the template filters, as `\field` does:
14
+ * `format(1200, 'money:USD')`, `format(d, 'date:long')`. Returns plain
15
+ * text; put it through `tex` (or escapeLatex) like any other value.
16
+ */
17
+ format(value: unknown, filters: string): string;
18
+ /** The signature block `\signature` prints for a party. */
19
+ signature(party: unknown, path?: string): RawLatex;
20
+ /** A red "missing" marker in drafts; an error in final and signed builds. */
21
+ missing(what: string): RawLatex;
22
+ }
23
+ /**
24
+ * A component turns a value into LaTeX: `\component{name}{path}` in a
25
+ * template calls it with the value at `path`. Return `tex`-tagged LaTeX
26
+ * (inserted as is) or a plain string (escaped).
27
+ */
28
+ export type Component = (value: unknown, ctx: ComponentContext) => RawLatex | string | number | null | undefined;
29
+ export declare function isRawLatex(v: unknown): v is RawLatex;
package/component.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRawLatex = isRawLatex;
4
+ const escape_1 = require("@latex-kit/escape");
5
+ function isRawLatex(v) {
6
+ return (v instanceof escape_1.RawLatex ||
7
+ (!!v && typeof v === 'object' && v.constructor?.name === 'RawLatex' && typeof v.value === 'string'));
8
+ }
package/esm/analyze.d.ts CHANGED
@@ -1,9 +1,10 @@
1
+ import { LoadedClause } from './clause';
1
2
  import { CompiledTemplate } from './compile';
2
3
  import { Diagnostic } from './diagnostics';
3
4
  import { JsonSchema } from './jsonschema';
4
5
  export interface FieldRef {
5
- /** How the template reads it: `field`, `raw`, `when`, `each`. */
6
- kind: 'field' | 'raw' | 'when' | 'each';
6
+ /** How the template reads it. */
7
+ kind: 'field' | 'raw' | 'when' | 'each' | 'signature' | 'component';
7
8
  /** The path as written, e.g. `item.price`. */
8
9
  path: string;
9
10
  /** The path from the data root, e.g. `items[].price`. */
@@ -17,10 +18,21 @@ export interface AnalyzeOptions {
17
18
  /** JSON Schema of the record's data. Without it only syntax is checked. */
18
19
  schema?: JsonSchema;
19
20
  loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
21
+ loadClause?: (id: string) => LoadedClause | null;
22
+ /** Names \component can use. Without it component names are not checked. */
23
+ components?: string[];
20
24
  }
21
25
  export interface AnalyzeResult {
22
26
  fields: FieldRef[];
23
27
  snippets: string[];
28
+ /** Library clauses the template can place, with versions. */
29
+ clauses: {
30
+ id: string;
31
+ version?: string;
32
+ file: string;
33
+ }[];
34
+ /** Components the template calls. */
35
+ components: string[];
24
36
  diagnostics: Diagnostic[];
25
37
  }
26
38
  /**
package/esm/analyze.js CHANGED
@@ -11,6 +11,9 @@ export function analyzeTemplate(template, options = {}) {
11
11
  const diagnostics = [...template.diagnostics];
12
12
  const fields = [];
13
13
  const snippets = [];
14
+ const clauses = [];
15
+ const components = [];
16
+ const refs = [];
14
17
  const stack = [template.file];
15
18
  const resolve = (path, scopes, loc) => {
16
19
  const [head, ...rest] = splitPath(path);
@@ -102,9 +105,58 @@ export function analyzeTemplate(template, options = {}) {
102
105
  stack.pop();
103
106
  break;
104
107
  }
108
+ case 'clause': {
109
+ const clause = options.loadClause?.(node.id) ?? null;
110
+ if (!clause) {
111
+ diagnostics.push(diag('error', `clause not found: ${node.id}`, node.loc));
112
+ break;
113
+ }
114
+ if (stack.includes(clause.template.file)) {
115
+ diagnostics.push(diag('error', `clause ${node.id} includes itself`, node.loc));
116
+ break;
117
+ }
118
+ if (!clauses.some((c) => c.id === node.id)) {
119
+ clauses.push({ id: node.id, version: clause.version, file: clause.template.file });
120
+ diagnostics.push(...clause.template.diagnostics);
121
+ if (!clause.title)
122
+ diagnostics.push(diag('warning', `clause ${node.id} has no "% title:" line, so it prints as a bare number`, { file: clause.template.file, line: 1, column: 1 }));
123
+ }
124
+ stack.push(clause.template.file);
125
+ walk(clause.template.nodes, scopes);
126
+ stack.pop();
127
+ break;
128
+ }
129
+ case 'clauseref':
130
+ refs.push({ id: node.id, loc: node.loc });
131
+ break;
132
+ case 'signature': {
133
+ const { absolute, schema } = resolve(node.path, scopes, node.loc);
134
+ fields.push({ kind: 'signature', path: node.path, absolute, filters: [], ...node.loc });
135
+ if (root && schema !== undefined && schemaAt(schema, ['name'], root) === undefined) {
136
+ diagnostics.push(diag('error', `\\signature{${node.path}}: ${absolute} has no name in the schema, so it is not a party or signer`, node.loc));
137
+ }
138
+ break;
139
+ }
140
+ case 'component': {
141
+ if (!components.includes(node.name))
142
+ components.push(node.name);
143
+ if (options.components && !options.components.includes(node.name)) {
144
+ diagnostics.push(diag('error', `unknown component ${node.name} (known: ${[...options.components].sort().join(', ') || 'none'})`, node.loc));
145
+ }
146
+ if (node.path) {
147
+ const { absolute } = resolve(node.path, scopes, node.loc);
148
+ fields.push({ kind: 'component', path: node.path, absolute, filters: [node.name], ...node.loc });
149
+ }
150
+ break;
151
+ }
105
152
  }
106
153
  }
107
154
  };
108
155
  walk(template.nodes, []);
109
- return { fields, snippets, diagnostics };
156
+ for (const r of refs) {
157
+ if (!clauses.some((c) => c.id === r.id)) {
158
+ diagnostics.push(diag('error', `\\clauseref{${r.id}}: the template never places \\clause{${r.id}}`, r.loc));
159
+ }
160
+ }
161
+ return { fields, snippets, clauses, components, diagnostics };
110
162
  }
@@ -0,0 +1,27 @@
1
+ import { CompiledTemplate } from './compile';
2
+ import type { Component } from './component';
3
+ export interface ClauseMeta {
4
+ title?: string;
5
+ version?: string;
6
+ }
7
+ /** A clause from the library, compiled, with its header. */
8
+ export interface LoadedClause extends ClauseMeta {
9
+ id: string;
10
+ /** The clause text (empty for a clause written as a TypeScript function). */
11
+ template: CompiledTemplate;
12
+ /** A TypeScript clause's body, called with the record's data. */
13
+ render?: Component;
14
+ }
15
+ export interface ClauseUse {
16
+ id: string;
17
+ version?: string;
18
+ file: string;
19
+ }
20
+ /**
21
+ * Read a clause file's header: the leading `%` comment lines.
22
+ *
23
+ * % title: Confidentiality
24
+ * % version: 3
25
+ */
26
+ export declare function parseClauseHeader(text: string): ClauseMeta;
27
+ export declare const clauseLabel: (id: string) => string;