@latex-kit/template 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2026 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,121 @@
1
- # Temporary Holding Version
1
+ # @latex-kit/template
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml">
9
+ <img height="20" src="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/latex-kit/blob/main/LICENSE">
12
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
13
+ </a>
14
+ <a href="https://www.npmjs.com/package/@latex-kit/template">
15
+ <img height="20" src="https://img.shields.io/npm/v/@latex-kit/template.svg"/>
16
+ </a>
17
+ </p>
18
+
19
+ <p align="center">The latex-kit template language: fill-in macros inside real <code>.tex</code> files, checked and escaped.</p>
20
+
21
+ A latex-kit template is an ordinary LaTeX file with a few extra macros. It
22
+ opens in any LaTeX editor and, with `latex-kit.sty`, compiles on its own as
23
+ a blank form. latex-kit replaces only those macros: every other byte of the
24
+ file is kept exactly as written, and every value is escaped.
25
+
26
+ ```latex
27
+ \documentclass{article}
28
+ \usepackage{latex-kit}
29
+ \begin{document}
30
+ This Agreement is made on \field{effectiveDate|date:long} between
31
+ \field{discloser.name} and \field{recipient.name}.
32
+
33
+ \when{mutual}{Each party may disclose}\otherwise{The Discloser may disclose}
34
+ Confidential Information for \field{termMonths|words} (\field{termMonths}) months.
35
+
36
+ Fees: \each{fees}{fee}{\field{fee.label} \field{fee.amount|money:USD}\sep{; }}.
37
+
38
+ Document ID: \docid
39
+ \end{document}
40
+ ```
41
+
42
+ ## The language
43
+
44
+ | Macro | Does |
45
+ |---|---|
46
+ | `\field{path}` | Inserts a value, escaped. Paths use dots: `party.address.city`, `items.0.name` |
47
+ | `\field{path\|filter\|filter:arg}` | Runs filters left to right (see below) |
48
+ | `\raw{path}` | Inserts a value **unescaped**. `latex-kit check` warns on every use |
49
+ | `\when{condition}{…}\otherwise{…}` | Conditional. `\otherwise` is optional and may follow on the next line |
50
+ | `\each{list}{item}{…}` | Loop. Inside: `item`, `$index` (1-based), `$first`, `$last` |
51
+ | `\sep{…}` | Inside `\each`: printed between items, not after the last |
52
+ | `\snippet{name}` | Includes `name.tex` (next to the template, then `snippets/`) with the same data |
53
+ | `\docid` | The document's ID, minted once and stored on the record |
54
+
55
+ Special values: `$variant`, `$locale`, `$docid`, `$template`.
56
+
57
+ `\snippet` and `\clauseref` (reserved for the coming clause library) are
58
+ named so they never collide with LaTeX's `\partial` and `\ref`.
59
+
60
+ ### Conditions
61
+
62
+ A small, safe grammar, never `eval`:
63
+ `==` `!=` `<` `<=` `>` `>=`, `&&` `||` `!`, parentheses, paths, numbers,
64
+ `"strings"`, `true` `false` `null`. A missing path is false; an empty list
65
+ is false.
66
+
67
+ ```latex
68
+ \when{fee > 0 && !waived}{…}
69
+ \when{party.kind == "organization" || $variant == "blank"}{…}
70
+ ```
71
+
72
+ ### Filters
73
+
74
+ | Filter | Example | Output (en-US) |
75
+ |---|---|---|
76
+ | `date`, `date:long\|short\|medium\|full\|iso` | `2026-11-25` | November 25, 2026 |
77
+ | `money`, `money:USD` | `5400` or `{ amount, currency }` | $5,400.00 |
78
+ | `number`, `number:2` | `1234.5` | 1,234.50 |
79
+ | `percent`, `percent:1` | `0.15` | 15% |
80
+ | `words` | `24` | twenty-four |
81
+ | `upper`, `lower`, `title`, `trim` | | |
82
+ | `join`, `join:" and "` | `["a", "b"]` | a, b |
83
+ | `default:"text"` | missing | text |
84
+ | `lines`, `paragraphs` | multi-line text | keeps line / paragraph breaks |
85
+
86
+ Dates, numbers and money follow the record's locale (`ja-JP`, `de-DE`, …).
87
+
88
+ ### Variants
89
+
90
+ | Variant | Fields | Marks |
91
+ |---|---|---|
92
+ | `draft` | filled; a missing value prints a red `missing: path` box | DRAFT watermark, date and git commit |
93
+ | `blank` | every field is a labelled line | none |
94
+ | `final` | filled; a missing value is an error | none |
95
+ | `signed` | like `final`; test `$variant == "signed"` for signature text | none |
96
+
97
+ ## Usage
98
+
99
+ ```ts
100
+ import { analyzeTemplate, compileTemplate, evaluateTemplate, wrapDocument } from '@latex-kit/template';
101
+
102
+ const t = compileTemplate(source, 'templates/nda/template.tex');
103
+ const { tex, diagnostics } = evaluateTemplate(t, { data, variant: 'final', locale: 'en-US', docId });
104
+ const ready = wrapDocument(tex, { variant: 'final' });
105
+
106
+ // static checks against a JSON Schema of the data
107
+ const { fields, diagnostics: problems } = analyzeTemplate(t, { schema });
108
+ ```
109
+
110
+ Diagnostics carry `file`, `line` and `column`, formatted as
111
+ `templates/nda/template.tex:12:3: error: unknown field party.nmae`.
112
+
113
+ ## Credits
114
+
115
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
116
+
117
+ ## Disclaimer
118
+
119
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
120
+
121
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/analyze.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { CompiledTemplate } from './compile';
2
+ import { Diagnostic } from './diagnostics';
3
+ import { JsonSchema } from './jsonschema';
4
+ export interface FieldRef {
5
+ /** How the template reads it: `field`, `raw`, `when`, `each`. */
6
+ kind: 'field' | 'raw' | 'when' | 'each';
7
+ /** The path as written, e.g. `item.price`. */
8
+ path: string;
9
+ /** The path from the data root, e.g. `items[].price`. */
10
+ absolute: string;
11
+ filters: string[];
12
+ file: string;
13
+ line: number;
14
+ column: number;
15
+ }
16
+ export interface AnalyzeOptions {
17
+ /** JSON Schema of the record's data. Without it only syntax is checked. */
18
+ schema?: JsonSchema;
19
+ loadSnippet?: (name: string, from: string) => CompiledTemplate | null;
20
+ }
21
+ export interface AnalyzeResult {
22
+ fields: FieldRef[];
23
+ snippets: string[];
24
+ diagnostics: Diagnostic[];
25
+ }
26
+ /**
27
+ * Static checks for a template: every path exists in the schema, \each walks
28
+ * a list, \raw is flagged, snippets resolve. Lists every field it reads.
29
+ */
30
+ export declare function analyzeTemplate(template: CompiledTemplate, options?: AnalyzeOptions): AnalyzeResult;
package/analyze.js ADDED
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyzeTemplate = analyzeTemplate;
4
+ const condition_1 = require("./condition");
5
+ const diagnostics_1 = require("./diagnostics");
6
+ const jsonschema_1 = require("./jsonschema");
7
+ const path_1 = require("./path");
8
+ /**
9
+ * Static checks for a template: every path exists in the schema, \each walks
10
+ * a list, \raw is flagged, snippets resolve. Lists every field it reads.
11
+ */
12
+ function analyzeTemplate(template, options = {}) {
13
+ const root = options.schema;
14
+ const diagnostics = [...template.diagnostics];
15
+ const fields = [];
16
+ const snippets = [];
17
+ const stack = [template.file];
18
+ const resolve = (path, scopes, loc) => {
19
+ const [head, ...rest] = (0, path_1.splitPath)(path);
20
+ if (head.startsWith('$')) {
21
+ if (path_1.LOOP_SPECIALS.includes(head)) {
22
+ if (scopes.length === 0)
23
+ diagnostics.push((0, diagnostics_1.diag)('error', `${head} only works inside \\each`, loc));
24
+ }
25
+ else if (!path_1.GLOBAL_SPECIALS.includes(head)) {
26
+ diagnostics.push((0, diagnostics_1.diag)('error', `unknown special value ${head} (known: ${[...path_1.GLOBAL_SPECIALS, ...path_1.LOOP_SPECIALS].join(', ')})`, loc));
27
+ }
28
+ if (rest.length)
29
+ diagnostics.push((0, diagnostics_1.diag)('error', `${head} has no fields`, loc));
30
+ return { absolute: path, schema: jsonschema_1.ANY };
31
+ }
32
+ const scope = [...scopes].reverse().find((s) => s.name === head);
33
+ const absolute = scope ? [scope.absolute, ...rest].join('.') : path;
34
+ if (!root)
35
+ return { absolute, schema: jsonschema_1.ANY };
36
+ const base = scope ? scope.schema : root;
37
+ const segs = scope ? rest : [head, ...rest];
38
+ const found = base === undefined ? undefined : (0, jsonschema_1.schemaAt)(base, segs, root);
39
+ if (found === undefined && base !== undefined) {
40
+ diagnostics.push((0, diagnostics_1.diag)('error', `unknown field ${absolute} (not in the template's schema)`, loc));
41
+ }
42
+ return { absolute, schema: found };
43
+ };
44
+ const walk = (nodes, scopes) => {
45
+ for (const node of nodes) {
46
+ switch (node.kind) {
47
+ case 'text':
48
+ case 'docid':
49
+ break;
50
+ case 'field': {
51
+ const { absolute } = resolve(node.spec.path, scopes, node.loc);
52
+ fields.push({
53
+ kind: node.raw ? 'raw' : 'field',
54
+ path: node.spec.path,
55
+ absolute,
56
+ filters: node.spec.filters.map((f) => (f.arg === undefined ? f.name : `${f.name}:${f.arg}`)),
57
+ ...node.loc,
58
+ });
59
+ if (node.raw) {
60
+ diagnostics.push((0, diagnostics_1.diag)('warning', `\\raw{${node.spec.path}} inserts LaTeX unescaped; only use it for trusted values`, node.loc));
61
+ }
62
+ break;
63
+ }
64
+ case 'when':
65
+ for (const p of (0, condition_1.conditionPaths)(node.cond)) {
66
+ const { absolute } = resolve(p, scopes, node.loc);
67
+ fields.push({ kind: 'when', path: p, absolute, filters: [], ...node.loc });
68
+ }
69
+ walk(node.then, scopes);
70
+ if (node.else)
71
+ walk(node.else, scopes);
72
+ break;
73
+ case 'each': {
74
+ const { absolute, schema } = resolve(node.path, scopes, node.loc);
75
+ fields.push({ kind: 'each', path: node.path, absolute, filters: [], ...node.loc });
76
+ let item = jsonschema_1.ANY;
77
+ if (root && schema !== undefined) {
78
+ item = (0, jsonschema_1.itemSchema)(schema, root);
79
+ if (item === undefined)
80
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\each{${node.path}}: ${absolute} is not a list in the schema`, node.loc));
81
+ }
82
+ walk(node.body, [...scopes, { name: node.name, absolute: `${absolute}[]`, schema: item }]);
83
+ break;
84
+ }
85
+ case 'sep':
86
+ walk(node.body, scopes);
87
+ break;
88
+ case 'snippet': {
89
+ const from = stack[stack.length - 1];
90
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
91
+ if (!snippet) {
92
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet not found: ${node.name}`, node.loc));
93
+ break;
94
+ }
95
+ if (stack.includes(snippet.file)) {
96
+ diagnostics.push((0, diagnostics_1.diag)('error', `snippet ${node.name} includes itself`, node.loc));
97
+ break;
98
+ }
99
+ if (!snippets.includes(snippet.file)) {
100
+ snippets.push(snippet.file);
101
+ diagnostics.push(...snippet.diagnostics);
102
+ }
103
+ stack.push(snippet.file);
104
+ walk(snippet.nodes, scopes);
105
+ stack.pop();
106
+ break;
107
+ }
108
+ }
109
+ }
110
+ };
111
+ walk(template.nodes, []);
112
+ return { fields, snippets, diagnostics };
113
+ }
package/compile.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { Expr } from './condition';
2
+ import { Diagnostic, Location } from './diagnostics';
3
+ import { FieldSpec } from './filters';
4
+ /**
5
+ * The template language's macros and how many {…} arguments each takes.
6
+ * Bare names keep templates readable; \snippet (not \partial, which is the
7
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
8
+ */
9
+ export declare const MACROS: {
10
+ readonly field: 1;
11
+ readonly raw: 1;
12
+ readonly when: 2;
13
+ readonly otherwise: 1;
14
+ readonly each: 3;
15
+ readonly sep: 1;
16
+ readonly snippet: 1;
17
+ readonly docid: 0;
18
+ readonly clauseref: 1;
19
+ };
20
+ export type MacroName = keyof typeof MACROS;
21
+ export type Node = {
22
+ kind: 'text';
23
+ text: string;
24
+ } | {
25
+ kind: 'field';
26
+ spec: FieldSpec;
27
+ raw: boolean;
28
+ source: string;
29
+ loc: Location;
30
+ } | {
31
+ kind: 'when';
32
+ cond: Expr;
33
+ source: string;
34
+ then: Node[];
35
+ else?: Node[];
36
+ loc: Location;
37
+ } | {
38
+ kind: 'each';
39
+ path: string;
40
+ name: string;
41
+ body: Node[];
42
+ loc: Location;
43
+ } | {
44
+ kind: 'sep';
45
+ body: Node[];
46
+ loc: Location;
47
+ } | {
48
+ kind: 'snippet';
49
+ name: string;
50
+ loc: Location;
51
+ } | {
52
+ kind: 'docid';
53
+ loc: Location;
54
+ };
55
+ export interface CompiledTemplate {
56
+ file: string;
57
+ text: string;
58
+ nodes: Node[];
59
+ /** Syntax problems found while compiling. */
60
+ diagnostics: Diagnostic[];
61
+ }
62
+ export declare function compileTemplate(text: string, file: string): CompiledTemplate;
package/compile.js ADDED
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MACROS = void 0;
4
+ exports.compileTemplate = compileTemplate;
5
+ const unified_latex_util_parse_1 = require("@unified-latex/unified-latex-util-parse");
6
+ const condition_1 = require("./condition");
7
+ const diagnostics_1 = require("./diagnostics");
8
+ const filters_1 = require("./filters");
9
+ const path_1 = require("./path");
10
+ /**
11
+ * The template language's macros and how many {…} arguments each takes.
12
+ * Bare names keep templates readable; \snippet (not \partial, which is the
13
+ * math ∂) and \clauseref (not \ref) avoid LaTeX's own commands.
14
+ */
15
+ exports.MACROS = {
16
+ field: 1,
17
+ raw: 1,
18
+ when: 2,
19
+ otherwise: 1,
20
+ each: 3,
21
+ sep: 1,
22
+ snippet: 1,
23
+ docid: 0,
24
+ clauseref: 1,
25
+ };
26
+ const parser = (0, unified_latex_util_parse_1.getParser)({
27
+ macros: Object.fromEntries(Object.entries(exports.MACROS).map(([name, n]) => [name, { signature: Array(n).fill('m').join(' ') }])),
28
+ });
29
+ /** Find our macros with unified-latex, so comments, verbatim and \verb are skipped. */
30
+ function findMacros(text) {
31
+ const out = [];
32
+ const seen = new Set();
33
+ const walk = (node) => {
34
+ if (Array.isArray(node)) {
35
+ node.forEach(walk);
36
+ return;
37
+ }
38
+ if (!node || typeof node !== 'object')
39
+ return;
40
+ const n = node;
41
+ if (n.type === 'macro' && typeof n.content === 'string' && n.content in exports.MACROS && n.position) {
42
+ const start = n.position.start.offset;
43
+ if (!seen.has(start)) {
44
+ seen.add(start);
45
+ out.push({ name: n.content, start });
46
+ }
47
+ }
48
+ if (n.content && typeof n.content !== 'string')
49
+ walk(n.content);
50
+ if (n.args)
51
+ walk(n.args);
52
+ };
53
+ walk(parser.parse(text));
54
+ return out.sort((a, b) => a.start - b.start);
55
+ }
56
+ class SyntaxError extends Error {
57
+ offset;
58
+ constructor(message, offset) {
59
+ super(message);
60
+ this.offset = offset;
61
+ }
62
+ }
63
+ /** Skip spaces and at most one line break, as TeX does between arguments. */
64
+ function skipSpace(text, pos) {
65
+ let newlines = 0;
66
+ while (pos < text.length) {
67
+ const ch = text[pos];
68
+ if (ch === ' ' || ch === '\t' || ch === '\r')
69
+ pos++;
70
+ else if (ch === '\n' && newlines === 0) {
71
+ newlines++;
72
+ pos++;
73
+ }
74
+ else
75
+ break;
76
+ }
77
+ return pos;
78
+ }
79
+ /** Read `count` brace groups starting at `pos`. Returns the content ranges and the end. */
80
+ function readArgs(text, pos, count, macro) {
81
+ const args = [];
82
+ for (let i = 0; i < count; i++) {
83
+ const open = skipSpace(text, pos);
84
+ if (text[open] !== '{') {
85
+ throw new SyntaxError(`\\${macro} needs ${count} {…} argument${count > 1 ? 's' : ''}`, open);
86
+ }
87
+ let depth = 0;
88
+ let j = open;
89
+ for (; j < text.length; j++) {
90
+ const ch = text[j];
91
+ if (ch === '\\') {
92
+ j++;
93
+ }
94
+ else if (ch === '%') {
95
+ while (j < text.length && text[j] !== '\n')
96
+ j++;
97
+ }
98
+ else if (ch === '{') {
99
+ depth++;
100
+ }
101
+ else if (ch === '}') {
102
+ depth--;
103
+ if (depth === 0)
104
+ break;
105
+ }
106
+ }
107
+ if (depth !== 0)
108
+ throw new SyntaxError(`unbalanced braces in \\${macro}`, open);
109
+ args.push({ start: open + 1, end: j });
110
+ pos = j + 1;
111
+ }
112
+ return { args, end: pos };
113
+ }
114
+ function compileTemplate(text, file) {
115
+ const diagnostics = [];
116
+ const lines = new diagnostics_1.LineIndex(text);
117
+ const at = (offset) => ({ file, ...lines.locate(offset) });
118
+ let occurrences;
119
+ try {
120
+ occurrences = findMacros(text);
121
+ }
122
+ catch (e) {
123
+ diagnostics.push((0, diagnostics_1.diag)('error', `could not parse: ${e.message}`, at(0)));
124
+ return { file, text, nodes: [{ kind: 'text', text }], diagnostics };
125
+ }
126
+ let next = 0; // index into occurrences
127
+ const compileRange = (start, end, inEach) => {
128
+ const nodes = [];
129
+ let pos = start;
130
+ const pushText = (to) => {
131
+ if (to > pos)
132
+ nodes.push({ kind: 'text', text: text.slice(pos, to) });
133
+ };
134
+ while (next < occurrences.length && occurrences[next].start < end) {
135
+ const occ = occurrences[next++];
136
+ if (occ.start < pos)
137
+ continue; // inside an argument already consumed
138
+ pushText(occ.start);
139
+ const loc = at(occ.start);
140
+ const nameEnd = occ.start + 1 + occ.name.length;
141
+ pos = nameEnd;
142
+ try {
143
+ const { args, end: macroEnd } = readArgs(text, nameEnd, exports.MACROS[occ.name], occ.name);
144
+ const argText = (i) => text.slice(args[i].start, args[i].end).trim();
145
+ switch (occ.name) {
146
+ case 'field':
147
+ case 'raw': {
148
+ try {
149
+ nodes.push({ kind: 'field', spec: (0, filters_1.parseFieldSpec)(argText(0)), raw: occ.name === 'raw', source: argText(0), loc });
150
+ }
151
+ catch (e) {
152
+ if (!(e instanceof filters_1.FilterError))
153
+ throw e;
154
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\${occ.name}{${argText(0)}}: ${e.message}`, loc));
155
+ }
156
+ pos = macroEnd;
157
+ break;
158
+ }
159
+ case 'when': {
160
+ let cond = null;
161
+ try {
162
+ cond = (0, condition_1.parseCondition)(argText(0));
163
+ }
164
+ catch (e) {
165
+ if (!(e instanceof condition_1.ConditionError))
166
+ throw e;
167
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\when{${argText(0)}}: ${e.message}`, loc));
168
+ }
169
+ const thenNodes = compileRange(args[1].start, args[1].end, inEach);
170
+ pos = macroEnd;
171
+ let elseNodes;
172
+ const after = skipSpace(text, macroEnd);
173
+ const nextOcc = occurrences[next];
174
+ if (nextOcc && nextOcc.name === 'otherwise' && nextOcc.start === after) {
175
+ next++;
176
+ const o = readArgs(text, after + '\\otherwise'.length, 1, 'otherwise');
177
+ elseNodes = compileRange(o.args[0].start, o.args[0].end, inEach);
178
+ pos = o.end;
179
+ }
180
+ if (cond)
181
+ nodes.push({ kind: 'when', cond, source: argText(0), then: thenNodes, else: elseNodes, loc });
182
+ break;
183
+ }
184
+ case 'otherwise':
185
+ diagnostics.push((0, diagnostics_1.diag)('error', '\\otherwise must come right after \\when{…}{…}', loc));
186
+ pos = macroEnd;
187
+ break;
188
+ case 'each': {
189
+ const path = argText(0);
190
+ const name = argText(1);
191
+ if (!(0, path_1.isPath)(path))
192
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\each: invalid list path "${path}"`, loc));
193
+ if (!(0, path_1.isName)(name))
194
+ diagnostics.push((0, diagnostics_1.diag)('error', `\\each: invalid item name "${name}" (use a simple name like item)`, loc));
195
+ const body = compileRange(args[2].start, args[2].end, true);
196
+ nodes.push({ kind: 'each', path, name, body, loc });
197
+ pos = macroEnd;
198
+ break;
199
+ }
200
+ case 'sep': {
201
+ if (!inEach)
202
+ diagnostics.push((0, diagnostics_1.diag)('error', '\\sep only works inside \\each', loc));
203
+ nodes.push({ kind: 'sep', body: compileRange(args[0].start, args[0].end, inEach), loc });
204
+ pos = macroEnd;
205
+ break;
206
+ }
207
+ case 'snippet': {
208
+ 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));
211
+ }
212
+ else {
213
+ nodes.push({ kind: 'snippet', name, loc });
214
+ }
215
+ pos = macroEnd;
216
+ break;
217
+ }
218
+ case 'docid': {
219
+ nodes.push({ kind: 'docid', loc });
220
+ // allow \docid{} as in plain LaTeX usage
221
+ pos = text.startsWith('{}', macroEnd) ? macroEnd + 2 : macroEnd;
222
+ break;
223
+ }
224
+ case 'clauseref':
225
+ diagnostics.push((0, diagnostics_1.diag)('error', '\\clauseref is reserved for the clause library, which is not available yet', loc));
226
+ pos = macroEnd;
227
+ break;
228
+ }
229
+ }
230
+ catch (e) {
231
+ if (!(e instanceof SyntaxError))
232
+ throw e;
233
+ diagnostics.push((0, diagnostics_1.diag)('error', e.message, at(e.offset)));
234
+ }
235
+ }
236
+ pushText(end);
237
+ pos = end;
238
+ return nodes;
239
+ };
240
+ const nodes = compileRange(0, text.length, false);
241
+ return { file, text, nodes, diagnostics };
242
+ }
package/condition.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The condition language for \when{…}: a small, safe expression grammar.
3
+ * Never evaluated with eval.
4
+ *
5
+ * expr := or
6
+ * or := and ('||' and)*
7
+ * and := not ('&&' not)*
8
+ * not := '!' not | compare
9
+ * compare := primary (('==' | '!=' | '<' | '<=' | '>' | '>=') primary)?
10
+ * primary := path | number | "string" | true | false | null | '(' expr ')'
11
+ */
12
+ export type Expr = {
13
+ type: 'path';
14
+ path: string;
15
+ } | {
16
+ type: 'literal';
17
+ value: string | number | boolean | null;
18
+ } | {
19
+ type: 'not';
20
+ expr: Expr;
21
+ } | {
22
+ type: 'and' | 'or';
23
+ left: Expr;
24
+ right: Expr;
25
+ } | {
26
+ type: 'compare';
27
+ op: CompareOp;
28
+ left: Expr;
29
+ right: Expr;
30
+ };
31
+ export type CompareOp = '==' | '!=' | '<' | '<=' | '>' | '>=';
32
+ export declare class ConditionError extends Error {
33
+ name: string;
34
+ }
35
+ export declare function parseCondition(src: string): Expr;
36
+ export declare function truthy(v: unknown): boolean;
37
+ export declare function evaluateCondition(expr: Expr, lookup: (path: string) => unknown): boolean;
38
+ export declare function conditionPaths(expr: Expr, out?: string[]): string[];