@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/condition.js ADDED
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConditionError = void 0;
4
+ exports.parseCondition = parseCondition;
5
+ exports.truthy = truthy;
6
+ exports.evaluateCondition = evaluateCondition;
7
+ exports.conditionPaths = conditionPaths;
8
+ const path_1 = require("./path");
9
+ class ConditionError extends Error {
10
+ name = 'ConditionError';
11
+ }
12
+ exports.ConditionError = ConditionError;
13
+ function tokenize(src) {
14
+ const out = [];
15
+ let i = 0;
16
+ while (i < src.length) {
17
+ const ch = src[i];
18
+ if (/\s/.test(ch)) {
19
+ i++;
20
+ continue;
21
+ }
22
+ const two = src.slice(i, i + 2);
23
+ if (['&&', '||', '==', '!=', '<=', '>='].includes(two)) {
24
+ out.push({ t: 'op', v: two });
25
+ i += 2;
26
+ continue;
27
+ }
28
+ if ('!<>()'.includes(ch)) {
29
+ out.push({ t: 'op', v: ch });
30
+ i++;
31
+ continue;
32
+ }
33
+ if (ch === '"') {
34
+ let s = '';
35
+ i++;
36
+ while (i < src.length && src[i] !== '"') {
37
+ if (src[i] === '\\' && i + 1 < src.length)
38
+ i++;
39
+ s += src[i++];
40
+ }
41
+ if (src[i] !== '"')
42
+ throw new ConditionError('unterminated string');
43
+ i++;
44
+ out.push({ t: 'str', v: s });
45
+ continue;
46
+ }
47
+ const num = /^-?\d+(?:\.\d+)?/.exec(src.slice(i));
48
+ if (num) {
49
+ out.push({ t: 'num', v: Number(num[0]) });
50
+ i += num[0].length;
51
+ continue;
52
+ }
53
+ const word = /^\$?[A-Za-z_][A-Za-z0-9_]*(?:\.(?:[A-Za-z_][A-Za-z0-9_]*|\d+))*/.exec(src.slice(i));
54
+ if (word) {
55
+ out.push({ t: 'word', v: word[0] });
56
+ i += word[0].length;
57
+ continue;
58
+ }
59
+ if (ch === '=')
60
+ throw new ConditionError('use == to compare, not =');
61
+ if (ch === '&' || ch === '|')
62
+ throw new ConditionError(`use ${ch}${ch}, not ${ch}`);
63
+ throw new ConditionError(`unexpected "${ch}"`);
64
+ }
65
+ return out;
66
+ }
67
+ function parseCondition(src) {
68
+ const tokens = tokenize(src);
69
+ if (tokens.length === 0)
70
+ throw new ConditionError('empty condition');
71
+ let pos = 0;
72
+ const peek = () => tokens[pos];
73
+ const isOp = (v) => peek()?.t === 'op' && peek().v === v;
74
+ const primary = () => {
75
+ const tok = tokens[pos++];
76
+ if (!tok)
77
+ throw new ConditionError('condition ends too early');
78
+ if (tok.t === 'op' && tok.v === '(') {
79
+ const e = or();
80
+ if (!isOp(')'))
81
+ throw new ConditionError('missing )');
82
+ pos++;
83
+ return e;
84
+ }
85
+ if (tok.t === 'num')
86
+ return { type: 'literal', value: tok.v };
87
+ if (tok.t === 'str')
88
+ return { type: 'literal', value: tok.v };
89
+ if (tok.t === 'word') {
90
+ if (tok.v === 'true')
91
+ return { type: 'literal', value: true };
92
+ if (tok.v === 'false')
93
+ return { type: 'literal', value: false };
94
+ if (tok.v === 'null')
95
+ return { type: 'literal', value: null };
96
+ if (!(0, path_1.isPath)(tok.v))
97
+ throw new ConditionError(`invalid path ${tok.v}`);
98
+ return { type: 'path', path: tok.v };
99
+ }
100
+ throw new ConditionError(`unexpected "${tok.v}"`);
101
+ };
102
+ const compare = () => {
103
+ const left = primary();
104
+ const tok = peek();
105
+ if (tok?.t === 'op' && ['==', '!=', '<', '<=', '>', '>='].includes(tok.v)) {
106
+ pos++;
107
+ return { type: 'compare', op: tok.v, left, right: primary() };
108
+ }
109
+ return left;
110
+ };
111
+ const not = () => {
112
+ if (isOp('!')) {
113
+ pos++;
114
+ return { type: 'not', expr: not() };
115
+ }
116
+ return compare();
117
+ };
118
+ const and = () => {
119
+ let left = not();
120
+ while (isOp('&&')) {
121
+ pos++;
122
+ left = { type: 'and', left, right: not() };
123
+ }
124
+ return left;
125
+ };
126
+ const or = () => {
127
+ let left = and();
128
+ while (isOp('||')) {
129
+ pos++;
130
+ left = { type: 'or', left, right: and() };
131
+ }
132
+ return left;
133
+ };
134
+ const expr = or();
135
+ if (pos < tokens.length) {
136
+ const t = tokens[pos];
137
+ throw new ConditionError(`unexpected "${t.t === 'str' ? `"${t.v}"` : t.v}"`);
138
+ }
139
+ return expr;
140
+ }
141
+ function truthy(v) {
142
+ if (Array.isArray(v))
143
+ return v.length > 0;
144
+ return v !== undefined && v !== null && v !== false && v !== 0 && v !== '';
145
+ }
146
+ function evaluateCondition(expr, lookup) {
147
+ return truthy(value(expr, lookup));
148
+ }
149
+ function value(expr, lookup) {
150
+ switch (expr.type) {
151
+ case 'path':
152
+ return lookup(expr.path);
153
+ case 'literal':
154
+ return expr.value;
155
+ case 'not':
156
+ return !truthy(value(expr.expr, lookup));
157
+ case 'and':
158
+ return truthy(value(expr.left, lookup)) && truthy(value(expr.right, lookup));
159
+ case 'or':
160
+ return truthy(value(expr.left, lookup)) || truthy(value(expr.right, lookup));
161
+ case 'compare': {
162
+ const l = value(expr.left, lookup);
163
+ const r = value(expr.right, lookup);
164
+ switch (expr.op) {
165
+ case '==':
166
+ return (l ?? null) === (r ?? null);
167
+ case '!=':
168
+ return (l ?? null) !== (r ?? null);
169
+ default: {
170
+ // ordering only between two numbers or two strings; anything else is false
171
+ if (!((typeof l === 'number' && typeof r === 'number') || (typeof l === 'string' && typeof r === 'string')))
172
+ return false;
173
+ if (expr.op === '<')
174
+ return l < r;
175
+ if (expr.op === '<=')
176
+ return l <= r;
177
+ if (expr.op === '>')
178
+ return l > r;
179
+ return l >= r;
180
+ }
181
+ }
182
+ }
183
+ }
184
+ }
185
+ function conditionPaths(expr, out = []) {
186
+ switch (expr.type) {
187
+ case 'path':
188
+ out.push(expr.path);
189
+ break;
190
+ case 'not':
191
+ conditionPaths(expr.expr, out);
192
+ break;
193
+ case 'and':
194
+ case 'or':
195
+ case 'compare':
196
+ conditionPaths(expr.left, out);
197
+ conditionPaths(expr.right, out);
198
+ break;
199
+ }
200
+ return out;
201
+ }
@@ -0,0 +1,29 @@
1
+ export interface Location {
2
+ file: string;
3
+ line: number;
4
+ column: number;
5
+ }
6
+ export interface Diagnostic {
7
+ severity: 'error' | 'warning';
8
+ message: string;
9
+ file?: string;
10
+ line?: number;
11
+ column?: number;
12
+ }
13
+ export declare class TemplateError extends Error {
14
+ readonly diagnostics: Diagnostic[];
15
+ constructor(message: string, diagnostics: Diagnostic[]);
16
+ }
17
+ export declare function diag(severity: Diagnostic['severity'], message: string, loc?: Location): Diagnostic;
18
+ /** `file:line:col: error: message`, the format editors and CI annotate. */
19
+ export declare function formatDiagnostic(d: Diagnostic): string;
20
+ export declare function hasErrors(diagnostics: Diagnostic[]): boolean;
21
+ /** Maps string offsets to 1-based line and column. */
22
+ export declare class LineIndex {
23
+ private starts;
24
+ constructor(text: string);
25
+ locate(offset: number): {
26
+ line: number;
27
+ column: number;
28
+ };
29
+ }
package/diagnostics.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LineIndex = exports.TemplateError = void 0;
4
+ exports.diag = diag;
5
+ exports.formatDiagnostic = formatDiagnostic;
6
+ exports.hasErrors = hasErrors;
7
+ class TemplateError extends Error {
8
+ diagnostics;
9
+ constructor(message, diagnostics) {
10
+ super(message);
11
+ this.diagnostics = diagnostics;
12
+ this.name = 'TemplateError';
13
+ }
14
+ }
15
+ exports.TemplateError = TemplateError;
16
+ function diag(severity, message, loc) {
17
+ return loc ? { severity, message, file: loc.file, line: loc.line, column: loc.column } : { severity, message };
18
+ }
19
+ /** `file:line:col: error: message`, the format editors and CI annotate. */
20
+ function formatDiagnostic(d) {
21
+ const where = d.file ? `${d.file}${d.line ? `:${d.line}${d.column ? `:${d.column}` : ''}` : ''}: ` : '';
22
+ return `${where}${d.severity}: ${d.message}`;
23
+ }
24
+ function hasErrors(diagnostics) {
25
+ return diagnostics.some((d) => d.severity === 'error');
26
+ }
27
+ /** Maps string offsets to 1-based line and column. */
28
+ class LineIndex {
29
+ starts = [0];
30
+ constructor(text) {
31
+ for (let i = 0; i < text.length; i++)
32
+ if (text.charCodeAt(i) === 10)
33
+ this.starts.push(i + 1);
34
+ }
35
+ locate(offset) {
36
+ let lo = 0;
37
+ let hi = this.starts.length - 1;
38
+ while (lo < hi) {
39
+ const mid = (lo + hi + 1) >> 1;
40
+ if (this.starts[mid] <= offset)
41
+ lo = mid;
42
+ else
43
+ hi = mid - 1;
44
+ }
45
+ return { line: lo + 1, column: offset - this.starts[lo] + 1 };
46
+ }
47
+ }
48
+ exports.LineIndex = LineIndex;
package/document.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { Variant } from './evaluate';
2
+ export interface WrapOptions {
3
+ variant: Variant;
4
+ /** Short text printed on draft pages, e.g. date and git commit. */
5
+ stamp?: string;
6
+ }
7
+ /**
8
+ * Make a filled template ready for TeX: tell `latex-kit.sty` it is rendering
9
+ * a document (not previewing a template) and which variant, and load the
10
+ * package if the template did not.
11
+ *
12
+ * The settings go at the very start of line 1, so line numbers in TeX's
13
+ * errors still match the generated file line for line.
14
+ */
15
+ export declare function wrapDocument(tex: string, options: WrapOptions): string;
package/document.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wrapDocument = wrapDocument;
4
+ const escape_1 = require("@latex-kit/escape");
5
+ const USES_PACKAGE = /\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\])?\s*\{[^}]*\blatex-kit\b[^}]*\}/;
6
+ /**
7
+ * Make a filled template ready for TeX: tell `latex-kit.sty` it is rendering
8
+ * a document (not previewing a template) and which variant, and load the
9
+ * package if the template did not.
10
+ *
11
+ * The settings go at the very start of line 1, so line numbers in TeX's
12
+ * errors still match the generated file line for line.
13
+ */
14
+ function wrapDocument(tex, options) {
15
+ const stamp = options.stamp ? (0, escape_1.escapeLatex)(options.stamp) : '';
16
+ const prefix = `\\PassOptionsToPackage{rendered,${options.variant}}{latex-kit}\\def\\lkstamp{${stamp}}`;
17
+ let body = tex;
18
+ if (!USES_PACKAGE.test(body)) {
19
+ const at = body.indexOf('\\begin{document}');
20
+ if (at === -1)
21
+ throw new Error('the template has no \\begin{document}');
22
+ body = `${body.slice(0, at)}\\usepackage{latex-kit}${body.slice(at)}`;
23
+ }
24
+ return prefix + body;
25
+ }
@@ -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/esm/analyze.js ADDED
@@ -0,0 +1,110 @@
1
+ import { conditionPaths } from './condition';
2
+ import { diag } from './diagnostics';
3
+ import { ANY, itemSchema, schemaAt } from './jsonschema';
4
+ import { GLOBAL_SPECIALS, LOOP_SPECIALS, splitPath } from './path';
5
+ /**
6
+ * Static checks for a template: every path exists in the schema, \each walks
7
+ * a list, \raw is flagged, snippets resolve. Lists every field it reads.
8
+ */
9
+ export function analyzeTemplate(template, options = {}) {
10
+ const root = options.schema;
11
+ const diagnostics = [...template.diagnostics];
12
+ const fields = [];
13
+ const snippets = [];
14
+ const stack = [template.file];
15
+ const resolve = (path, scopes, loc) => {
16
+ const [head, ...rest] = splitPath(path);
17
+ if (head.startsWith('$')) {
18
+ if (LOOP_SPECIALS.includes(head)) {
19
+ if (scopes.length === 0)
20
+ diagnostics.push(diag('error', `${head} only works inside \\each`, loc));
21
+ }
22
+ else if (!GLOBAL_SPECIALS.includes(head)) {
23
+ diagnostics.push(diag('error', `unknown special value ${head} (known: ${[...GLOBAL_SPECIALS, ...LOOP_SPECIALS].join(', ')})`, loc));
24
+ }
25
+ if (rest.length)
26
+ diagnostics.push(diag('error', `${head} has no fields`, loc));
27
+ return { absolute: path, schema: ANY };
28
+ }
29
+ const scope = [...scopes].reverse().find((s) => s.name === head);
30
+ const absolute = scope ? [scope.absolute, ...rest].join('.') : path;
31
+ if (!root)
32
+ return { absolute, schema: ANY };
33
+ const base = scope ? scope.schema : root;
34
+ const segs = scope ? rest : [head, ...rest];
35
+ const found = base === undefined ? undefined : schemaAt(base, segs, root);
36
+ if (found === undefined && base !== undefined) {
37
+ diagnostics.push(diag('error', `unknown field ${absolute} (not in the template's schema)`, loc));
38
+ }
39
+ return { absolute, schema: found };
40
+ };
41
+ const walk = (nodes, scopes) => {
42
+ for (const node of nodes) {
43
+ switch (node.kind) {
44
+ case 'text':
45
+ case 'docid':
46
+ break;
47
+ case 'field': {
48
+ const { absolute } = resolve(node.spec.path, scopes, node.loc);
49
+ fields.push({
50
+ kind: node.raw ? 'raw' : 'field',
51
+ path: node.spec.path,
52
+ absolute,
53
+ filters: node.spec.filters.map((f) => (f.arg === undefined ? f.name : `${f.name}:${f.arg}`)),
54
+ ...node.loc,
55
+ });
56
+ if (node.raw) {
57
+ diagnostics.push(diag('warning', `\\raw{${node.spec.path}} inserts LaTeX unescaped; only use it for trusted values`, node.loc));
58
+ }
59
+ break;
60
+ }
61
+ case 'when':
62
+ for (const p of conditionPaths(node.cond)) {
63
+ const { absolute } = resolve(p, scopes, node.loc);
64
+ fields.push({ kind: 'when', path: p, absolute, filters: [], ...node.loc });
65
+ }
66
+ walk(node.then, scopes);
67
+ if (node.else)
68
+ walk(node.else, scopes);
69
+ break;
70
+ case 'each': {
71
+ const { absolute, schema } = resolve(node.path, scopes, node.loc);
72
+ fields.push({ kind: 'each', path: node.path, absolute, filters: [], ...node.loc });
73
+ let item = ANY;
74
+ if (root && schema !== undefined) {
75
+ item = itemSchema(schema, root);
76
+ if (item === undefined)
77
+ diagnostics.push(diag('error', `\\each{${node.path}}: ${absolute} is not a list in the schema`, node.loc));
78
+ }
79
+ walk(node.body, [...scopes, { name: node.name, absolute: `${absolute}[]`, schema: item }]);
80
+ break;
81
+ }
82
+ case 'sep':
83
+ walk(node.body, scopes);
84
+ break;
85
+ case 'snippet': {
86
+ const from = stack[stack.length - 1];
87
+ const snippet = options.loadSnippet?.(node.name, from) ?? null;
88
+ if (!snippet) {
89
+ diagnostics.push(diag('error', `snippet not found: ${node.name}`, node.loc));
90
+ break;
91
+ }
92
+ if (stack.includes(snippet.file)) {
93
+ diagnostics.push(diag('error', `snippet ${node.name} includes itself`, node.loc));
94
+ break;
95
+ }
96
+ if (!snippets.includes(snippet.file)) {
97
+ snippets.push(snippet.file);
98
+ diagnostics.push(...snippet.diagnostics);
99
+ }
100
+ stack.push(snippet.file);
101
+ walk(snippet.nodes, scopes);
102
+ stack.pop();
103
+ break;
104
+ }
105
+ }
106
+ }
107
+ };
108
+ walk(template.nodes, []);
109
+ return { fields, snippets, diagnostics };
110
+ }
@@ -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;